running.rs

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