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