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