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