running.rs

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