running.rs

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