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                if let Some(substituted) = substitute_variables_in_str(&s, context) {
 551                    *s = substituted;
 552                }
 553            }
 554            _ => {}
 555        }
 556    }
 557
 558    pub(crate) fn relativlize_paths(
 559        key: Option<&str>,
 560        config: &mut serde_json::Value,
 561        context: &TaskContext,
 562    ) {
 563        match config {
 564            serde_json::Value::Object(obj) => {
 565                obj.iter_mut()
 566                    .for_each(|(key, value)| Self::relativlize_paths(Some(key), value, context));
 567            }
 568            serde_json::Value::Array(array) => {
 569                array
 570                    .iter_mut()
 571                    .for_each(|value| Self::relativlize_paths(None, value, context));
 572            }
 573            serde_json::Value::String(s) if key == Some("program") || key == Some("cwd") => {
 574                resolve_path(s);
 575
 576                if let Some(substituted) = substitute_variables_in_str(&s, context) {
 577                    *s = substituted;
 578                }
 579            }
 580            _ => {}
 581        }
 582    }
 583
 584    pub(crate) fn new(
 585        session: Entity<Session>,
 586        project: Entity<Project>,
 587        workspace: WeakEntity<Workspace>,
 588        serialized_pane_layout: Option<SerializedLayout>,
 589        dock_axis: Axis,
 590        window: &mut Window,
 591        cx: &mut Context<Self>,
 592    ) -> Self {
 593        let focus_handle = cx.focus_handle();
 594        let session_id = session.read(cx).session_id();
 595        let weak_state = cx.weak_entity();
 596        let stack_frame_list = cx.new(|cx| {
 597            StackFrameList::new(workspace.clone(), session.clone(), weak_state, window, cx)
 598        });
 599
 600        let debug_terminal = cx.new(|cx| DebugTerminal::empty(window, cx));
 601
 602        let variable_list =
 603            cx.new(|cx| VariableList::new(session.clone(), stack_frame_list.clone(), window, cx));
 604
 605        let module_list = cx.new(|cx| ModuleList::new(session.clone(), workspace.clone(), cx));
 606
 607        let loaded_source_list = cx.new(|cx| LoadedSourceList::new(session.clone(), cx));
 608
 609        let console = cx.new(|cx| {
 610            Console::new(
 611                session.clone(),
 612                stack_frame_list.clone(),
 613                variable_list.clone(),
 614                window,
 615                cx,
 616            )
 617        });
 618
 619        let breakpoint_list = BreakpointList::new(session.clone(), workspace.clone(), &project, cx);
 620
 621        let _subscriptions = vec![
 622            cx.observe(&module_list, |_, _, cx| cx.notify()),
 623            cx.subscribe_in(&session, window, |this, _, event, window, cx| {
 624                match event {
 625                    SessionEvent::Stopped(thread_id) => {
 626                        let panel = this
 627                            .workspace
 628                            .update(cx, |workspace, cx| {
 629                                workspace.open_panel::<crate::DebugPanel>(window, cx);
 630                                workspace.panel::<crate::DebugPanel>(cx)
 631                            })
 632                            .log_err()
 633                            .flatten();
 634
 635                        if let Some(thread_id) = thread_id {
 636                            this.select_thread(*thread_id, window, cx);
 637                        }
 638                        if let Some(panel) = panel {
 639                            let id = this.session_id;
 640                            window.defer(cx, move |window, cx| {
 641                                panel.update(cx, |this, cx| {
 642                                    this.activate_session_by_id(id, window, cx);
 643                                })
 644                            })
 645                        }
 646                    }
 647                    SessionEvent::Threads => {
 648                        let threads = this.session.update(cx, |this, cx| this.threads(cx));
 649                        this.select_current_thread(&threads, window, cx);
 650                    }
 651                    SessionEvent::CapabilitiesLoaded => {
 652                        let capabilities = this.capabilities(cx);
 653                        if !capabilities.supports_modules_request.unwrap_or(false) {
 654                            this.remove_pane_item(DebuggerPaneItem::Modules, window, cx);
 655                        }
 656                        if !capabilities
 657                            .supports_loaded_sources_request
 658                            .unwrap_or(false)
 659                        {
 660                            this.remove_pane_item(DebuggerPaneItem::LoadedSources, window, cx);
 661                        }
 662                    }
 663                    SessionEvent::RunInTerminal { request, sender } => this
 664                        .handle_run_in_terminal(request, sender.clone(), window, cx)
 665                        .detach_and_log_err(cx),
 666
 667                    _ => {}
 668                }
 669                cx.notify()
 670            }),
 671            cx.on_focus_out(&focus_handle, window, |this, _, window, cx| {
 672                this.serialize_layout(window, cx);
 673            }),
 674        ];
 675
 676        let mut pane_close_subscriptions = HashMap::default();
 677        let panes = if let Some(root) = serialized_pane_layout.and_then(|serialized_layout| {
 678            persistence::deserialize_pane_layout(
 679                serialized_layout.panes,
 680                dock_axis != serialized_layout.dock_axis,
 681                &workspace,
 682                &project,
 683                &stack_frame_list,
 684                &variable_list,
 685                &module_list,
 686                &console,
 687                &breakpoint_list,
 688                &loaded_source_list,
 689                &debug_terminal,
 690                &mut pane_close_subscriptions,
 691                window,
 692                cx,
 693            )
 694        }) {
 695            workspace::PaneGroup::with_root(root)
 696        } else {
 697            pane_close_subscriptions.clear();
 698
 699            let root = Self::default_pane_layout(
 700                project,
 701                &workspace,
 702                &stack_frame_list,
 703                &variable_list,
 704                &console,
 705                &breakpoint_list,
 706                &debug_terminal,
 707                dock_axis,
 708                &mut pane_close_subscriptions,
 709                window,
 710                cx,
 711            );
 712
 713            workspace::PaneGroup::with_root(root)
 714        };
 715        let active_pane = panes.first_pane();
 716
 717        Self {
 718            session,
 719            workspace,
 720            focus_handle,
 721            variable_list,
 722            _subscriptions,
 723            thread_id: None,
 724            _remote_id: None,
 725            stack_frame_list,
 726            session_id,
 727            panes,
 728            active_pane,
 729            module_list,
 730            console,
 731            breakpoint_list,
 732            loaded_sources_list: loaded_source_list,
 733            pane_close_subscriptions,
 734            debug_terminal,
 735            dock_axis,
 736            _schedule_serialize: None,
 737        }
 738    }
 739
 740    pub(crate) fn remove_pane_item(
 741        &mut self,
 742        item_kind: DebuggerPaneItem,
 743        window: &mut Window,
 744        cx: &mut Context<Self>,
 745    ) {
 746        if let Some((pane, item_id)) = self.panes.panes().iter().find_map(|pane| {
 747            Some(pane).zip(
 748                pane.read(cx)
 749                    .items()
 750                    .find(|item| {
 751                        item.act_as::<SubView>(cx)
 752                            .is_some_and(|view| view.read(cx).kind == item_kind)
 753                    })
 754                    .map(|item| item.item_id()),
 755            )
 756        }) {
 757            pane.update(cx, |pane, cx| {
 758                pane.remove_item(item_id, false, true, window, cx)
 759            })
 760        }
 761    }
 762
 763    pub(crate) fn has_pane_at_position(&self, position: Point<Pixels>) -> bool {
 764        self.panes.pane_at_pixel_position(position).is_some()
 765    }
 766
 767    pub(crate) fn resolve_scenario(
 768        &self,
 769        scenario: DebugScenario,
 770        task_context: TaskContext,
 771        buffer: Option<Entity<Buffer>>,
 772        worktree_id: Option<WorktreeId>,
 773        window: &Window,
 774        cx: &mut Context<Self>,
 775    ) -> Task<Result<DebugTaskDefinition>> {
 776        let Some(workspace) = self.workspace.upgrade() else {
 777            return Task::ready(Err(anyhow!("no workspace")));
 778        };
 779        let project = workspace.read(cx).project().clone();
 780        let dap_store = project.read(cx).dap_store().downgrade();
 781        let dap_registry = cx.global::<DapRegistry>().clone();
 782        let task_store = project.read(cx).task_store().downgrade();
 783        let weak_project = project.downgrade();
 784        let weak_workspace = workspace.downgrade();
 785        let is_local = project.read(cx).is_local();
 786        cx.spawn_in(window, async move |this, cx| {
 787            let DebugScenario {
 788                adapter,
 789                label,
 790                build,
 791                mut config,
 792                tcp_connection,
 793            } = scenario;
 794            Self::relativlize_paths(None, &mut config, &task_context);
 795            Self::substitute_variables_in_config(&mut config, &task_context);
 796
 797            let request_type = dap_registry
 798                .adapter(&adapter)
 799                .ok_or_else(|| anyhow!("{}: is not a valid adapter name", &adapter))
 800                .and_then(|adapter| adapter.validate_config(&config));
 801
 802            let config_is_valid = request_type.is_ok();
 803
 804            let build_output = if let Some(build) = build {
 805                let (task, locator_name) = match build {
 806                    BuildTaskDefinition::Template {
 807                        task_template,
 808                        locator_name,
 809                    } => (task_template, locator_name),
 810                    BuildTaskDefinition::ByName(ref label) => {
 811                        let Some(task) = task_store.update(cx, |this, cx| {
 812                            this.task_inventory().and_then(|inventory| {
 813                                inventory.read(cx).task_template_by_label(
 814                                    buffer,
 815                                    worktree_id,
 816                                    &label,
 817                                    cx,
 818                                )
 819                            })
 820                        })?
 821                        else {
 822                            anyhow::bail!("Couldn't find task template for {:?}", build)
 823                        };
 824                        (task, None)
 825                    }
 826                };
 827                let Some(task) = task.resolve_task("debug-build-task", &task_context) else {
 828                    anyhow::bail!("Could not resolve task variables within a debug scenario");
 829                };
 830
 831                let locator_name = if let Some(locator_name) = locator_name {
 832                    debug_assert!(!config_is_valid);
 833                    Some(locator_name)
 834                } else if !config_is_valid {
 835                    dap_store
 836                        .update(cx, |this, cx| {
 837                            this.debug_scenario_for_build_task(
 838                                task.original_task().clone(),
 839                                adapter.clone().into(),
 840                                task.display_label().to_owned().into(),
 841                                cx,
 842                            )
 843                            .and_then(|scenario| {
 844                                match scenario.build {
 845                                    Some(BuildTaskDefinition::Template {
 846                                        locator_name, ..
 847                                    }) => locator_name,
 848                                    _ => None,
 849                                }
 850                            })
 851                        })
 852                        .ok()
 853                        .flatten()
 854                } else {
 855                    None
 856                };
 857
 858                let builder = ShellBuilder::new(is_local, &task.resolved.shell);
 859                let command_label = builder.command_label(&task.resolved.command_label);
 860                let (command, args) =
 861                    builder.build(task.resolved.command.clone(), &task.resolved.args);
 862
 863                let task_with_shell = SpawnInTerminal {
 864                    command_label,
 865                    command,
 866                    args,
 867                    ..task.resolved.clone()
 868                };
 869                let terminal = project
 870                    .update_in(cx, |project, window, cx| {
 871                        project.create_terminal(
 872                            TerminalKind::Task(task_with_shell.clone()),
 873                            window.window_handle(),
 874                            cx,
 875                        )
 876                    })?
 877                    .await?;
 878
 879                let terminal_view = cx.new_window_entity(|window, cx| {
 880                    TerminalView::new(
 881                        terminal.clone(),
 882                        weak_workspace,
 883                        None,
 884                        weak_project,
 885                        false,
 886                        window,
 887                        cx,
 888                    )
 889                })?;
 890
 891                this.update_in(cx, |this, window, cx| {
 892                    this.ensure_pane_item(DebuggerPaneItem::Terminal, window, cx);
 893                    this.debug_terminal.update(cx, |debug_terminal, cx| {
 894                        debug_terminal.terminal = Some(terminal_view);
 895                        cx.notify();
 896                    });
 897                })?;
 898
 899                let exit_status = terminal
 900                    .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))?
 901                    .await
 902                    .context("Failed to wait for completed task")?;
 903
 904                if !exit_status.success() {
 905                    anyhow::bail!("Build failed");
 906                }
 907                Some((task.resolved.clone(), locator_name))
 908            } else {
 909                None
 910            };
 911
 912            if config_is_valid {
 913                // Ok(DebugTaskDefinition {
 914                //     label,
 915                //     adapter: DebugAdapterName(adapter),
 916                //     config,
 917                //     tcp_connection,
 918                // })
 919            } else if let Some((task, locator_name)) = build_output {
 920                let locator_name =
 921                    locator_name.context("Could not find a valid locator for a build task")?;
 922                let request = dap_store
 923                    .update(cx, |this, cx| {
 924                        this.run_debug_locator(&locator_name, task, cx)
 925                    })?
 926                    .await?;
 927
 928                let zed_config = ZedDebugConfig {
 929                    label: label.clone(),
 930                    adapter: adapter.clone(),
 931                    request,
 932                    stop_on_entry: None,
 933                };
 934
 935                let scenario = dap_registry
 936                    .adapter(&adapter)
 937                    .ok_or_else(|| anyhow!("{}: is not a valid adapter name", &adapter))
 938                    .map(|adapter| adapter.config_from_zed_format(zed_config))??;
 939                config = scenario.config;
 940                Self::substitute_variables_in_config(&mut config, &task_context);
 941            } else {
 942                anyhow::bail!("No request or build provided");
 943            };
 944
 945            Ok(DebugTaskDefinition {
 946                label,
 947                adapter: DebugAdapterName(adapter),
 948                config,
 949                tcp_connection,
 950            })
 951        })
 952    }
 953
 954    fn handle_run_in_terminal(
 955        &self,
 956        request: &RunInTerminalRequestArguments,
 957        mut sender: mpsc::Sender<Result<u32>>,
 958        window: &mut Window,
 959        cx: &mut Context<Self>,
 960    ) -> Task<Result<()>> {
 961        let running = cx.entity();
 962        let Ok(project) = self
 963            .workspace
 964            .read_with(cx, |workspace, _| workspace.project().clone())
 965        else {
 966            return Task::ready(Err(anyhow!("no workspace")));
 967        };
 968        let session = self.session.read(cx);
 969
 970        let cwd = Some(&request.cwd)
 971            .filter(|cwd| cwd.len() > 0)
 972            .map(PathBuf::from)
 973            .or_else(|| session.binary().cwd.clone());
 974
 975        let mut args = request.args.clone();
 976
 977        // Handle special case for NodeJS debug adapter
 978        // If only the Node binary path is provided, we set the command to None
 979        // This prevents the NodeJS REPL from appearing, which is not the desired behavior
 980        // The expected usage is for users to provide their own Node command, e.g., `node test.js`
 981        // This allows the NodeJS debug client to attach correctly
 982        let command = if args.len() > 1 {
 983            Some(args.remove(0))
 984        } else {
 985            None
 986        };
 987
 988        let mut envs: HashMap<String, String> = Default::default();
 989        if let Some(Value::Object(env)) = &request.env {
 990            for (key, value) in env {
 991                let value_str = match (key.as_str(), value) {
 992                    (_, Value::String(value)) => value,
 993                    _ => continue,
 994                };
 995
 996                envs.insert(key.clone(), value_str.clone());
 997            }
 998        }
 999
1000        let shell = project.read(cx).terminal_settings(&cwd, cx).shell.clone();
1001        let kind = if let Some(command) = command {
1002            let title = request.title.clone().unwrap_or(command.clone());
1003            TerminalKind::Task(task::SpawnInTerminal {
1004                id: task::TaskId("debug".to_string()),
1005                full_label: title.clone(),
1006                label: title.clone(),
1007                command: command.clone(),
1008                args,
1009                command_label: title.clone(),
1010                cwd,
1011                env: envs,
1012                use_new_terminal: true,
1013                allow_concurrent_runs: true,
1014                reveal: task::RevealStrategy::NoFocus,
1015                reveal_target: task::RevealTarget::Dock,
1016                hide: task::HideStrategy::Never,
1017                shell,
1018                show_summary: false,
1019                show_command: false,
1020                show_rerun: false,
1021            })
1022        } else {
1023            TerminalKind::Shell(cwd.map(|c| c.to_path_buf()))
1024        };
1025
1026        let workspace = self.workspace.clone();
1027        let weak_project = project.downgrade();
1028
1029        let terminal_task = project.update(cx, |project, cx| {
1030            project.create_terminal(kind, window.window_handle(), cx)
1031        });
1032        let terminal_task = cx.spawn_in(window, async move |_, cx| {
1033            let terminal = terminal_task.await?;
1034
1035            let terminal_view = cx.new_window_entity(|window, cx| {
1036                TerminalView::new(
1037                    terminal.clone(),
1038                    workspace,
1039                    None,
1040                    weak_project,
1041                    false,
1042                    window,
1043                    cx,
1044                )
1045            })?;
1046
1047            running.update_in(cx, |running, window, cx| {
1048                running.ensure_pane_item(DebuggerPaneItem::Terminal, window, cx);
1049                running.debug_terminal.update(cx, |debug_terminal, cx| {
1050                    debug_terminal.terminal = Some(terminal_view);
1051                    cx.notify();
1052                });
1053            })?;
1054
1055            terminal.read_with(cx, |terminal, _| {
1056                terminal
1057                    .pty_info
1058                    .pid()
1059                    .map(|pid| pid.as_u32())
1060                    .context("Terminal was spawned but PID was not available")
1061            })?
1062        });
1063
1064        cx.background_spawn(async move { anyhow::Ok(sender.send(terminal_task.await).await?) })
1065    }
1066
1067    fn create_sub_view(
1068        &self,
1069        item_kind: DebuggerPaneItem,
1070        _pane: &Entity<Pane>,
1071        cx: &mut Context<Self>,
1072    ) -> Box<dyn ItemHandle> {
1073        match item_kind {
1074            DebuggerPaneItem::Console => {
1075                let weak_console = self.console.clone().downgrade();
1076
1077                Box::new(SubView::new(
1078                    self.console.focus_handle(cx),
1079                    self.console.clone().into(),
1080                    item_kind,
1081                    Some(Box::new(move |cx| {
1082                        weak_console
1083                            .read_with(cx, |console, cx| console.show_indicator(cx))
1084                            .unwrap_or_default()
1085                    })),
1086                    cx,
1087                ))
1088            }
1089            DebuggerPaneItem::Variables => Box::new(SubView::new(
1090                self.variable_list.focus_handle(cx),
1091                self.variable_list.clone().into(),
1092                item_kind,
1093                None,
1094                cx,
1095            )),
1096            DebuggerPaneItem::BreakpointList => Box::new(SubView::new(
1097                self.breakpoint_list.focus_handle(cx),
1098                self.breakpoint_list.clone().into(),
1099                item_kind,
1100                None,
1101                cx,
1102            )),
1103            DebuggerPaneItem::Frames => Box::new(SubView::new(
1104                self.stack_frame_list.focus_handle(cx),
1105                self.stack_frame_list.clone().into(),
1106                item_kind,
1107                None,
1108                cx,
1109            )),
1110            DebuggerPaneItem::Modules => Box::new(SubView::new(
1111                self.module_list.focus_handle(cx),
1112                self.module_list.clone().into(),
1113                item_kind,
1114                None,
1115                cx,
1116            )),
1117            DebuggerPaneItem::LoadedSources => Box::new(SubView::new(
1118                self.loaded_sources_list.focus_handle(cx),
1119                self.loaded_sources_list.clone().into(),
1120                item_kind,
1121                None,
1122                cx,
1123            )),
1124            DebuggerPaneItem::Terminal => Box::new(SubView::new(
1125                self.debug_terminal.focus_handle(cx),
1126                self.debug_terminal.clone().into(),
1127                item_kind,
1128                None,
1129                cx,
1130            )),
1131        }
1132    }
1133
1134    pub(crate) fn ensure_pane_item(
1135        &mut self,
1136        item_kind: DebuggerPaneItem,
1137        window: &mut Window,
1138        cx: &mut Context<Self>,
1139    ) {
1140        if self.pane_items_status(cx).get(&item_kind) == Some(&true) {
1141            return;
1142        };
1143        let pane = self.panes.last_pane();
1144        let sub_view = self.create_sub_view(item_kind, &pane, cx);
1145
1146        pane.update(cx, |pane, cx| {
1147            pane.add_item_inner(sub_view, false, false, false, None, window, cx);
1148        })
1149    }
1150
1151    pub(crate) fn add_pane_item(
1152        &mut self,
1153        item_kind: DebuggerPaneItem,
1154        position: Point<Pixels>,
1155        window: &mut Window,
1156        cx: &mut Context<Self>,
1157    ) {
1158        debug_assert!(
1159            item_kind.is_supported(self.session.read(cx).capabilities()),
1160            "We should only allow adding supported item kinds"
1161        );
1162
1163        if let Some(pane) = self.panes.pane_at_pixel_position(position) {
1164            let sub_view = self.create_sub_view(item_kind, pane, cx);
1165
1166            pane.update(cx, |pane, cx| {
1167                pane.add_item(sub_view, false, false, None, window, cx);
1168            })
1169        }
1170    }
1171
1172    pub(crate) fn pane_items_status(&self, cx: &App) -> IndexMap<DebuggerPaneItem, bool> {
1173        let caps = self.session.read(cx).capabilities();
1174        let mut pane_item_status = IndexMap::from_iter(
1175            DebuggerPaneItem::all()
1176                .iter()
1177                .filter(|kind| kind.is_supported(&caps))
1178                .map(|kind| (*kind, false)),
1179        );
1180        self.panes.panes().iter().for_each(|pane| {
1181            pane.read(cx)
1182                .items()
1183                .filter_map(|item| item.act_as::<SubView>(cx))
1184                .for_each(|view| {
1185                    pane_item_status.insert(view.read(cx).kind, true);
1186                });
1187        });
1188
1189        pane_item_status
1190    }
1191
1192    pub(crate) fn serialize_layout(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1193        if self._schedule_serialize.is_none() {
1194            self._schedule_serialize = Some(cx.spawn_in(window, async move |this, cx| {
1195                cx.background_executor()
1196                    .timer(Duration::from_millis(100))
1197                    .await;
1198
1199                let Some((adapter_name, pane_layout)) = this
1200                    .read_with(cx, |this, cx| {
1201                        let adapter_name = this.session.read(cx).adapter();
1202                        (
1203                            adapter_name,
1204                            persistence::build_serialized_layout(
1205                                &this.panes.root,
1206                                this.dock_axis,
1207                                cx,
1208                            ),
1209                        )
1210                    })
1211                    .ok()
1212                else {
1213                    return;
1214                };
1215
1216                persistence::serialize_pane_layout(adapter_name, pane_layout)
1217                    .await
1218                    .log_err();
1219
1220                this.update(cx, |this, _| {
1221                    this._schedule_serialize.take();
1222                })
1223                .ok();
1224            }));
1225        }
1226    }
1227
1228    pub(crate) fn handle_pane_event(
1229        this: &mut RunningState,
1230        source_pane: &Entity<Pane>,
1231        event: &Event,
1232        window: &mut Window,
1233        cx: &mut Context<RunningState>,
1234    ) {
1235        this.serialize_layout(window, cx);
1236        match event {
1237            Event::Remove { .. } => {
1238                let _did_find_pane = this.panes.remove(&source_pane).is_ok();
1239                debug_assert!(_did_find_pane);
1240                cx.notify();
1241            }
1242            Event::Focus => {
1243                this.active_pane = source_pane.clone();
1244            }
1245            Event::ZoomIn => {
1246                source_pane.update(cx, |pane, cx| {
1247                    pane.set_zoomed(true, cx);
1248                });
1249                cx.notify();
1250            }
1251            Event::ZoomOut => {
1252                source_pane.update(cx, |pane, cx| {
1253                    pane.set_zoomed(false, cx);
1254                });
1255                cx.notify();
1256            }
1257            _ => {}
1258        }
1259    }
1260
1261    pub(crate) fn activate_pane_in_direction(
1262        &mut self,
1263        direction: SplitDirection,
1264        window: &mut Window,
1265        cx: &mut Context<Self>,
1266    ) {
1267        let active_pane = self.active_pane.clone();
1268        if let Some(pane) = self
1269            .panes
1270            .find_pane_in_direction(&active_pane, direction, cx)
1271        {
1272            pane.update(cx, |pane, cx| {
1273                pane.focus_active_item(window, cx);
1274            })
1275        } else {
1276            self.workspace
1277                .update(cx, |workspace, cx| {
1278                    workspace.activate_pane_in_direction(direction, window, cx)
1279                })
1280                .ok();
1281        }
1282    }
1283
1284    pub(crate) fn go_to_selected_stack_frame(&self, window: &mut Window, cx: &mut Context<Self>) {
1285        if self.thread_id.is_some() {
1286            self.stack_frame_list
1287                .update(cx, |list, cx| {
1288                    let Some(stack_frame_id) = list.opened_stack_frame_id() else {
1289                        return Task::ready(Ok(()));
1290                    };
1291                    list.go_to_stack_frame(stack_frame_id, window, cx)
1292                })
1293                .detach();
1294        }
1295    }
1296
1297    pub(crate) fn has_open_context_menu(&self, cx: &App) -> bool {
1298        self.variable_list.read(cx).has_open_context_menu()
1299    }
1300
1301    pub fn session(&self) -> &Entity<Session> {
1302        &self.session
1303    }
1304
1305    pub fn session_id(&self) -> SessionId {
1306        self.session_id
1307    }
1308
1309    pub(crate) fn selected_stack_frame_id(&self, cx: &App) -> Option<dap::StackFrameId> {
1310        self.stack_frame_list.read(cx).opened_stack_frame_id()
1311    }
1312
1313    pub(crate) fn stack_frame_list(&self) -> &Entity<StackFrameList> {
1314        &self.stack_frame_list
1315    }
1316
1317    #[cfg(test)]
1318    pub fn console(&self) -> &Entity<Console> {
1319        &self.console
1320    }
1321
1322    #[cfg(test)]
1323    pub(crate) fn module_list(&self) -> &Entity<ModuleList> {
1324        &self.module_list
1325    }
1326
1327    pub(crate) fn activate_item(&self, item: DebuggerPaneItem, window: &mut Window, cx: &mut App) {
1328        let (variable_list_position, pane) = self
1329            .panes
1330            .panes()
1331            .into_iter()
1332            .find_map(|pane| {
1333                pane.read(cx)
1334                    .items_of_type::<SubView>()
1335                    .position(|view| view.read(cx).view_kind() == item)
1336                    .map(|view| (view, pane))
1337            })
1338            .unwrap();
1339        pane.update(cx, |this, cx| {
1340            this.activate_item(variable_list_position, true, true, window, cx);
1341        })
1342    }
1343
1344    #[cfg(test)]
1345    pub(crate) fn variable_list(&self) -> &Entity<VariableList> {
1346        &self.variable_list
1347    }
1348
1349    #[cfg(test)]
1350    pub(crate) fn serialized_layout(&self, cx: &App) -> SerializedLayout {
1351        persistence::build_serialized_layout(&self.panes.root, self.dock_axis, cx)
1352    }
1353
1354    pub fn capabilities(&self, cx: &App) -> Capabilities {
1355        self.session().read(cx).capabilities().clone()
1356    }
1357
1358    pub fn select_current_thread(
1359        &mut self,
1360        threads: &Vec<(Thread, ThreadStatus)>,
1361        window: &mut Window,
1362        cx: &mut Context<Self>,
1363    ) {
1364        let selected_thread = self
1365            .thread_id
1366            .and_then(|thread_id| threads.iter().find(|(thread, _)| thread.id == thread_id.0))
1367            .or_else(|| threads.first());
1368
1369        let Some((selected_thread, _)) = selected_thread else {
1370            return;
1371        };
1372
1373        if Some(ThreadId(selected_thread.id)) != self.thread_id {
1374            self.select_thread(ThreadId(selected_thread.id), window, cx);
1375        }
1376    }
1377
1378    pub(crate) fn selected_thread_id(&self) -> Option<ThreadId> {
1379        self.thread_id
1380    }
1381
1382    pub fn thread_status(&self, cx: &App) -> Option<ThreadStatus> {
1383        self.thread_id
1384            .map(|id| self.session().read(cx).thread_status(id))
1385    }
1386
1387    pub(crate) fn select_thread(
1388        &mut self,
1389        thread_id: ThreadId,
1390        window: &mut Window,
1391        cx: &mut Context<Self>,
1392    ) {
1393        if self.thread_id.is_some_and(|id| id == thread_id) {
1394            return;
1395        }
1396
1397        self.thread_id = Some(thread_id);
1398
1399        self.stack_frame_list
1400            .update(cx, |list, cx| list.schedule_refresh(true, window, cx));
1401    }
1402
1403    pub fn continue_thread(&mut self, cx: &mut Context<Self>) {
1404        let Some(thread_id) = self.thread_id else {
1405            return;
1406        };
1407
1408        self.session().update(cx, |state, cx| {
1409            state.continue_thread(thread_id, cx);
1410        });
1411    }
1412
1413    pub fn step_over(&mut self, cx: &mut Context<Self>) {
1414        let Some(thread_id) = self.thread_id else {
1415            return;
1416        };
1417
1418        let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1419
1420        self.session().update(cx, |state, cx| {
1421            state.step_over(thread_id, granularity, cx);
1422        });
1423    }
1424
1425    pub(crate) fn step_in(&mut self, cx: &mut Context<Self>) {
1426        let Some(thread_id) = self.thread_id else {
1427            return;
1428        };
1429
1430        let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1431
1432        self.session().update(cx, |state, cx| {
1433            state.step_in(thread_id, granularity, cx);
1434        });
1435    }
1436
1437    pub(crate) fn step_out(&mut self, cx: &mut Context<Self>) {
1438        let Some(thread_id) = self.thread_id else {
1439            return;
1440        };
1441
1442        let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1443
1444        self.session().update(cx, |state, cx| {
1445            state.step_out(thread_id, granularity, cx);
1446        });
1447    }
1448
1449    pub(crate) fn step_back(&mut self, cx: &mut Context<Self>) {
1450        let Some(thread_id) = self.thread_id else {
1451            return;
1452        };
1453
1454        let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1455
1456        self.session().update(cx, |state, cx| {
1457            state.step_back(thread_id, granularity, cx);
1458        });
1459    }
1460
1461    pub fn restart_session(&self, cx: &mut Context<Self>) {
1462        self.session().update(cx, |state, cx| {
1463            state.restart(None, cx);
1464        });
1465    }
1466
1467    pub fn pause_thread(&self, cx: &mut Context<Self>) {
1468        let Some(thread_id) = self.thread_id else {
1469            return;
1470        };
1471
1472        self.session().update(cx, |state, cx| {
1473            state.pause_thread(thread_id, cx);
1474        });
1475    }
1476
1477    pub(crate) fn shutdown(&mut self, cx: &mut Context<Self>) {
1478        self.workspace
1479            .update(cx, |workspace, cx| {
1480                workspace
1481                    .project()
1482                    .read(cx)
1483                    .breakpoint_store()
1484                    .update(cx, |store, cx| {
1485                        store.remove_active_position(Some(self.session_id), cx)
1486                    })
1487            })
1488            .log_err();
1489
1490        self.session.update(cx, |session, cx| {
1491            session.shutdown(cx).detach();
1492        })
1493    }
1494
1495    pub fn stop_thread(&self, cx: &mut Context<Self>) {
1496        let Some(thread_id) = self.thread_id else {
1497            return;
1498        };
1499
1500        self.workspace
1501            .update(cx, |workspace, cx| {
1502                workspace
1503                    .project()
1504                    .read(cx)
1505                    .breakpoint_store()
1506                    .update(cx, |store, cx| {
1507                        store.remove_active_position(Some(self.session_id), cx)
1508                    })
1509            })
1510            .log_err();
1511
1512        self.session().update(cx, |state, cx| {
1513            state.terminate_threads(Some(vec![thread_id; 1]), cx);
1514        });
1515    }
1516
1517    pub fn detach_client(&self, cx: &mut Context<Self>) {
1518        self.session().update(cx, |state, cx| {
1519            state.disconnect_client(cx);
1520        });
1521    }
1522
1523    pub fn toggle_ignore_breakpoints(&mut self, cx: &mut Context<Self>) {
1524        self.session.update(cx, |session, cx| {
1525            session.toggle_ignore_breakpoints(cx).detach();
1526        });
1527    }
1528
1529    fn default_pane_layout(
1530        project: Entity<Project>,
1531        workspace: &WeakEntity<Workspace>,
1532        stack_frame_list: &Entity<StackFrameList>,
1533        variable_list: &Entity<VariableList>,
1534        console: &Entity<Console>,
1535        breakpoints: &Entity<BreakpointList>,
1536        debug_terminal: &Entity<DebugTerminal>,
1537        dock_axis: Axis,
1538        subscriptions: &mut HashMap<EntityId, Subscription>,
1539        window: &mut Window,
1540        cx: &mut Context<'_, RunningState>,
1541    ) -> Member {
1542        let leftmost_pane = new_debugger_pane(workspace.clone(), project.clone(), window, cx);
1543        leftmost_pane.update(cx, |this, cx| {
1544            this.add_item(
1545                Box::new(SubView::new(
1546                    this.focus_handle(cx),
1547                    stack_frame_list.clone().into(),
1548                    DebuggerPaneItem::Frames,
1549                    None,
1550                    cx,
1551                )),
1552                true,
1553                false,
1554                None,
1555                window,
1556                cx,
1557            );
1558            this.add_item(
1559                Box::new(SubView::new(
1560                    breakpoints.focus_handle(cx),
1561                    breakpoints.clone().into(),
1562                    DebuggerPaneItem::BreakpointList,
1563                    None,
1564                    cx,
1565                )),
1566                true,
1567                false,
1568                None,
1569                window,
1570                cx,
1571            );
1572            this.activate_item(0, false, false, window, cx);
1573        });
1574        let center_pane = new_debugger_pane(workspace.clone(), project.clone(), window, cx);
1575
1576        center_pane.update(cx, |this, cx| {
1577            let weak_console = console.downgrade();
1578            this.add_item(
1579                Box::new(SubView::new(
1580                    console.focus_handle(cx),
1581                    console.clone().into(),
1582                    DebuggerPaneItem::Console,
1583                    Some(Box::new(move |cx| {
1584                        weak_console
1585                            .read_with(cx, |console, cx| console.show_indicator(cx))
1586                            .unwrap_or_default()
1587                    })),
1588                    cx,
1589                )),
1590                true,
1591                false,
1592                None,
1593                window,
1594                cx,
1595            );
1596
1597            this.add_item(
1598                Box::new(SubView::new(
1599                    variable_list.focus_handle(cx),
1600                    variable_list.clone().into(),
1601                    DebuggerPaneItem::Variables,
1602                    None,
1603                    cx,
1604                )),
1605                true,
1606                false,
1607                None,
1608                window,
1609                cx,
1610            );
1611            this.activate_item(0, false, false, window, cx);
1612        });
1613
1614        let rightmost_pane = new_debugger_pane(workspace.clone(), project.clone(), window, cx);
1615        rightmost_pane.update(cx, |this, cx| {
1616            this.add_item(
1617                Box::new(SubView::new(
1618                    debug_terminal.focus_handle(cx),
1619                    debug_terminal.clone().into(),
1620                    DebuggerPaneItem::Terminal,
1621                    None,
1622                    cx,
1623                )),
1624                false,
1625                false,
1626                None,
1627                window,
1628                cx,
1629            );
1630        });
1631
1632        subscriptions.extend(
1633            [&leftmost_pane, &center_pane, &rightmost_pane]
1634                .into_iter()
1635                .map(|entity| {
1636                    (
1637                        entity.entity_id(),
1638                        cx.subscribe_in(entity, window, Self::handle_pane_event),
1639                    )
1640                }),
1641        );
1642
1643        let group_root = workspace::PaneAxis::new(
1644            dock_axis.invert(),
1645            [leftmost_pane, center_pane, rightmost_pane]
1646                .into_iter()
1647                .map(workspace::Member::Pane)
1648                .collect(),
1649        );
1650
1651        Member::Axis(group_root)
1652    }
1653
1654    pub(crate) fn invert_axies(&mut self) {
1655        self.dock_axis = self.dock_axis.invert();
1656        self.panes.invert_axies();
1657    }
1658}
1659
1660impl EventEmitter<DebugPanelItemEvent> for RunningState {}
1661
1662impl Focusable for RunningState {
1663    fn focus_handle(&self, _: &App) -> FocusHandle {
1664        self.focus_handle.clone()
1665    }
1666}