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