running.rs

   1pub(crate) mod breakpoint_list;
   2pub(crate) mod console;
   3pub(crate) mod loaded_source_list;
   4pub(crate) mod memory_view;
   5pub(crate) mod module_list;
   6pub mod stack_frame_list;
   7pub mod variable_list;
   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    session::running::memory_view::MemoryView,
  15};
  16
  17use super::DebugPanelItemEvent;
  18use anyhow::{Context as _, Result, anyhow};
  19use breakpoint_list::BreakpointList;
  20use collections::{HashMap, IndexMap};
  21use console::Console;
  22use dap::{
  23    Capabilities, DapRegistry, RunInTerminalRequestArguments, Thread,
  24    adapters::{DebugAdapterName, DebugTaskDefinition},
  25    client::SessionId,
  26    debugger_settings::DebuggerSettings,
  27};
  28use futures::{SinkExt, channel::mpsc};
  29use gpui::{
  30    Action as _, AnyView, AppContext, Axis, Entity, EntityId, EventEmitter, FocusHandle, Focusable,
  31    NoAction, Pixels, Point, Subscription, Task, WeakEntity,
  32};
  33use language::Buffer;
  34use loaded_source_list::LoadedSourceList;
  35use module_list::ModuleList;
  36use project::{
  37    DebugScenarioContext, Project, WorktreeId,
  38    debugger::session::{self, Session, SessionEvent, SessionStateEvent, ThreadId, ThreadStatus},
  39    terminals::TerminalKind,
  40};
  41use rpc::proto::ViewId;
  42use serde_json::Value;
  43use settings::Settings;
  44use stack_frame_list::StackFrameList;
  45use task::{
  46    BuildTaskDefinition, DebugScenario, ShellBuilder, SpawnInTerminal, TaskContext, ZedDebugConfig,
  47    substitute_variables_in_str,
  48};
  49use terminal_view::TerminalView;
  50use ui::{
  51    FluentBuilder, IntoElement, Render, StatefulInteractiveElement, Tab, Tooltip, VisibleOnHover,
  52    VisualContext, prelude::*,
  53};
  54use util::ResultExt;
  55use variable_list::VariableList;
  56use workspace::{
  57    ActivePaneDecorator, DraggedTab, Item, ItemHandle, Member, Pane, PaneGroup, SplitDirection,
  58    Workspace, item::TabContentParams, move_item, pane::Event,
  59};
  60
  61pub struct RunningState {
  62    session: Entity<Session>,
  63    thread_id: Option<ThreadId>,
  64    focus_handle: FocusHandle,
  65    _remote_id: Option<ViewId>,
  66    workspace: WeakEntity<Workspace>,
  67    session_id: SessionId,
  68    variable_list: Entity<variable_list::VariableList>,
  69    _subscriptions: Vec<Subscription>,
  70    stack_frame_list: Entity<stack_frame_list::StackFrameList>,
  71    loaded_sources_list: Entity<LoadedSourceList>,
  72    pub debug_terminal: Entity<DebugTerminal>,
  73    module_list: Entity<module_list::ModuleList>,
  74    console: Entity<Console>,
  75    breakpoint_list: Entity<BreakpointList>,
  76    panes: PaneGroup,
  77    active_pane: Entity<Pane>,
  78    pane_close_subscriptions: HashMap<EntityId, Subscription>,
  79    dock_axis: Axis,
  80    _schedule_serialize: Option<Task<()>>,
  81    pub(crate) scenario: Option<DebugScenario>,
  82    pub(crate) scenario_context: Option<DebugScenarioContext>,
  83    memory_view: Entity<MemoryView>,
  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(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,
 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();
 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    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                    .is_some_and(|item| item.read(cx).hovered);
 418
 419                h_flex()
 420                    .track_focus(&focus_handle)
 421                    .group(pane_group_id.clone())
 422                    .pl_1p5()
 423                    .pr_1()
 424                    .justify_between()
 425                    .border_b_1()
 426                    .border_color(cx.theme().colors().border)
 427                    .bg(cx.theme().colors().tab_bar_background)
 428                    .on_action(|_: &menu::Cancel, window, cx| {
 429                        if cx.stop_active_drag(window) {
 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                                    .is_some_and(|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(),
 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
 516                        h_flex()
 517                            .visible_on_hover(pane_group_id)
 518                            .when(is_hovered, |this| this.visible())
 519                            .when_some(as_subview.as_ref(), |this, subview| {
 520                                subview.update(cx, |view, cx| {
 521                                    let Some(additional_actions) = view.actions.as_mut() else {
 522                                        return this;
 523                                    };
 524                                    this.child(additional_actions(window, cx))
 525                                })
 526                            })
 527                            .child(
 528                                IconButton::new(
 529                                    SharedString::from(format!(
 530                                        "debug-toggle-zoom-{}",
 531                                        cx.entity_id()
 532                                    )),
 533                                    if zoomed {
 534                                        IconName::Minimize
 535                                    } else {
 536                                        IconName::Maximize
 537                                    },
 538                                )
 539                                .icon_size(IconSize::Small)
 540                                .on_click(cx.listener(move |pane, _, _, cx| {
 541                                    let is_zoomed = pane.is_zoomed();
 542                                    pane.set_zoomed(!is_zoomed, cx);
 543                                    cx.notify();
 544                                }))
 545                                .tooltip({
 546                                    let focus_handle = focus_handle.clone();
 547                                    move |window, cx| {
 548                                        let zoomed_text =
 549                                            if zoomed { "Minimize" } else { "Expand" };
 550                                        Tooltip::for_action_in(
 551                                            zoomed_text,
 552                                            &ToggleExpandItem,
 553                                            &focus_handle,
 554                                            window,
 555                                            cx,
 556                                        )
 557                                    }
 558                                }),
 559                            )
 560                    })
 561                    .into_any_element()
 562            }
 563        });
 564        pane
 565    })
 566}
 567
 568pub struct DebugTerminal {
 569    pub terminal: Option<Entity<TerminalView>>,
 570    focus_handle: FocusHandle,
 571    _subscriptions: [Subscription; 1],
 572}
 573
 574impl DebugTerminal {
 575    fn empty(window: &mut Window, cx: &mut Context<Self>) -> Self {
 576        let focus_handle = cx.focus_handle();
 577        let focus_subscription = cx.on_focus(&focus_handle, window, |this, window, cx| {
 578            if let Some(terminal) = this.terminal.as_ref() {
 579                terminal.focus_handle(cx).focus(window);
 580            }
 581        });
 582
 583        Self {
 584            terminal: None,
 585            focus_handle,
 586            _subscriptions: [focus_subscription],
 587        }
 588    }
 589}
 590
 591impl gpui::Render for DebugTerminal {
 592    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 593        div()
 594            .track_focus(&self.focus_handle)
 595            .size_full()
 596            .bg(cx.theme().colors().editor_background)
 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(
 680                workspace.clone(),
 681                session.clone(),
 682                weak_state.clone(),
 683                window,
 684                cx,
 685            )
 686        });
 687
 688        let debug_terminal =
 689            parent_terminal.unwrap_or_else(|| cx.new(|cx| DebugTerminal::empty(window, cx)));
 690        let memory_view = cx.new(|cx| {
 691            MemoryView::new(
 692                session.clone(),
 693                workspace.clone(),
 694                stack_frame_list.downgrade(),
 695                window,
 696                cx,
 697            )
 698        });
 699        let variable_list = cx.new(|cx| {
 700            VariableList::new(
 701                session.clone(),
 702                stack_frame_list.clone(),
 703                memory_view.clone(),
 704                weak_state.clone(),
 705                window,
 706                cx,
 707            )
 708        });
 709
 710        let module_list = cx.new(|cx| ModuleList::new(session.clone(), workspace.clone(), cx));
 711
 712        let loaded_source_list = cx.new(|cx| LoadedSourceList::new(session.clone(), cx));
 713
 714        let console = cx.new(|cx| {
 715            Console::new(
 716                session.clone(),
 717                stack_frame_list.clone(),
 718                variable_list.clone(),
 719                window,
 720                cx,
 721            )
 722        });
 723
 724        let breakpoint_list = BreakpointList::new(
 725            Some(session.clone()),
 726            workspace.clone(),
 727            &project,
 728            window,
 729            cx,
 730        );
 731
 732        let _subscriptions = vec![
 733            cx.on_app_quit(move |this, cx| {
 734                let shutdown = this
 735                    .session
 736                    .update(cx, |session, cx| session.on_app_quit(cx));
 737                let terminal = this.debug_terminal.clone();
 738                async move {
 739                    shutdown.await;
 740                    drop(terminal)
 741                }
 742            }),
 743            cx.observe(&module_list, |_, _, cx| cx.notify()),
 744            cx.subscribe_in(&session, window, |this, _, event, window, cx| {
 745                match event {
 746                    SessionEvent::Stopped(thread_id) => {
 747                        let panel = this
 748                            .workspace
 749                            .update(cx, |workspace, cx| {
 750                                workspace.open_panel::<crate::DebugPanel>(window, cx);
 751                                workspace.panel::<crate::DebugPanel>(cx)
 752                            })
 753                            .log_err()
 754                            .flatten();
 755
 756                        if let Some(thread_id) = thread_id {
 757                            this.select_thread(*thread_id, window, cx);
 758                        }
 759                        if let Some(panel) = panel {
 760                            let id = this.session_id;
 761                            window.defer(cx, move |window, cx| {
 762                                panel.update(cx, |this, cx| {
 763                                    this.activate_session_by_id(id, window, cx);
 764                                })
 765                            })
 766                        }
 767                    }
 768                    SessionEvent::Threads => {
 769                        let threads = this.session.update(cx, |this, cx| this.threads(cx));
 770                        this.select_current_thread(&threads, window, cx);
 771                    }
 772                    SessionEvent::CapabilitiesLoaded => {
 773                        let capabilities = this.capabilities(cx);
 774                        if !capabilities.supports_modules_request.unwrap_or(false) {
 775                            this.remove_pane_item(DebuggerPaneItem::Modules, window, cx);
 776                        }
 777                        if !capabilities
 778                            .supports_loaded_sources_request
 779                            .unwrap_or(false)
 780                        {
 781                            this.remove_pane_item(DebuggerPaneItem::LoadedSources, window, cx);
 782                        }
 783                    }
 784                    SessionEvent::RunInTerminal { request, sender } => this
 785                        .handle_run_in_terminal(request, sender.clone(), window, cx)
 786                        .detach_and_log_err(cx),
 787
 788                    _ => {}
 789                }
 790                cx.notify()
 791            }),
 792            cx.on_focus_out(&focus_handle, window, |this, _, window, cx| {
 793                this.serialize_layout(window, cx);
 794            }),
 795            cx.subscribe(
 796                &session,
 797                |this, session, event: &SessionStateEvent, cx| match event {
 798                    SessionStateEvent::Shutdown if session.read(cx).is_building() => {
 799                        this.shutdown(cx);
 800                    }
 801                    _ => {}
 802                },
 803            ),
 804        ];
 805
 806        let mut pane_close_subscriptions = HashMap::default();
 807        let panes = if let Some(root) = serialized_pane_layout.and_then(|serialized_layout| {
 808            persistence::deserialize_pane_layout(
 809                serialized_layout.panes,
 810                dock_axis != serialized_layout.dock_axis,
 811                &workspace,
 812                &project,
 813                &stack_frame_list,
 814                &variable_list,
 815                &module_list,
 816                &console,
 817                &breakpoint_list,
 818                &loaded_source_list,
 819                &debug_terminal,
 820                &memory_view,
 821                &mut pane_close_subscriptions,
 822                window,
 823                cx,
 824            )
 825        }) {
 826            workspace::PaneGroup::with_root(root)
 827        } else {
 828            pane_close_subscriptions.clear();
 829
 830            let root = Self::default_pane_layout(
 831                project,
 832                &workspace,
 833                &stack_frame_list,
 834                &variable_list,
 835                &console,
 836                &breakpoint_list,
 837                &debug_terminal,
 838                dock_axis,
 839                &mut pane_close_subscriptions,
 840                window,
 841                cx,
 842            );
 843
 844            workspace::PaneGroup::with_root(root)
 845        };
 846        let active_pane = panes.first_pane();
 847
 848        Self {
 849            memory_view,
 850            session,
 851            workspace,
 852            focus_handle,
 853            variable_list,
 854            _subscriptions,
 855            thread_id: None,
 856            _remote_id: None,
 857            stack_frame_list,
 858            session_id,
 859            panes,
 860            active_pane,
 861            module_list,
 862            console,
 863            breakpoint_list,
 864            loaded_sources_list: loaded_source_list,
 865            pane_close_subscriptions,
 866            debug_terminal,
 867            dock_axis,
 868            _schedule_serialize: None,
 869            scenario: None,
 870            scenario_context: None,
 871        }
 872    }
 873
 874    pub(crate) fn remove_pane_item(
 875        &mut self,
 876        item_kind: DebuggerPaneItem,
 877        window: &mut Window,
 878        cx: &mut Context<Self>,
 879    ) {
 880        if let Some((pane, item_id)) = self.panes.panes().iter().find_map(|pane| {
 881            Some(pane).zip(
 882                pane.read(cx)
 883                    .items()
 884                    .find(|item| {
 885                        item.act_as::<SubView>(cx)
 886                            .is_some_and(|view| view.read(cx).kind == item_kind)
 887                    })
 888                    .map(|item| item.item_id()),
 889            )
 890        }) {
 891            pane.update(cx, |pane, cx| {
 892                pane.remove_item(item_id, false, true, window, cx)
 893            })
 894        }
 895    }
 896
 897    pub(crate) fn has_pane_at_position(&self, position: Point<Pixels>) -> bool {
 898        self.panes.pane_at_pixel_position(position).is_some()
 899    }
 900
 901    pub(crate) fn resolve_scenario(
 902        &self,
 903        scenario: DebugScenario,
 904        task_context: TaskContext,
 905        buffer: Option<Entity<Buffer>>,
 906        worktree_id: Option<WorktreeId>,
 907        window: &Window,
 908        cx: &mut Context<Self>,
 909    ) -> Task<Result<DebugTaskDefinition>> {
 910        let Some(workspace) = self.workspace.upgrade() else {
 911            return Task::ready(Err(anyhow!("no workspace")));
 912        };
 913        let project = workspace.read(cx).project().clone();
 914        let dap_store = project.read(cx).dap_store().downgrade();
 915        let dap_registry = cx.global::<DapRegistry>().clone();
 916        let task_store = project.read(cx).task_store().downgrade();
 917        let weak_project = project.downgrade();
 918        let weak_workspace = workspace.downgrade();
 919        let ssh_info = project
 920            .read(cx)
 921            .ssh_client()
 922            .and_then(|it| it.read(cx).ssh_info());
 923
 924        cx.spawn_in(window, async move |this, cx| {
 925            let DebugScenario {
 926                adapter,
 927                label,
 928                build,
 929                mut config,
 930                tcp_connection,
 931            } = scenario;
 932            Self::relativize_paths(None, &mut config, &task_context);
 933            Self::substitute_variables_in_config(&mut config, &task_context);
 934
 935            let request_type = match dap_registry
 936                .adapter(&adapter)
 937                .with_context(|| format!("{}: is not a valid adapter name", &adapter)) {
 938                    Ok(adapter) => adapter.request_kind(&config).await,
 939                    Err(e) => Err(e)
 940                };
 941
 942
 943            let config_is_valid = request_type.is_ok();
 944            let mut extra_config = Value::Null;
 945            let build_output = if let Some(build) = build {
 946                let (task_template, locator_name) = match build {
 947                    BuildTaskDefinition::Template {
 948                        task_template,
 949                        locator_name,
 950                    } => (task_template, locator_name),
 951                    BuildTaskDefinition::ByName(ref label) => {
 952                        let task = task_store.update(cx, |this, cx| {
 953                            this.task_inventory().map(|inventory| {
 954                                inventory.read(cx).task_template_by_label(
 955                                    buffer,
 956                                    worktree_id,
 957                                    label,
 958                                    cx,
 959                                )
 960                            })
 961                        })?;
 962                        let task = match task {
 963                            Some(task) => task.await,
 964                            None => None,
 965                        }.with_context(|| format!("Couldn't find task template for {build:?}"))?;
 966                        (task, None)
 967                    }
 968                };
 969                let Some(task) = task_template.resolve_task("debug-build-task", &task_context) else {
 970                    anyhow::bail!("Could not resolve task variables within a debug scenario");
 971                };
 972
 973                let locator_name = if let Some(locator_name) = locator_name {
 974                    extra_config = config.clone();
 975                    debug_assert!(!config_is_valid);
 976                    Some(locator_name)
 977                } else if !config_is_valid {
 978                    let task = dap_store
 979                        .update(cx, |this, cx| {
 980                            this.debug_scenario_for_build_task(
 981                                task.original_task().clone(),
 982                                adapter.clone().into(),
 983                                task.display_label().to_owned().into(),
 984                                cx,
 985                            )
 986
 987                        });
 988                    if let Ok(t) = task {
 989                        t.await.and_then(|scenario| {
 990                            extra_config = scenario.config;
 991                            match scenario.build {
 992                                Some(BuildTaskDefinition::Template {
 993                                    locator_name, ..
 994                                }) => locator_name,
 995                                _ => None,
 996                            }
 997                        })
 998                    } else {
 999                        None
1000                    }
1001
1002                } else {
1003                    None
1004                };
1005
1006                let builder = ShellBuilder::new(ssh_info.as_ref().map(|info| &*info.shell), &task.resolved.shell);
1007                let command_label = builder.command_label(&task.resolved.command_label);
1008                let (command, args) =
1009                    builder.build(task.resolved.command.clone(), &task.resolved.args);
1010
1011                let task_with_shell = SpawnInTerminal {
1012                    command_label,
1013                    command: Some(command),
1014                    args,
1015                    ..task.resolved.clone()
1016                };
1017                let terminal = project
1018                    .update(cx, |project, cx| {
1019                        project.create_terminal(
1020                            TerminalKind::Task(task_with_shell.clone()),
1021                            cx,
1022                        )
1023                    })?
1024                    .await?;
1025
1026                let terminal_view = cx.new_window_entity(|window, cx| {
1027                    TerminalView::new(
1028                        terminal.clone(),
1029                        weak_workspace,
1030                        None,
1031                        weak_project,
1032                        window,
1033                        cx,
1034                    )
1035                })?;
1036
1037                this.update_in(cx, |this, window, cx| {
1038                    this.ensure_pane_item(DebuggerPaneItem::Terminal, window, cx);
1039                    this.debug_terminal.update(cx, |debug_terminal, cx| {
1040                        debug_terminal.terminal = Some(terminal_view);
1041                        cx.notify();
1042                    });
1043                })?;
1044
1045                let exit_status = terminal
1046                    .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))?
1047                    .await
1048                    .context("Failed to wait for completed task")?;
1049
1050                if !exit_status.success() {
1051                    anyhow::bail!("Build failed");
1052                }
1053                Some((task.resolved.clone(), locator_name, extra_config))
1054            } else {
1055                None
1056            };
1057
1058            if config_is_valid {
1059            } else if let Some((task, locator_name, extra_config)) = build_output {
1060                let locator_name =
1061                    locator_name.with_context(|| {
1062                        format!("Could not find a valid locator for a build task and configure is invalid with error: {}", request_type.err()
1063                            .map(|err| err.to_string())
1064                            .unwrap_or_default())
1065                    })?;
1066                let request = dap_store
1067                    .update(cx, |this, cx| {
1068                        this.run_debug_locator(&locator_name, task, cx)
1069                    })?
1070                    .await?;
1071
1072                let zed_config = ZedDebugConfig {
1073                    label: label.clone(),
1074                    adapter: adapter.clone(),
1075                    request,
1076                    stop_on_entry: None,
1077                };
1078
1079                let scenario = dap_registry
1080                    .adapter(&adapter)
1081                    .with_context(|| anyhow!("{}: is not a valid adapter name", &adapter))?.config_from_zed_format(zed_config)
1082                    .await?;
1083                config = scenario.config;
1084                util::merge_non_null_json_value_into(extra_config, &mut config);
1085
1086                Self::substitute_variables_in_config(&mut config, &task_context);
1087            } else {
1088                let Err(e) = request_type else {
1089                    unreachable!();
1090                };
1091                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}");
1092            };
1093
1094            Ok(DebugTaskDefinition {
1095                label,
1096                adapter: DebugAdapterName(adapter),
1097                config,
1098                tcp_connection,
1099            })
1100        })
1101    }
1102
1103    fn handle_run_in_terminal(
1104        &self,
1105        request: &RunInTerminalRequestArguments,
1106        mut sender: mpsc::Sender<Result<u32>>,
1107        window: &mut Window,
1108        cx: &mut Context<Self>,
1109    ) -> Task<Result<()>> {
1110        let running = cx.entity();
1111        let Ok(project) = self
1112            .workspace
1113            .read_with(cx, |workspace, _| workspace.project().clone())
1114        else {
1115            return Task::ready(Err(anyhow!("no workspace")));
1116        };
1117        let session = self.session.read(cx);
1118
1119        let cwd = (!request.cwd.is_empty())
1120            .then(|| PathBuf::from(&request.cwd))
1121            .or_else(|| session.binary().unwrap().cwd.clone());
1122
1123        let mut envs: HashMap<String, String> =
1124            self.session.read(cx).task_context().project_env.clone();
1125        if let Some(Value::Object(env)) = &request.env {
1126            for (key, value) in env {
1127                let value_str = match (key.as_str(), value) {
1128                    (_, Value::String(value)) => value,
1129                    _ => continue,
1130                };
1131
1132                envs.insert(key.clone(), value_str.clone());
1133            }
1134        }
1135
1136        let mut args = request.args.clone();
1137        let command = if envs.contains_key("VSCODE_INSPECTOR_OPTIONS") {
1138            // Handle special case for NodeJS debug adapter
1139            // If the Node binary path is provided (possibly with arguments like --experimental-network-inspection),
1140            // we set the command to None
1141            // This prevents the NodeJS REPL from appearing, which is not the desired behavior
1142            // The expected usage is for users to provide their own Node command, e.g., `node test.js`
1143            // This allows the NodeJS debug client to attach correctly
1144            if args
1145                .iter()
1146                .filter(|arg| !arg.starts_with("--"))
1147                .collect::<Vec<_>>()
1148                .len()
1149                > 1
1150            {
1151                Some(args.remove(0))
1152            } else {
1153                None
1154            }
1155        } else if !args.is_empty() {
1156            Some(args.remove(0))
1157        } else {
1158            None
1159        };
1160
1161        let shell = project.read(cx).terminal_settings(&cwd, cx).shell.clone();
1162        let title = request
1163            .title
1164            .clone()
1165            .filter(|title| !title.is_empty())
1166            .or_else(|| command.clone())
1167            .unwrap_or_else(|| "Debug terminal".to_string());
1168        let kind = TerminalKind::Task(task::SpawnInTerminal {
1169            id: task::TaskId("debug".to_string()),
1170            full_label: title.clone(),
1171            label: title.clone(),
1172            command,
1173            args,
1174            command_label: title,
1175            cwd,
1176            env: envs,
1177            use_new_terminal: true,
1178            allow_concurrent_runs: true,
1179            reveal: task::RevealStrategy::NoFocus,
1180            reveal_target: task::RevealTarget::Dock,
1181            hide: task::HideStrategy::Never,
1182            shell,
1183            show_summary: false,
1184            show_command: false,
1185            show_rerun: false,
1186        });
1187
1188        let workspace = self.workspace.clone();
1189        let weak_project = project.downgrade();
1190
1191        let terminal_task = project.update(cx, |project, cx| project.create_terminal(kind, cx));
1192        let terminal_task = cx.spawn_in(window, async move |_, cx| {
1193            let terminal = terminal_task.await?;
1194
1195            let terminal_view = cx.new_window_entity(|window, cx| {
1196                TerminalView::new(terminal.clone(), workspace, None, weak_project, window, cx)
1197            })?;
1198
1199            running.update_in(cx, |running, window, cx| {
1200                running.ensure_pane_item(DebuggerPaneItem::Terminal, window, cx);
1201                running.debug_terminal.update(cx, |debug_terminal, cx| {
1202                    debug_terminal.terminal = Some(terminal_view);
1203                    cx.notify();
1204                });
1205            })?;
1206
1207            terminal.read_with(cx, |terminal, _| {
1208                terminal
1209                    .pty_info
1210                    .pid()
1211                    .map(|pid| pid.as_u32())
1212                    .context("Terminal was spawned but PID was not available")
1213            })?
1214        });
1215
1216        cx.background_spawn(async move { anyhow::Ok(sender.send(terminal_task.await).await?) })
1217    }
1218
1219    fn create_sub_view(
1220        &self,
1221        item_kind: DebuggerPaneItem,
1222        _pane: &Entity<Pane>,
1223        cx: &mut Context<Self>,
1224    ) -> Box<dyn ItemHandle> {
1225        match item_kind {
1226            DebuggerPaneItem::Console => Box::new(SubView::console(self.console.clone(), cx)),
1227            DebuggerPaneItem::Variables => Box::new(SubView::new(
1228                self.variable_list.focus_handle(cx),
1229                self.variable_list.clone().into(),
1230                item_kind,
1231                cx,
1232            )),
1233            DebuggerPaneItem::BreakpointList => {
1234                Box::new(SubView::breakpoint_list(self.breakpoint_list.clone(), cx))
1235            }
1236            DebuggerPaneItem::Frames => Box::new(SubView::new(
1237                self.stack_frame_list.focus_handle(cx),
1238                self.stack_frame_list.clone().into(),
1239                item_kind,
1240                cx,
1241            )),
1242            DebuggerPaneItem::Modules => Box::new(SubView::new(
1243                self.module_list.focus_handle(cx),
1244                self.module_list.clone().into(),
1245                item_kind,
1246                cx,
1247            )),
1248            DebuggerPaneItem::LoadedSources => Box::new(SubView::new(
1249                self.loaded_sources_list.focus_handle(cx),
1250                self.loaded_sources_list.clone().into(),
1251                item_kind,
1252                cx,
1253            )),
1254            DebuggerPaneItem::Terminal => Box::new(SubView::new(
1255                self.debug_terminal.focus_handle(cx),
1256                self.debug_terminal.clone().into(),
1257                item_kind,
1258                cx,
1259            )),
1260            DebuggerPaneItem::MemoryView => Box::new(SubView::new(
1261                self.memory_view.focus_handle(cx),
1262                self.memory_view.clone().into(),
1263                item_kind,
1264                cx,
1265            )),
1266        }
1267    }
1268
1269    pub(crate) fn ensure_pane_item(
1270        &mut self,
1271        item_kind: DebuggerPaneItem,
1272        window: &mut Window,
1273        cx: &mut Context<Self>,
1274    ) {
1275        if self.pane_items_status(cx).get(&item_kind) == Some(&true) {
1276            return;
1277        };
1278        let pane = self.panes.last_pane();
1279        let sub_view = self.create_sub_view(item_kind, &pane, cx);
1280
1281        pane.update(cx, |pane, cx| {
1282            pane.add_item_inner(sub_view, false, false, false, None, window, cx);
1283        })
1284    }
1285
1286    pub(crate) fn add_pane_item(
1287        &mut self,
1288        item_kind: DebuggerPaneItem,
1289        position: Point<Pixels>,
1290        window: &mut Window,
1291        cx: &mut Context<Self>,
1292    ) {
1293        debug_assert!(
1294            item_kind.is_supported(self.session.read(cx).capabilities()),
1295            "We should only allow adding supported item kinds"
1296        );
1297
1298        if let Some(pane) = self.panes.pane_at_pixel_position(position) {
1299            let sub_view = self.create_sub_view(item_kind, pane, cx);
1300
1301            pane.update(cx, |pane, cx| {
1302                pane.add_item(sub_view, false, false, None, window, cx);
1303            })
1304        }
1305    }
1306
1307    pub(crate) fn pane_items_status(&self, cx: &App) -> IndexMap<DebuggerPaneItem, bool> {
1308        let caps = self.session.read(cx).capabilities();
1309        let mut pane_item_status = IndexMap::from_iter(
1310            DebuggerPaneItem::all()
1311                .iter()
1312                .filter(|kind| kind.is_supported(caps))
1313                .map(|kind| (*kind, false)),
1314        );
1315        self.panes.panes().iter().for_each(|pane| {
1316            pane.read(cx)
1317                .items()
1318                .filter_map(|item| item.act_as::<SubView>(cx))
1319                .for_each(|view| {
1320                    pane_item_status.insert(view.read(cx).kind, true);
1321                });
1322        });
1323
1324        pane_item_status
1325    }
1326
1327    pub(crate) fn serialize_layout(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1328        if self._schedule_serialize.is_none() {
1329            self._schedule_serialize = Some(cx.spawn_in(window, async move |this, cx| {
1330                cx.background_executor()
1331                    .timer(Duration::from_millis(100))
1332                    .await;
1333
1334                let Some((adapter_name, pane_layout)) = this
1335                    .read_with(cx, |this, cx| {
1336                        let adapter_name = this.session.read(cx).adapter();
1337                        (
1338                            adapter_name,
1339                            persistence::build_serialized_layout(
1340                                &this.panes.root,
1341                                this.dock_axis,
1342                                cx,
1343                            ),
1344                        )
1345                    })
1346                    .ok()
1347                else {
1348                    return;
1349                };
1350
1351                persistence::serialize_pane_layout(adapter_name, pane_layout)
1352                    .await
1353                    .log_err();
1354
1355                this.update(cx, |this, _| {
1356                    this._schedule_serialize.take();
1357                })
1358                .ok();
1359            }));
1360        }
1361    }
1362
1363    pub(crate) fn handle_pane_event(
1364        this: &mut RunningState,
1365        source_pane: &Entity<Pane>,
1366        event: &Event,
1367        window: &mut Window,
1368        cx: &mut Context<RunningState>,
1369    ) {
1370        this.serialize_layout(window, cx);
1371        match event {
1372            Event::Remove { .. } => {
1373                let _did_find_pane = this.panes.remove(source_pane).is_ok();
1374                debug_assert!(_did_find_pane);
1375                cx.notify();
1376            }
1377            Event::Focus => {
1378                this.active_pane = source_pane.clone();
1379            }
1380            _ => {}
1381        }
1382    }
1383
1384    pub(crate) fn activate_pane_in_direction(
1385        &mut self,
1386        direction: SplitDirection,
1387        window: &mut Window,
1388        cx: &mut Context<Self>,
1389    ) {
1390        let active_pane = self.active_pane.clone();
1391        if let Some(pane) = self
1392            .panes
1393            .find_pane_in_direction(&active_pane, direction, cx)
1394        {
1395            pane.update(cx, |pane, cx| {
1396                pane.focus_active_item(window, cx);
1397            })
1398        } else {
1399            self.workspace
1400                .update(cx, |workspace, cx| {
1401                    workspace.activate_pane_in_direction(direction, window, cx)
1402                })
1403                .ok();
1404        }
1405    }
1406
1407    pub(crate) fn go_to_selected_stack_frame(&self, window: &mut Window, cx: &mut Context<Self>) {
1408        if self.thread_id.is_some() {
1409            self.stack_frame_list
1410                .update(cx, |list, cx| {
1411                    let Some(stack_frame_id) = list.opened_stack_frame_id() else {
1412                        return Task::ready(Ok(()));
1413                    };
1414                    list.go_to_stack_frame(stack_frame_id, window, cx)
1415                })
1416                .detach();
1417        }
1418    }
1419
1420    pub(crate) fn has_open_context_menu(&self, cx: &App) -> bool {
1421        self.variable_list.read(cx).has_open_context_menu()
1422    }
1423
1424    pub fn session(&self) -> &Entity<Session> {
1425        &self.session
1426    }
1427
1428    pub fn session_id(&self) -> SessionId {
1429        self.session_id
1430    }
1431
1432    pub(crate) fn selected_stack_frame_id(&self, cx: &App) -> Option<dap::StackFrameId> {
1433        self.stack_frame_list.read(cx).opened_stack_frame_id()
1434    }
1435
1436    pub(crate) fn stack_frame_list(&self) -> &Entity<StackFrameList> {
1437        &self.stack_frame_list
1438    }
1439
1440    #[cfg(test)]
1441    pub fn console(&self) -> &Entity<Console> {
1442        &self.console
1443    }
1444
1445    #[cfg(test)]
1446    pub(crate) fn module_list(&self) -> &Entity<ModuleList> {
1447        &self.module_list
1448    }
1449
1450    pub(crate) fn activate_item(
1451        &mut self,
1452        item: DebuggerPaneItem,
1453        window: &mut Window,
1454        cx: &mut Context<Self>,
1455    ) {
1456        self.ensure_pane_item(item, window, cx);
1457
1458        let (variable_list_position, pane) = self
1459            .panes
1460            .panes()
1461            .into_iter()
1462            .find_map(|pane| {
1463                pane.read(cx)
1464                    .items_of_type::<SubView>()
1465                    .position(|view| view.read(cx).view_kind() == item)
1466                    .map(|view| (view, pane))
1467            })
1468            .unwrap();
1469
1470        pane.update(cx, |this, cx| {
1471            this.activate_item(variable_list_position, true, true, window, cx);
1472        });
1473    }
1474
1475    #[cfg(test)]
1476    pub(crate) fn variable_list(&self) -> &Entity<VariableList> {
1477        &self.variable_list
1478    }
1479
1480    #[cfg(test)]
1481    pub(crate) fn serialized_layout(&self, cx: &App) -> SerializedLayout {
1482        persistence::build_serialized_layout(&self.panes.root, self.dock_axis, cx)
1483    }
1484
1485    pub fn capabilities(&self, cx: &App) -> Capabilities {
1486        self.session().read(cx).capabilities().clone()
1487    }
1488
1489    pub fn select_current_thread(
1490        &mut self,
1491        threads: &Vec<(Thread, ThreadStatus)>,
1492        window: &mut Window,
1493        cx: &mut Context<Self>,
1494    ) {
1495        let selected_thread = self
1496            .thread_id
1497            .and_then(|thread_id| threads.iter().find(|(thread, _)| thread.id == thread_id.0))
1498            .or_else(|| threads.first());
1499
1500        let Some((selected_thread, _)) = selected_thread else {
1501            return;
1502        };
1503
1504        if Some(ThreadId(selected_thread.id)) != self.thread_id {
1505            self.select_thread(ThreadId(selected_thread.id), window, cx);
1506        }
1507    }
1508
1509    pub fn selected_thread_id(&self) -> Option<ThreadId> {
1510        self.thread_id
1511    }
1512
1513    pub fn thread_status(&self, cx: &App) -> Option<ThreadStatus> {
1514        self.thread_id
1515            .map(|id| self.session().read(cx).thread_status(id))
1516    }
1517
1518    pub(crate) fn select_thread(
1519        &mut self,
1520        thread_id: ThreadId,
1521        window: &mut Window,
1522        cx: &mut Context<Self>,
1523    ) {
1524        if self.thread_id.is_some_and(|id| id == thread_id) {
1525            return;
1526        }
1527
1528        self.thread_id = Some(thread_id);
1529
1530        self.stack_frame_list
1531            .update(cx, |list, cx| list.schedule_refresh(true, window, cx));
1532    }
1533
1534    pub fn continue_thread(&mut self, cx: &mut Context<Self>) {
1535        let Some(thread_id) = self.thread_id else {
1536            return;
1537        };
1538
1539        self.session().update(cx, |state, cx| {
1540            state.continue_thread(thread_id, cx);
1541        });
1542    }
1543
1544    pub fn step_over(&mut self, cx: &mut Context<Self>) {
1545        let Some(thread_id) = self.thread_id else {
1546            return;
1547        };
1548
1549        let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1550
1551        self.session().update(cx, |state, cx| {
1552            state.step_over(thread_id, granularity, cx);
1553        });
1554    }
1555
1556    pub(crate) fn step_in(&mut self, cx: &mut Context<Self>) {
1557        let Some(thread_id) = self.thread_id else {
1558            return;
1559        };
1560
1561        let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1562
1563        self.session().update(cx, |state, cx| {
1564            state.step_in(thread_id, granularity, cx);
1565        });
1566    }
1567
1568    pub(crate) fn step_out(&mut self, cx: &mut Context<Self>) {
1569        let Some(thread_id) = self.thread_id else {
1570            return;
1571        };
1572
1573        let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1574
1575        self.session().update(cx, |state, cx| {
1576            state.step_out(thread_id, granularity, cx);
1577        });
1578    }
1579
1580    pub(crate) fn step_back(&mut self, cx: &mut Context<Self>) {
1581        let Some(thread_id) = self.thread_id else {
1582            return;
1583        };
1584
1585        let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1586
1587        self.session().update(cx, |state, cx| {
1588            state.step_back(thread_id, granularity, cx);
1589        });
1590    }
1591
1592    pub fn rerun_session(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1593        if let Some((scenario, context)) = self.scenario.take().zip(self.scenario_context.take())
1594            && scenario.build.is_some()
1595        {
1596            let DebugScenarioContext {
1597                task_context,
1598                active_buffer,
1599                worktree_id,
1600            } = context;
1601            let active_buffer = active_buffer.and_then(|buffer| buffer.upgrade());
1602
1603            self.workspace
1604                .update(cx, |workspace, cx| {
1605                    workspace.start_debug_session(
1606                        scenario,
1607                        task_context,
1608                        active_buffer,
1609                        worktree_id,
1610                        window,
1611                        cx,
1612                    )
1613                })
1614                .ok();
1615        } else {
1616            self.restart_session(cx);
1617        }
1618    }
1619
1620    pub fn restart_session(&self, cx: &mut Context<Self>) {
1621        self.session().update(cx, |state, cx| {
1622            state.restart(None, cx);
1623        });
1624    }
1625
1626    pub fn pause_thread(&self, cx: &mut Context<Self>) {
1627        let Some(thread_id) = self.thread_id else {
1628            return;
1629        };
1630
1631        self.session().update(cx, |state, cx| {
1632            state.pause_thread(thread_id, cx);
1633        });
1634    }
1635
1636    pub(crate) fn shutdown(&mut self, cx: &mut Context<Self>) {
1637        self.workspace
1638            .update(cx, |workspace, cx| {
1639                workspace
1640                    .project()
1641                    .read(cx)
1642                    .breakpoint_store()
1643                    .update(cx, |store, cx| {
1644                        store.remove_active_position(Some(self.session_id), cx)
1645                    })
1646            })
1647            .log_err();
1648
1649        let is_building = self.session.update(cx, |session, cx| {
1650            session.shutdown(cx).detach();
1651            matches!(session.mode, session::SessionState::Booting(_))
1652        });
1653
1654        if is_building {
1655            self.debug_terminal.update(cx, |terminal, cx| {
1656                if let Some(view) = terminal.terminal.as_ref() {
1657                    view.update(cx, |view, cx| {
1658                        view.terminal()
1659                            .update(cx, |terminal, _| terminal.kill_active_task())
1660                    })
1661                }
1662            })
1663        }
1664    }
1665
1666    pub fn stop_thread(&self, cx: &mut Context<Self>) {
1667        let Some(thread_id) = self.thread_id else {
1668            return;
1669        };
1670
1671        self.workspace
1672            .update(cx, |workspace, cx| {
1673                workspace
1674                    .project()
1675                    .read(cx)
1676                    .breakpoint_store()
1677                    .update(cx, |store, cx| {
1678                        store.remove_active_position(Some(self.session_id), cx)
1679                    })
1680            })
1681            .log_err();
1682
1683        self.session().update(cx, |state, cx| {
1684            state.terminate_threads(Some(vec![thread_id; 1]), cx);
1685        });
1686    }
1687
1688    pub fn detach_client(&self, cx: &mut Context<Self>) {
1689        self.session().update(cx, |state, cx| {
1690            state.disconnect_client(cx);
1691        });
1692    }
1693
1694    pub fn toggle_ignore_breakpoints(&mut self, cx: &mut Context<Self>) {
1695        self.session.update(cx, |session, cx| {
1696            session.toggle_ignore_breakpoints(cx).detach();
1697        });
1698    }
1699
1700    fn default_pane_layout(
1701        project: Entity<Project>,
1702        workspace: &WeakEntity<Workspace>,
1703        stack_frame_list: &Entity<StackFrameList>,
1704        variable_list: &Entity<VariableList>,
1705        console: &Entity<Console>,
1706        breakpoints: &Entity<BreakpointList>,
1707        debug_terminal: &Entity<DebugTerminal>,
1708        dock_axis: Axis,
1709        subscriptions: &mut HashMap<EntityId, Subscription>,
1710        window: &mut Window,
1711        cx: &mut Context<'_, RunningState>,
1712    ) -> Member {
1713        let leftmost_pane = new_debugger_pane(workspace.clone(), project.clone(), window, cx);
1714        leftmost_pane.update(cx, |this, cx| {
1715            this.add_item(
1716                Box::new(SubView::new(
1717                    this.focus_handle(cx),
1718                    stack_frame_list.clone().into(),
1719                    DebuggerPaneItem::Frames,
1720                    cx,
1721                )),
1722                true,
1723                false,
1724                None,
1725                window,
1726                cx,
1727            );
1728            this.add_item(
1729                Box::new(SubView::breakpoint_list(breakpoints.clone(), cx)),
1730                true,
1731                false,
1732                None,
1733                window,
1734                cx,
1735            );
1736            this.activate_item(0, false, false, window, cx);
1737        });
1738        let center_pane = new_debugger_pane(workspace.clone(), project.clone(), window, cx);
1739
1740        center_pane.update(cx, |this, cx| {
1741            let view = SubView::console(console.clone(), cx);
1742
1743            this.add_item(Box::new(view), true, false, None, window, cx);
1744
1745            this.add_item(
1746                Box::new(SubView::new(
1747                    variable_list.focus_handle(cx),
1748                    variable_list.clone().into(),
1749                    DebuggerPaneItem::Variables,
1750                    cx,
1751                )),
1752                true,
1753                false,
1754                None,
1755                window,
1756                cx,
1757            );
1758            this.activate_item(0, false, false, window, cx);
1759        });
1760
1761        let rightmost_pane = new_debugger_pane(workspace.clone(), project, window, cx);
1762        rightmost_pane.update(cx, |this, cx| {
1763            this.add_item(
1764                Box::new(SubView::new(
1765                    debug_terminal.focus_handle(cx),
1766                    debug_terminal.clone().into(),
1767                    DebuggerPaneItem::Terminal,
1768                    cx,
1769                )),
1770                false,
1771                false,
1772                None,
1773                window,
1774                cx,
1775            );
1776        });
1777
1778        subscriptions.extend(
1779            [&leftmost_pane, &center_pane, &rightmost_pane]
1780                .into_iter()
1781                .map(|entity| {
1782                    (
1783                        entity.entity_id(),
1784                        cx.subscribe_in(entity, window, Self::handle_pane_event),
1785                    )
1786                }),
1787        );
1788
1789        let group_root = workspace::PaneAxis::new(
1790            dock_axis.invert(),
1791            [leftmost_pane, center_pane, rightmost_pane]
1792                .into_iter()
1793                .map(workspace::Member::Pane)
1794                .collect(),
1795        );
1796
1797        Member::Axis(group_root)
1798    }
1799
1800    pub(crate) fn invert_axies(&mut self) {
1801        self.dock_axis = self.dock_axis.invert();
1802        self.panes.invert_axies();
1803    }
1804}
1805
1806impl EventEmitter<DebugPanelItemEvent> for RunningState {}
1807
1808impl Focusable for RunningState {
1809    fn focus_handle(&self, _: &App) -> FocusHandle {
1810        self.focus_handle.clone()
1811    }
1812}