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                        false,
 905                        window,
 906                        cx,
 907                    )
 908                })?;
 909
 910                this.update_in(cx, |this, window, cx| {
 911                    this.ensure_pane_item(DebuggerPaneItem::Terminal, window, cx);
 912                    this.debug_terminal.update(cx, |debug_terminal, cx| {
 913                        debug_terminal.terminal = Some(terminal_view);
 914                        cx.notify();
 915                    });
 916                })?;
 917
 918                let exit_status = terminal
 919                    .read_with(cx, |terminal, cx| terminal.wait_for_completed_task(cx))?
 920                    .await
 921                    .context("Failed to wait for completed task")?;
 922
 923                if !exit_status.success() {
 924                    anyhow::bail!("Build failed");
 925                }
 926                Some((task.resolved.clone(), locator_name))
 927            } else {
 928                None
 929            };
 930
 931            if config_is_valid {
 932                // Ok(DebugTaskDefinition {
 933                //     label,
 934                //     adapter: DebugAdapterName(adapter),
 935                //     config,
 936                //     tcp_connection,
 937                // })
 938            } else if let Some((task, locator_name)) = build_output {
 939                let locator_name =
 940                    locator_name.context("Could not find a valid locator for a build task")?;
 941                let request = dap_store
 942                    .update(cx, |this, cx| {
 943                        this.run_debug_locator(&locator_name, task, cx)
 944                    })?
 945                    .await?;
 946
 947                let zed_config = ZedDebugConfig {
 948                    label: label.clone(),
 949                    adapter: adapter.clone(),
 950                    request,
 951                    stop_on_entry: None,
 952                };
 953
 954                let scenario = dap_registry
 955                    .adapter(&adapter)
 956                    .ok_or_else(|| anyhow!("{}: is not a valid adapter name", &adapter))
 957                    .map(|adapter| adapter.config_from_zed_format(zed_config))??;
 958                config = scenario.config;
 959                Self::substitute_variables_in_config(&mut config, &task_context);
 960            } else {
 961                let Err(e) = request_type else {
 962                    unreachable!();
 963                };
 964                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}");
 965            };
 966
 967            Ok(DebugTaskDefinition {
 968                label,
 969                adapter: DebugAdapterName(adapter),
 970                config,
 971                tcp_connection,
 972            })
 973        })
 974    }
 975
 976    fn handle_run_in_terminal(
 977        &self,
 978        request: &RunInTerminalRequestArguments,
 979        mut sender: mpsc::Sender<Result<u32>>,
 980        window: &mut Window,
 981        cx: &mut Context<Self>,
 982    ) -> Task<Result<()>> {
 983        let running = cx.entity();
 984        let Ok(project) = self
 985            .workspace
 986            .read_with(cx, |workspace, _| workspace.project().clone())
 987        else {
 988            return Task::ready(Err(anyhow!("no workspace")));
 989        };
 990        let session = self.session.read(cx);
 991
 992        let cwd = Some(&request.cwd)
 993            .filter(|cwd| cwd.len() > 0)
 994            .map(PathBuf::from)
 995            .or_else(|| session.binary().cwd.clone());
 996
 997        let mut args = request.args.clone();
 998
 999        // Handle special case for NodeJS debug adapter
1000        // If only the Node binary path is provided, we set the command to None
1001        // This prevents the NodeJS REPL from appearing, which is not the desired behavior
1002        // The expected usage is for users to provide their own Node command, e.g., `node test.js`
1003        // This allows the NodeJS debug client to attach correctly
1004        let command = if args.len() > 1 {
1005            Some(args.remove(0))
1006        } else {
1007            None
1008        };
1009
1010        let mut envs: HashMap<String, String> = Default::default();
1011        if let Some(Value::Object(env)) = &request.env {
1012            for (key, value) in env {
1013                let value_str = match (key.as_str(), value) {
1014                    (_, Value::String(value)) => value,
1015                    _ => continue,
1016                };
1017
1018                envs.insert(key.clone(), value_str.clone());
1019            }
1020        }
1021
1022        let shell = project.read(cx).terminal_settings(&cwd, cx).shell.clone();
1023        let kind = if let Some(command) = command {
1024            let title = request.title.clone().unwrap_or(command.clone());
1025            TerminalKind::Task(task::SpawnInTerminal {
1026                id: task::TaskId("debug".to_string()),
1027                full_label: title.clone(),
1028                label: title.clone(),
1029                command: command.clone(),
1030                args,
1031                command_label: title.clone(),
1032                cwd,
1033                env: envs,
1034                use_new_terminal: true,
1035                allow_concurrent_runs: true,
1036                reveal: task::RevealStrategy::NoFocus,
1037                reveal_target: task::RevealTarget::Dock,
1038                hide: task::HideStrategy::Never,
1039                shell,
1040                show_summary: false,
1041                show_command: false,
1042                show_rerun: false,
1043            })
1044        } else {
1045            TerminalKind::Shell(cwd.map(|c| c.to_path_buf()))
1046        };
1047
1048        let workspace = self.workspace.clone();
1049        let weak_project = project.downgrade();
1050
1051        let terminal_task = project.update(cx, |project, cx| {
1052            project.create_terminal(kind, window.window_handle(), cx)
1053        });
1054        let terminal_task = cx.spawn_in(window, async move |_, cx| {
1055            let terminal = terminal_task.await?;
1056
1057            let terminal_view = cx.new_window_entity(|window, cx| {
1058                TerminalView::new(
1059                    terminal.clone(),
1060                    workspace,
1061                    None,
1062                    weak_project,
1063                    false,
1064                    window,
1065                    cx,
1066                )
1067            })?;
1068
1069            running.update_in(cx, |running, window, cx| {
1070                running.ensure_pane_item(DebuggerPaneItem::Terminal, window, cx);
1071                running.debug_terminal.update(cx, |debug_terminal, cx| {
1072                    debug_terminal.terminal = Some(terminal_view);
1073                    cx.notify();
1074                });
1075            })?;
1076
1077            terminal.read_with(cx, |terminal, _| {
1078                terminal
1079                    .pty_info
1080                    .pid()
1081                    .map(|pid| pid.as_u32())
1082                    .context("Terminal was spawned but PID was not available")
1083            })?
1084        });
1085
1086        cx.background_spawn(async move { anyhow::Ok(sender.send(terminal_task.await).await?) })
1087    }
1088
1089    fn create_sub_view(
1090        &self,
1091        item_kind: DebuggerPaneItem,
1092        _pane: &Entity<Pane>,
1093        cx: &mut Context<Self>,
1094    ) -> Box<dyn ItemHandle> {
1095        match item_kind {
1096            DebuggerPaneItem::Console => {
1097                let weak_console = self.console.clone().downgrade();
1098
1099                Box::new(SubView::new(
1100                    self.console.focus_handle(cx),
1101                    self.console.clone().into(),
1102                    item_kind,
1103                    Some(Box::new(move |cx| {
1104                        weak_console
1105                            .read_with(cx, |console, cx| console.show_indicator(cx))
1106                            .unwrap_or_default()
1107                    })),
1108                    cx,
1109                ))
1110            }
1111            DebuggerPaneItem::Variables => Box::new(SubView::new(
1112                self.variable_list.focus_handle(cx),
1113                self.variable_list.clone().into(),
1114                item_kind,
1115                None,
1116                cx,
1117            )),
1118            DebuggerPaneItem::BreakpointList => Box::new(SubView::new(
1119                self.breakpoint_list.focus_handle(cx),
1120                self.breakpoint_list.clone().into(),
1121                item_kind,
1122                None,
1123                cx,
1124            )),
1125            DebuggerPaneItem::Frames => Box::new(SubView::new(
1126                self.stack_frame_list.focus_handle(cx),
1127                self.stack_frame_list.clone().into(),
1128                item_kind,
1129                None,
1130                cx,
1131            )),
1132            DebuggerPaneItem::Modules => Box::new(SubView::new(
1133                self.module_list.focus_handle(cx),
1134                self.module_list.clone().into(),
1135                item_kind,
1136                None,
1137                cx,
1138            )),
1139            DebuggerPaneItem::LoadedSources => Box::new(SubView::new(
1140                self.loaded_sources_list.focus_handle(cx),
1141                self.loaded_sources_list.clone().into(),
1142                item_kind,
1143                None,
1144                cx,
1145            )),
1146            DebuggerPaneItem::Terminal => Box::new(SubView::new(
1147                self.debug_terminal.focus_handle(cx),
1148                self.debug_terminal.clone().into(),
1149                item_kind,
1150                None,
1151                cx,
1152            )),
1153        }
1154    }
1155
1156    pub(crate) fn ensure_pane_item(
1157        &mut self,
1158        item_kind: DebuggerPaneItem,
1159        window: &mut Window,
1160        cx: &mut Context<Self>,
1161    ) {
1162        if self.pane_items_status(cx).get(&item_kind) == Some(&true) {
1163            return;
1164        };
1165        let pane = self.panes.last_pane();
1166        let sub_view = self.create_sub_view(item_kind, &pane, cx);
1167
1168        pane.update(cx, |pane, cx| {
1169            pane.add_item_inner(sub_view, false, false, false, None, window, cx);
1170        })
1171    }
1172
1173    pub(crate) fn add_pane_item(
1174        &mut self,
1175        item_kind: DebuggerPaneItem,
1176        position: Point<Pixels>,
1177        window: &mut Window,
1178        cx: &mut Context<Self>,
1179    ) {
1180        debug_assert!(
1181            item_kind.is_supported(self.session.read(cx).capabilities()),
1182            "We should only allow adding supported item kinds"
1183        );
1184
1185        if let Some(pane) = self.panes.pane_at_pixel_position(position) {
1186            let sub_view = self.create_sub_view(item_kind, pane, cx);
1187
1188            pane.update(cx, |pane, cx| {
1189                pane.add_item(sub_view, false, false, None, window, cx);
1190            })
1191        }
1192    }
1193
1194    pub(crate) fn pane_items_status(&self, cx: &App) -> IndexMap<DebuggerPaneItem, bool> {
1195        let caps = self.session.read(cx).capabilities();
1196        let mut pane_item_status = IndexMap::from_iter(
1197            DebuggerPaneItem::all()
1198                .iter()
1199                .filter(|kind| kind.is_supported(&caps))
1200                .map(|kind| (*kind, false)),
1201        );
1202        self.panes.panes().iter().for_each(|pane| {
1203            pane.read(cx)
1204                .items()
1205                .filter_map(|item| item.act_as::<SubView>(cx))
1206                .for_each(|view| {
1207                    pane_item_status.insert(view.read(cx).kind, true);
1208                });
1209        });
1210
1211        pane_item_status
1212    }
1213
1214    pub(crate) fn serialize_layout(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1215        if self._schedule_serialize.is_none() {
1216            self._schedule_serialize = Some(cx.spawn_in(window, async move |this, cx| {
1217                cx.background_executor()
1218                    .timer(Duration::from_millis(100))
1219                    .await;
1220
1221                let Some((adapter_name, pane_layout)) = this
1222                    .read_with(cx, |this, cx| {
1223                        let adapter_name = this.session.read(cx).adapter();
1224                        (
1225                            adapter_name,
1226                            persistence::build_serialized_layout(
1227                                &this.panes.root,
1228                                this.dock_axis,
1229                                cx,
1230                            ),
1231                        )
1232                    })
1233                    .ok()
1234                else {
1235                    return;
1236                };
1237
1238                persistence::serialize_pane_layout(adapter_name, pane_layout)
1239                    .await
1240                    .log_err();
1241
1242                this.update(cx, |this, _| {
1243                    this._schedule_serialize.take();
1244                })
1245                .ok();
1246            }));
1247        }
1248    }
1249
1250    pub(crate) fn handle_pane_event(
1251        this: &mut RunningState,
1252        source_pane: &Entity<Pane>,
1253        event: &Event,
1254        window: &mut Window,
1255        cx: &mut Context<RunningState>,
1256    ) {
1257        this.serialize_layout(window, cx);
1258        match event {
1259            Event::Remove { .. } => {
1260                let _did_find_pane = this.panes.remove(&source_pane).is_ok();
1261                debug_assert!(_did_find_pane);
1262                cx.notify();
1263            }
1264            Event::Focus => {
1265                this.active_pane = source_pane.clone();
1266            }
1267            _ => {}
1268        }
1269    }
1270
1271    pub(crate) fn activate_pane_in_direction(
1272        &mut self,
1273        direction: SplitDirection,
1274        window: &mut Window,
1275        cx: &mut Context<Self>,
1276    ) {
1277        let active_pane = self.active_pane.clone();
1278        if let Some(pane) = self
1279            .panes
1280            .find_pane_in_direction(&active_pane, direction, cx)
1281        {
1282            pane.update(cx, |pane, cx| {
1283                pane.focus_active_item(window, cx);
1284            })
1285        } else {
1286            self.workspace
1287                .update(cx, |workspace, cx| {
1288                    workspace.activate_pane_in_direction(direction, window, cx)
1289                })
1290                .ok();
1291        }
1292    }
1293
1294    pub(crate) fn go_to_selected_stack_frame(&self, window: &mut Window, cx: &mut Context<Self>) {
1295        if self.thread_id.is_some() {
1296            self.stack_frame_list
1297                .update(cx, |list, cx| {
1298                    let Some(stack_frame_id) = list.opened_stack_frame_id() else {
1299                        return Task::ready(Ok(()));
1300                    };
1301                    list.go_to_stack_frame(stack_frame_id, window, cx)
1302                })
1303                .detach();
1304        }
1305    }
1306
1307    pub(crate) fn has_open_context_menu(&self, cx: &App) -> bool {
1308        self.variable_list.read(cx).has_open_context_menu()
1309    }
1310
1311    pub fn session(&self) -> &Entity<Session> {
1312        &self.session
1313    }
1314
1315    pub fn session_id(&self) -> SessionId {
1316        self.session_id
1317    }
1318
1319    pub(crate) fn selected_stack_frame_id(&self, cx: &App) -> Option<dap::StackFrameId> {
1320        self.stack_frame_list.read(cx).opened_stack_frame_id()
1321    }
1322
1323    pub(crate) fn stack_frame_list(&self) -> &Entity<StackFrameList> {
1324        &self.stack_frame_list
1325    }
1326
1327    #[cfg(test)]
1328    pub fn console(&self) -> &Entity<Console> {
1329        &self.console
1330    }
1331
1332    #[cfg(test)]
1333    pub(crate) fn module_list(&self) -> &Entity<ModuleList> {
1334        &self.module_list
1335    }
1336
1337    pub(crate) fn activate_item(&self, item: DebuggerPaneItem, window: &mut Window, cx: &mut App) {
1338        let (variable_list_position, pane) = self
1339            .panes
1340            .panes()
1341            .into_iter()
1342            .find_map(|pane| {
1343                pane.read(cx)
1344                    .items_of_type::<SubView>()
1345                    .position(|view| view.read(cx).view_kind() == item)
1346                    .map(|view| (view, pane))
1347            })
1348            .unwrap();
1349        pane.update(cx, |this, cx| {
1350            this.activate_item(variable_list_position, true, true, window, cx);
1351        })
1352    }
1353
1354    #[cfg(test)]
1355    pub(crate) fn variable_list(&self) -> &Entity<VariableList> {
1356        &self.variable_list
1357    }
1358
1359    #[cfg(test)]
1360    pub(crate) fn serialized_layout(&self, cx: &App) -> SerializedLayout {
1361        persistence::build_serialized_layout(&self.panes.root, self.dock_axis, cx)
1362    }
1363
1364    pub fn capabilities(&self, cx: &App) -> Capabilities {
1365        self.session().read(cx).capabilities().clone()
1366    }
1367
1368    pub fn select_current_thread(
1369        &mut self,
1370        threads: &Vec<(Thread, ThreadStatus)>,
1371        window: &mut Window,
1372        cx: &mut Context<Self>,
1373    ) {
1374        let selected_thread = self
1375            .thread_id
1376            .and_then(|thread_id| threads.iter().find(|(thread, _)| thread.id == thread_id.0))
1377            .or_else(|| threads.first());
1378
1379        let Some((selected_thread, _)) = selected_thread else {
1380            return;
1381        };
1382
1383        if Some(ThreadId(selected_thread.id)) != self.thread_id {
1384            self.select_thread(ThreadId(selected_thread.id), window, cx);
1385        }
1386    }
1387
1388    pub(crate) fn selected_thread_id(&self) -> Option<ThreadId> {
1389        self.thread_id
1390    }
1391
1392    pub fn thread_status(&self, cx: &App) -> Option<ThreadStatus> {
1393        self.thread_id
1394            .map(|id| self.session().read(cx).thread_status(id))
1395    }
1396
1397    pub(crate) fn select_thread(
1398        &mut self,
1399        thread_id: ThreadId,
1400        window: &mut Window,
1401        cx: &mut Context<Self>,
1402    ) {
1403        if self.thread_id.is_some_and(|id| id == thread_id) {
1404            return;
1405        }
1406
1407        self.thread_id = Some(thread_id);
1408
1409        self.stack_frame_list
1410            .update(cx, |list, cx| list.schedule_refresh(true, window, cx));
1411    }
1412
1413    pub fn continue_thread(&mut self, cx: &mut Context<Self>) {
1414        let Some(thread_id) = self.thread_id else {
1415            return;
1416        };
1417
1418        self.session().update(cx, |state, cx| {
1419            state.continue_thread(thread_id, cx);
1420        });
1421    }
1422
1423    pub fn step_over(&mut self, cx: &mut Context<Self>) {
1424        let Some(thread_id) = self.thread_id else {
1425            return;
1426        };
1427
1428        let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1429
1430        self.session().update(cx, |state, cx| {
1431            state.step_over(thread_id, granularity, cx);
1432        });
1433    }
1434
1435    pub(crate) fn step_in(&mut self, cx: &mut Context<Self>) {
1436        let Some(thread_id) = self.thread_id else {
1437            return;
1438        };
1439
1440        let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1441
1442        self.session().update(cx, |state, cx| {
1443            state.step_in(thread_id, granularity, cx);
1444        });
1445    }
1446
1447    pub(crate) fn step_out(&mut self, cx: &mut Context<Self>) {
1448        let Some(thread_id) = self.thread_id else {
1449            return;
1450        };
1451
1452        let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1453
1454        self.session().update(cx, |state, cx| {
1455            state.step_out(thread_id, granularity, cx);
1456        });
1457    }
1458
1459    pub(crate) fn step_back(&mut self, cx: &mut Context<Self>) {
1460        let Some(thread_id) = self.thread_id else {
1461            return;
1462        };
1463
1464        let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
1465
1466        self.session().update(cx, |state, cx| {
1467            state.step_back(thread_id, granularity, cx);
1468        });
1469    }
1470
1471    pub fn restart_session(&self, cx: &mut Context<Self>) {
1472        self.session().update(cx, |state, cx| {
1473            state.restart(None, cx);
1474        });
1475    }
1476
1477    pub fn pause_thread(&self, cx: &mut Context<Self>) {
1478        let Some(thread_id) = self.thread_id else {
1479            return;
1480        };
1481
1482        self.session().update(cx, |state, cx| {
1483            state.pause_thread(thread_id, cx);
1484        });
1485    }
1486
1487    pub(crate) fn shutdown(&mut self, cx: &mut Context<Self>) {
1488        self.workspace
1489            .update(cx, |workspace, cx| {
1490                workspace
1491                    .project()
1492                    .read(cx)
1493                    .breakpoint_store()
1494                    .update(cx, |store, cx| {
1495                        store.remove_active_position(Some(self.session_id), cx)
1496                    })
1497            })
1498            .log_err();
1499
1500        self.session.update(cx, |session, cx| {
1501            session.shutdown(cx).detach();
1502        })
1503    }
1504
1505    pub fn stop_thread(&self, cx: &mut Context<Self>) {
1506        let Some(thread_id) = self.thread_id else {
1507            return;
1508        };
1509
1510        self.workspace
1511            .update(cx, |workspace, cx| {
1512                workspace
1513                    .project()
1514                    .read(cx)
1515                    .breakpoint_store()
1516                    .update(cx, |store, cx| {
1517                        store.remove_active_position(Some(self.session_id), cx)
1518                    })
1519            })
1520            .log_err();
1521
1522        self.session().update(cx, |state, cx| {
1523            state.terminate_threads(Some(vec![thread_id; 1]), cx);
1524        });
1525    }
1526
1527    pub fn detach_client(&self, cx: &mut Context<Self>) {
1528        self.session().update(cx, |state, cx| {
1529            state.disconnect_client(cx);
1530        });
1531    }
1532
1533    pub fn toggle_ignore_breakpoints(&mut self, cx: &mut Context<Self>) {
1534        self.session.update(cx, |session, cx| {
1535            session.toggle_ignore_breakpoints(cx).detach();
1536        });
1537    }
1538
1539    fn default_pane_layout(
1540        project: Entity<Project>,
1541        workspace: &WeakEntity<Workspace>,
1542        stack_frame_list: &Entity<StackFrameList>,
1543        variable_list: &Entity<VariableList>,
1544        console: &Entity<Console>,
1545        breakpoints: &Entity<BreakpointList>,
1546        debug_terminal: &Entity<DebugTerminal>,
1547        dock_axis: Axis,
1548        subscriptions: &mut HashMap<EntityId, Subscription>,
1549        window: &mut Window,
1550        cx: &mut Context<'_, RunningState>,
1551    ) -> Member {
1552        let leftmost_pane = new_debugger_pane(workspace.clone(), project.clone(), window, cx);
1553        leftmost_pane.update(cx, |this, cx| {
1554            this.add_item(
1555                Box::new(SubView::new(
1556                    this.focus_handle(cx),
1557                    stack_frame_list.clone().into(),
1558                    DebuggerPaneItem::Frames,
1559                    None,
1560                    cx,
1561                )),
1562                true,
1563                false,
1564                None,
1565                window,
1566                cx,
1567            );
1568            this.add_item(
1569                Box::new(SubView::new(
1570                    breakpoints.focus_handle(cx),
1571                    breakpoints.clone().into(),
1572                    DebuggerPaneItem::BreakpointList,
1573                    None,
1574                    cx,
1575                )),
1576                true,
1577                false,
1578                None,
1579                window,
1580                cx,
1581            );
1582            this.activate_item(0, false, false, window, cx);
1583        });
1584        let center_pane = new_debugger_pane(workspace.clone(), project.clone(), window, cx);
1585
1586        center_pane.update(cx, |this, cx| {
1587            let weak_console = console.downgrade();
1588            this.add_item(
1589                Box::new(SubView::new(
1590                    console.focus_handle(cx),
1591                    console.clone().into(),
1592                    DebuggerPaneItem::Console,
1593                    Some(Box::new(move |cx| {
1594                        weak_console
1595                            .read_with(cx, |console, cx| console.show_indicator(cx))
1596                            .unwrap_or_default()
1597                    })),
1598                    cx,
1599                )),
1600                true,
1601                false,
1602                None,
1603                window,
1604                cx,
1605            );
1606
1607            this.add_item(
1608                Box::new(SubView::new(
1609                    variable_list.focus_handle(cx),
1610                    variable_list.clone().into(),
1611                    DebuggerPaneItem::Variables,
1612                    None,
1613                    cx,
1614                )),
1615                true,
1616                false,
1617                None,
1618                window,
1619                cx,
1620            );
1621            this.activate_item(0, false, false, window, cx);
1622        });
1623
1624        let rightmost_pane = new_debugger_pane(workspace.clone(), project.clone(), window, cx);
1625        rightmost_pane.update(cx, |this, cx| {
1626            this.add_item(
1627                Box::new(SubView::new(
1628                    debug_terminal.focus_handle(cx),
1629                    debug_terminal.clone().into(),
1630                    DebuggerPaneItem::Terminal,
1631                    None,
1632                    cx,
1633                )),
1634                false,
1635                false,
1636                None,
1637                window,
1638                cx,
1639            );
1640        });
1641
1642        subscriptions.extend(
1643            [&leftmost_pane, &center_pane, &rightmost_pane]
1644                .into_iter()
1645                .map(|entity| {
1646                    (
1647                        entity.entity_id(),
1648                        cx.subscribe_in(entity, window, Self::handle_pane_event),
1649                    )
1650                }),
1651        );
1652
1653        let group_root = workspace::PaneAxis::new(
1654            dock_axis.invert(),
1655            [leftmost_pane, center_pane, rightmost_pane]
1656                .into_iter()
1657                .map(workspace::Member::Pane)
1658                .collect(),
1659        );
1660
1661        Member::Axis(group_root)
1662    }
1663
1664    pub(crate) fn invert_axies(&mut self) {
1665        self.dock_axis = self.dock_axis.invert();
1666        self.panes.invert_axies();
1667    }
1668}
1669
1670impl EventEmitter<DebugPanelItemEvent> for RunningState {}
1671
1672impl Focusable for RunningState {
1673    fn focus_handle(&self, _: &App) -> FocusHandle {
1674        self.focus_handle.clone()
1675    }
1676}