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, sync::Arc, time::Duration};
   9
  10use crate::persistence::{self, DebuggerPaneItem, SerializedPaneLayout};
  11
  12use super::DebugPanelItemEvent;
  13use breakpoint_list::BreakpointList;
  14use collections::{HashMap, IndexMap};
  15use console::Console;
  16use dap::{Capabilities, Thread, client::SessionId, debugger_settings::DebuggerSettings};
  17use gpui::{
  18    Action as _, AnyView, AppContext, Entity, EntityId, EventEmitter, FocusHandle, Focusable,
  19    NoAction, Pixels, Point, Subscription, Task, WeakEntity,
  20};
  21use loaded_source_list::LoadedSourceList;
  22use module_list::ModuleList;
  23use project::{
  24    Project,
  25    debugger::session::{Session, SessionEvent, ThreadId, ThreadStatus},
  26};
  27use rpc::proto::ViewId;
  28use settings::Settings;
  29use stack_frame_list::StackFrameList;
  30use terminal_view::TerminalView;
  31use ui::{
  32    ActiveTheme, AnyElement, App, ButtonCommon as _, Clickable as _, Context, ContextMenu,
  33    DropdownMenu, FluentBuilder, IconButton, IconName, IconSize, InteractiveElement, IntoElement,
  34    Label, LabelCommon as _, ParentElement, Render, SharedString, StatefulInteractiveElement,
  35    Styled, Tab, Tooltip, Window, div, h_flex, v_flex,
  36};
  37use util::ResultExt;
  38use variable_list::VariableList;
  39use workspace::{
  40    ActivePaneDecorator, DraggedTab, Item, ItemHandle, Member, Pane, PaneGroup, SplitDirection,
  41    Workspace, item::TabContentParams, move_item, pane::Event,
  42};
  43
  44pub struct RunningState {
  45    session: Entity<Session>,
  46    thread_id: Option<ThreadId>,
  47    focus_handle: FocusHandle,
  48    _remote_id: Option<ViewId>,
  49    workspace: WeakEntity<Workspace>,
  50    session_id: SessionId,
  51    variable_list: Entity<variable_list::VariableList>,
  52    _subscriptions: Vec<Subscription>,
  53    stack_frame_list: Entity<stack_frame_list::StackFrameList>,
  54    loaded_sources_list: Entity<LoadedSourceList>,
  55    pub debug_terminal: Entity<DebugTerminal>,
  56    module_list: Entity<module_list::ModuleList>,
  57    _console: Entity<Console>,
  58    breakpoint_list: Entity<BreakpointList>,
  59    panes: PaneGroup,
  60    active_pane: Option<Entity<Pane>>,
  61    pane_close_subscriptions: HashMap<EntityId, Subscription>,
  62    _schedule_serialize: Option<Task<()>>,
  63}
  64
  65impl Render for RunningState {
  66    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
  67        let zoomed_pane = self
  68            .panes
  69            .panes()
  70            .into_iter()
  71            .find(|pane| pane.read(cx).is_zoomed());
  72
  73        let active = self.panes.panes().into_iter().next();
  74        let x = if let Some(ref zoomed_pane) = zoomed_pane {
  75            zoomed_pane.update(cx, |pane, cx| pane.render(window, cx).into_any_element())
  76        } else if let Some(active) = active {
  77            self.panes
  78                .render(
  79                    None,
  80                    &ActivePaneDecorator::new(active, &self.workspace),
  81                    window,
  82                    cx,
  83                )
  84                .into_any_element()
  85        } else {
  86            div().into_any_element()
  87        };
  88        let thread_status = self
  89            .thread_id
  90            .map(|thread_id| self.session.read(cx).thread_status(thread_id))
  91            .unwrap_or(ThreadStatus::Exited);
  92
  93        self.variable_list.update(cx, |this, cx| {
  94            this.disabled(thread_status != ThreadStatus::Stopped, cx);
  95        });
  96        v_flex()
  97            .size_full()
  98            .key_context("DebugSessionItem")
  99            .track_focus(&self.focus_handle(cx))
 100            .child(h_flex().flex_1().child(x))
 101    }
 102}
 103
 104pub(crate) struct SubView {
 105    inner: AnyView,
 106    pane_focus_handle: FocusHandle,
 107    kind: DebuggerPaneItem,
 108    show_indicator: Box<dyn Fn(&App) -> bool>,
 109}
 110
 111impl SubView {
 112    pub(crate) fn new(
 113        pane_focus_handle: FocusHandle,
 114        view: AnyView,
 115        kind: DebuggerPaneItem,
 116        show_indicator: Option<Box<dyn Fn(&App) -> bool>>,
 117        cx: &mut App,
 118    ) -> Entity<Self> {
 119        cx.new(|_| Self {
 120            kind,
 121            inner: view,
 122            pane_focus_handle,
 123            show_indicator: show_indicator.unwrap_or(Box::new(|_| false)),
 124        })
 125    }
 126
 127    pub(crate) fn view_kind(&self) -> DebuggerPaneItem {
 128        self.kind
 129    }
 130}
 131impl Focusable for SubView {
 132    fn focus_handle(&self, _: &App) -> FocusHandle {
 133        self.pane_focus_handle.clone()
 134    }
 135}
 136impl EventEmitter<()> for SubView {}
 137impl Item for SubView {
 138    type Event = ();
 139
 140    /// This is used to serialize debugger pane layouts
 141    /// A SharedString gets converted to a enum and back during serialization/deserialization.
 142    fn tab_content_text(&self, _window: &Window, _cx: &App) -> Option<SharedString> {
 143        Some(self.kind.to_shared_string())
 144    }
 145
 146    fn tab_content(
 147        &self,
 148        params: workspace::item::TabContentParams,
 149        _: &Window,
 150        cx: &App,
 151    ) -> AnyElement {
 152        let label = Label::new(self.kind.to_shared_string())
 153            .size(ui::LabelSize::Small)
 154            .color(params.text_color())
 155            .line_height_style(ui::LineHeightStyle::UiLabel);
 156
 157        if !params.selected && self.show_indicator.as_ref()(cx) {
 158            return h_flex()
 159                .justify_between()
 160                .child(ui::Indicator::dot())
 161                .gap_2()
 162                .child(label)
 163                .into_any_element();
 164        }
 165
 166        label.into_any_element()
 167    }
 168}
 169
 170impl Render for SubView {
 171    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 172        v_flex()
 173            .size_full()
 174            .when(self.pane_focus_handle.contains_focused(window, cx), |el| {
 175                // TODO better way of showing focus?
 176                el.border_1().border_color(gpui::red())
 177            })
 178            .child(self.inner.clone())
 179    }
 180}
 181
 182pub(crate) fn new_debugger_pane(
 183    workspace: WeakEntity<Workspace>,
 184    project: Entity<Project>,
 185    window: &mut Window,
 186    cx: &mut Context<RunningState>,
 187) -> Entity<Pane> {
 188    let weak_running = cx.weak_entity();
 189    let custom_drop_handle = {
 190        let workspace = workspace.clone();
 191        let project = project.downgrade();
 192        let weak_running = weak_running.clone();
 193        move |pane: &mut Pane, any: &dyn Any, window: &mut Window, cx: &mut Context<Pane>| {
 194            let Some(tab) = any.downcast_ref::<DraggedTab>() else {
 195                return ControlFlow::Break(());
 196            };
 197            let Some(project) = project.upgrade() else {
 198                return ControlFlow::Break(());
 199            };
 200            let this_pane = cx.entity().clone();
 201            let item = if tab.pane == this_pane {
 202                pane.item_for_index(tab.ix)
 203            } else {
 204                tab.pane.read(cx).item_for_index(tab.ix)
 205            };
 206            let Some(item) = item.filter(|item| item.downcast::<SubView>().is_some()) else {
 207                return ControlFlow::Break(());
 208            };
 209
 210            let source = tab.pane.clone();
 211            let item_id_to_move = item.item_id();
 212
 213            let Ok(new_split_pane) = pane
 214                .drag_split_direction()
 215                .map(|split_direction| {
 216                    weak_running.update(cx, |running, cx| {
 217                        let new_pane =
 218                            new_debugger_pane(workspace.clone(), project.clone(), window, cx);
 219                        let _previous_subscription = running.pane_close_subscriptions.insert(
 220                            new_pane.entity_id(),
 221                            cx.subscribe_in(&new_pane, window, RunningState::handle_pane_event),
 222                        );
 223                        debug_assert!(_previous_subscription.is_none());
 224                        running
 225                            .panes
 226                            .split(&this_pane, &new_pane, split_direction)?;
 227                        anyhow::Ok(new_pane)
 228                    })
 229                })
 230                .transpose()
 231            else {
 232                return ControlFlow::Break(());
 233            };
 234
 235            match new_split_pane.transpose() {
 236                // Source pane may be the one currently updated, so defer the move.
 237                Ok(Some(new_pane)) => cx
 238                    .spawn_in(window, async move |_, cx| {
 239                        cx.update(|window, cx| {
 240                            move_item(
 241                                &source,
 242                                &new_pane,
 243                                item_id_to_move,
 244                                new_pane.read(cx).active_item_index(),
 245                                window,
 246                                cx,
 247                            );
 248                        })
 249                        .ok();
 250                    })
 251                    .detach(),
 252                // If we drop into existing pane or current pane,
 253                // regular pane drop handler will take care of it,
 254                // using the right tab index for the operation.
 255                Ok(None) => return ControlFlow::Continue(()),
 256                err @ Err(_) => {
 257                    err.log_err();
 258                    return ControlFlow::Break(());
 259                }
 260            };
 261
 262            ControlFlow::Break(())
 263        }
 264    };
 265
 266    let ret = cx.new(move |cx| {
 267        let mut pane = Pane::new(
 268            workspace.clone(),
 269            project.clone(),
 270            Default::default(),
 271            None,
 272            NoAction.boxed_clone(),
 273            window,
 274            cx,
 275        );
 276        let focus_handle = pane.focus_handle(cx);
 277        pane.set_can_split(Some(Arc::new({
 278            let weak_running = weak_running.clone();
 279            move |pane, dragged_item, _window, cx| {
 280                if let Some(tab) = dragged_item.downcast_ref::<DraggedTab>() {
 281                    let is_current_pane = tab.pane == cx.entity();
 282                    let Some(can_drag_away) = weak_running
 283                        .update(cx, |running_state, _| {
 284                            let current_panes = running_state.panes.panes();
 285                            !current_panes.contains(&&tab.pane)
 286                                || current_panes.len() > 1
 287                                || (!is_current_pane || pane.items_len() > 1)
 288                        })
 289                        .ok()
 290                    else {
 291                        return false;
 292                    };
 293                    if can_drag_away {
 294                        let item = if is_current_pane {
 295                            pane.item_for_index(tab.ix)
 296                        } else {
 297                            tab.pane.read(cx).item_for_index(tab.ix)
 298                        };
 299                        if let Some(item) = item {
 300                            return item.downcast::<SubView>().is_some();
 301                        }
 302                    }
 303                }
 304                false
 305            }
 306        })));
 307        pane.display_nav_history_buttons(None);
 308        pane.set_custom_drop_handle(cx, custom_drop_handle);
 309        pane.set_should_display_tab_bar(|_, _| true);
 310        pane.set_render_tab_bar_buttons(cx, |_, _, _| (None, None));
 311        pane.set_render_tab_bar(cx, {
 312            move |pane, window, cx| {
 313                let active_pane_item = pane.active_item();
 314                h_flex()
 315                    .justify_between()
 316                    .bg(cx.theme().colors().tab_bar_background)
 317                    .border_b_1()
 318                    .border_color(cx.theme().colors().border)
 319                    .track_focus(&focus_handle)
 320                    .child(
 321                        h_flex()
 322                            .w_full()
 323                            .px_2()
 324                            .gap_1()
 325                            .h(Tab::container_height(cx))
 326                            .drag_over::<DraggedTab>(|bar, _, _, cx| {
 327                                bar.bg(cx.theme().colors().drop_target_background)
 328                            })
 329                            .on_drop(cx.listener(
 330                                move |this, dragged_tab: &DraggedTab, window, cx| {
 331                                    this.drag_split_direction = None;
 332                                    this.handle_tab_drop(dragged_tab, this.items_len(), window, cx)
 333                                },
 334                            ))
 335                            .children(pane.items().enumerate().map(|(ix, item)| {
 336                                let selected = active_pane_item
 337                                    .as_ref()
 338                                    .map_or(false, |active| active.item_id() == item.item_id());
 339                                let item_ = item.boxed_clone();
 340                                div()
 341                                    .id(SharedString::from(format!(
 342                                        "debugger_tab_{}",
 343                                        item.item_id().as_u64()
 344                                    )))
 345                                    .p_1()
 346                                    .rounded_md()
 347                                    .cursor_pointer()
 348                                    .map(|this| {
 349                                        if selected {
 350                                            this.bg(cx.theme().colors().tab_active_background)
 351                                        } else {
 352                                            let hover_color = cx.theme().colors().element_hover;
 353                                            this.hover(|style| style.bg(hover_color))
 354                                        }
 355                                    })
 356                                    .on_click(cx.listener(move |this, _, window, cx| {
 357                                        let index = this.index_for_item(&*item_);
 358                                        if let Some(index) = index {
 359                                            this.activate_item(index, true, true, window, cx);
 360                                        }
 361                                    }))
 362                                    .child(item.tab_content(
 363                                        TabContentParams {
 364                                            selected,
 365                                            ..Default::default()
 366                                        },
 367                                        window,
 368                                        cx,
 369                                    ))
 370                                    .on_drop(cx.listener(
 371                                        move |this, dragged_tab: &DraggedTab, window, cx| {
 372                                            this.drag_split_direction = None;
 373                                            this.handle_tab_drop(dragged_tab, ix, window, cx)
 374                                        },
 375                                    ))
 376                                    .on_drag(
 377                                        DraggedTab {
 378                                            item: item.boxed_clone(),
 379                                            pane: cx.entity().clone(),
 380                                            detail: 0,
 381                                            is_active: selected,
 382                                            ix,
 383                                        },
 384                                        |tab, _, _, cx| cx.new(|_| tab.clone()),
 385                                    )
 386                            })),
 387                    )
 388                    .child({
 389                        let zoomed = pane.is_zoomed();
 390                        IconButton::new(
 391                            "debug-toggle-zoom",
 392                            if zoomed {
 393                                IconName::Minimize
 394                            } else {
 395                                IconName::Maximize
 396                            },
 397                        )
 398                        .icon_size(IconSize::Small)
 399                        .on_click(cx.listener(move |pane, _, window, cx| {
 400                            pane.toggle_zoom(&workspace::ToggleZoom, window, cx);
 401                        }))
 402                        .tooltip({
 403                            let focus_handle = focus_handle.clone();
 404                            move |window, cx| {
 405                                let zoomed_text = if zoomed { "Zoom Out" } else { "Zoom In" };
 406                                Tooltip::for_action_in(
 407                                    zoomed_text,
 408                                    &workspace::ToggleZoom,
 409                                    &focus_handle,
 410                                    window,
 411                                    cx,
 412                                )
 413                            }
 414                        })
 415                    })
 416                    .into_any_element()
 417            }
 418        });
 419        pane
 420    });
 421
 422    ret
 423}
 424
 425pub struct DebugTerminal {
 426    pub terminal: Option<Entity<TerminalView>>,
 427    focus_handle: FocusHandle,
 428}
 429
 430impl DebugTerminal {
 431    fn empty(cx: &mut Context<Self>) -> Self {
 432        Self {
 433            terminal: None,
 434            focus_handle: cx.focus_handle(),
 435        }
 436    }
 437}
 438
 439impl gpui::Render for DebugTerminal {
 440    fn render(&mut self, _window: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
 441        if let Some(terminal) = self.terminal.clone() {
 442            terminal.into_any_element()
 443        } else {
 444            div().track_focus(&self.focus_handle).into_any_element()
 445        }
 446    }
 447}
 448impl Focusable for DebugTerminal {
 449    fn focus_handle(&self, cx: &App) -> FocusHandle {
 450        if let Some(terminal) = self.terminal.as_ref() {
 451            return terminal.focus_handle(cx);
 452        } else {
 453            self.focus_handle.clone()
 454        }
 455    }
 456}
 457
 458impl RunningState {
 459    pub fn new(
 460        session: Entity<Session>,
 461        project: Entity<Project>,
 462        workspace: WeakEntity<Workspace>,
 463        serialized_pane_layout: Option<SerializedPaneLayout>,
 464        window: &mut Window,
 465        cx: &mut Context<Self>,
 466    ) -> Self {
 467        let focus_handle = cx.focus_handle();
 468        let session_id = session.read(cx).session_id();
 469        let weak_state = cx.weak_entity();
 470        let stack_frame_list = cx.new(|cx| {
 471            StackFrameList::new(workspace.clone(), session.clone(), weak_state, window, cx)
 472        });
 473
 474        let debug_terminal = cx.new(DebugTerminal::empty);
 475
 476        let variable_list =
 477            cx.new(|cx| VariableList::new(session.clone(), stack_frame_list.clone(), window, cx));
 478
 479        let module_list = cx.new(|cx| ModuleList::new(session.clone(), workspace.clone(), cx));
 480
 481        let loaded_source_list = cx.new(|cx| LoadedSourceList::new(session.clone(), cx));
 482
 483        let console = cx.new(|cx| {
 484            Console::new(
 485                session.clone(),
 486                stack_frame_list.clone(),
 487                variable_list.clone(),
 488                window,
 489                cx,
 490            )
 491        });
 492
 493        let breakpoint_list = BreakpointList::new(session.clone(), workspace.clone(), &project, cx);
 494
 495        let _subscriptions = vec![
 496            cx.observe(&module_list, |_, _, cx| cx.notify()),
 497            cx.subscribe_in(&session, window, |this, _, event, window, cx| {
 498                match event {
 499                    SessionEvent::Stopped(thread_id) => {
 500                        this.workspace
 501                            .update(cx, |workspace, cx| {
 502                                workspace.open_panel::<crate::DebugPanel>(window, cx);
 503                            })
 504                            .log_err();
 505
 506                        if let Some(thread_id) = thread_id {
 507                            this.select_thread(*thread_id, window, cx);
 508                        }
 509                    }
 510                    SessionEvent::Threads => {
 511                        let threads = this.session.update(cx, |this, cx| this.threads(cx));
 512                        this.select_current_thread(&threads, window, cx);
 513                    }
 514                    SessionEvent::CapabilitiesLoaded => {
 515                        let capabilities = this.capabilities(cx);
 516                        if !capabilities.supports_modules_request.unwrap_or(false) {
 517                            this.remove_pane_item(DebuggerPaneItem::Modules, window, cx);
 518                        }
 519                        if !capabilities
 520                            .supports_loaded_sources_request
 521                            .unwrap_or(false)
 522                        {
 523                            this.remove_pane_item(DebuggerPaneItem::LoadedSources, window, cx);
 524                        }
 525                    }
 526
 527                    _ => {}
 528                }
 529                cx.notify()
 530            }),
 531            cx.on_focus_out(&focus_handle, window, |this, _, window, cx| {
 532                this.serialize_layout(window, cx);
 533            }),
 534        ];
 535
 536        let mut pane_close_subscriptions = HashMap::default();
 537        let panes = if let Some(root) = serialized_pane_layout.and_then(|serialized_layout| {
 538            persistence::deserialize_pane_layout(
 539                serialized_layout,
 540                &workspace,
 541                &project,
 542                &stack_frame_list,
 543                &variable_list,
 544                &module_list,
 545                &console,
 546                &breakpoint_list,
 547                &loaded_source_list,
 548                &debug_terminal,
 549                &mut pane_close_subscriptions,
 550                window,
 551                cx,
 552            )
 553        }) {
 554            workspace::PaneGroup::with_root(root)
 555        } else {
 556            pane_close_subscriptions.clear();
 557
 558            let root = Self::default_pane_layout(
 559                project,
 560                &workspace,
 561                &stack_frame_list,
 562                &variable_list,
 563                &module_list,
 564                &loaded_source_list,
 565                &console,
 566                &breakpoint_list,
 567                &mut pane_close_subscriptions,
 568                window,
 569                cx,
 570            );
 571
 572            workspace::PaneGroup::with_root(root)
 573        };
 574
 575        Self {
 576            session,
 577            workspace,
 578            focus_handle,
 579            variable_list,
 580            _subscriptions,
 581            thread_id: None,
 582            _remote_id: None,
 583            stack_frame_list,
 584            session_id,
 585            panes,
 586            active_pane: None,
 587            module_list,
 588            _console: console,
 589            breakpoint_list,
 590            loaded_sources_list: loaded_source_list,
 591            pane_close_subscriptions,
 592            debug_terminal,
 593            _schedule_serialize: None,
 594        }
 595    }
 596
 597    pub(crate) fn remove_pane_item(
 598        &mut self,
 599        item_kind: DebuggerPaneItem,
 600        window: &mut Window,
 601        cx: &mut Context<Self>,
 602    ) {
 603        if let Some((pane, item_id)) = self.panes.panes().iter().find_map(|pane| {
 604            Some(pane).zip(
 605                pane.read(cx)
 606                    .items()
 607                    .find(|item| {
 608                        item.act_as::<SubView>(cx)
 609                            .is_some_and(|view| view.read(cx).kind == item_kind)
 610                    })
 611                    .map(|item| item.item_id()),
 612            )
 613        }) {
 614            pane.update(cx, |pane, cx| {
 615                pane.remove_item(item_id, false, true, window, cx)
 616            })
 617        }
 618    }
 619
 620    pub(crate) fn has_pane_at_position(&self, position: Point<Pixels>) -> bool {
 621        self.panes.pane_at_pixel_position(position).is_some()
 622    }
 623
 624    fn create_sub_view(
 625        &self,
 626        item_kind: DebuggerPaneItem,
 627        _pane: &Entity<Pane>,
 628        cx: &mut Context<Self>,
 629    ) -> Box<dyn ItemHandle> {
 630        match item_kind {
 631            DebuggerPaneItem::Console => {
 632                let weak_console = self._console.clone().downgrade();
 633
 634                Box::new(SubView::new(
 635                    self._console.focus_handle(cx),
 636                    self._console.clone().into(),
 637                    item_kind,
 638                    Some(Box::new(move |cx| {
 639                        weak_console
 640                            .read_with(cx, |console, cx| console.show_indicator(cx))
 641                            .unwrap_or_default()
 642                    })),
 643                    cx,
 644                ))
 645            }
 646            DebuggerPaneItem::Variables => Box::new(SubView::new(
 647                self.variable_list.focus_handle(cx),
 648                self.variable_list.clone().into(),
 649                item_kind,
 650                None,
 651                cx,
 652            )),
 653            DebuggerPaneItem::BreakpointList => Box::new(SubView::new(
 654                self.breakpoint_list.focus_handle(cx),
 655                self.breakpoint_list.clone().into(),
 656                item_kind,
 657                None,
 658                cx,
 659            )),
 660            DebuggerPaneItem::Frames => Box::new(SubView::new(
 661                self.stack_frame_list.focus_handle(cx),
 662                self.stack_frame_list.clone().into(),
 663                item_kind,
 664                None,
 665                cx,
 666            )),
 667            DebuggerPaneItem::Modules => Box::new(SubView::new(
 668                self.module_list.focus_handle(cx),
 669                self.module_list.clone().into(),
 670                item_kind,
 671                None,
 672                cx,
 673            )),
 674            DebuggerPaneItem::LoadedSources => Box::new(SubView::new(
 675                self.loaded_sources_list.focus_handle(cx),
 676                self.loaded_sources_list.clone().into(),
 677                item_kind,
 678                None,
 679                cx,
 680            )),
 681            DebuggerPaneItem::Terminal => Box::new(SubView::new(
 682                self.debug_terminal.focus_handle(cx),
 683                self.debug_terminal.clone().into(),
 684                item_kind,
 685                None,
 686                cx,
 687            )),
 688        }
 689    }
 690
 691    pub(crate) fn ensure_pane_item(
 692        &mut self,
 693        item_kind: DebuggerPaneItem,
 694        window: &mut Window,
 695        cx: &mut Context<Self>,
 696    ) {
 697        if self.pane_items_status(cx).get(&item_kind) == Some(&true) {
 698            return;
 699        };
 700        let pane = self.panes.last_pane();
 701        let sub_view = self.create_sub_view(item_kind, &pane, cx);
 702
 703        pane.update(cx, |pane, cx| {
 704            pane.add_item_inner(sub_view, false, false, false, None, window, cx);
 705        })
 706    }
 707
 708    pub(crate) fn add_pane_item(
 709        &mut self,
 710        item_kind: DebuggerPaneItem,
 711        position: Point<Pixels>,
 712        window: &mut Window,
 713        cx: &mut Context<Self>,
 714    ) {
 715        debug_assert!(
 716            item_kind.is_supported(self.session.read(cx).capabilities()),
 717            "We should only allow adding supported item kinds"
 718        );
 719
 720        if let Some(pane) = self.panes.pane_at_pixel_position(position) {
 721            let sub_view = self.create_sub_view(item_kind, pane, cx);
 722
 723            pane.update(cx, |pane, cx| {
 724                pane.add_item(sub_view, false, false, None, window, cx);
 725            })
 726        }
 727    }
 728
 729    pub(crate) fn pane_items_status(&self, cx: &App) -> IndexMap<DebuggerPaneItem, bool> {
 730        let caps = self.session.read(cx).capabilities();
 731        let mut pane_item_status = IndexMap::from_iter(
 732            DebuggerPaneItem::all()
 733                .iter()
 734                .filter(|kind| kind.is_supported(&caps))
 735                .map(|kind| (*kind, false)),
 736        );
 737        self.panes.panes().iter().for_each(|pane| {
 738            pane.read(cx)
 739                .items()
 740                .filter_map(|item| item.act_as::<SubView>(cx))
 741                .for_each(|view| {
 742                    pane_item_status.insert(view.read(cx).kind, true);
 743                });
 744        });
 745
 746        pane_item_status
 747    }
 748
 749    pub(crate) fn serialize_layout(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 750        if self._schedule_serialize.is_none() {
 751            self._schedule_serialize = Some(cx.spawn_in(window, async move |this, cx| {
 752                cx.background_executor()
 753                    .timer(Duration::from_millis(100))
 754                    .await;
 755
 756                let Some((adapter_name, pane_group)) = this
 757                    .update(cx, |this, cx| {
 758                        let adapter_name = this.session.read(cx).adapter_name();
 759                        (
 760                            adapter_name,
 761                            persistence::build_serialized_pane_layout(&this.panes.root, cx),
 762                        )
 763                    })
 764                    .ok()
 765                else {
 766                    return;
 767                };
 768
 769                persistence::serialize_pane_layout(adapter_name, pane_group)
 770                    .await
 771                    .log_err();
 772
 773                this.update(cx, |this, _| {
 774                    this._schedule_serialize.take();
 775                })
 776                .ok();
 777            }));
 778        }
 779    }
 780
 781    pub(crate) fn handle_pane_event(
 782        this: &mut RunningState,
 783        source_pane: &Entity<Pane>,
 784        event: &Event,
 785        window: &mut Window,
 786        cx: &mut Context<RunningState>,
 787    ) {
 788        this.serialize_layout(window, cx);
 789        match event {
 790            Event::Remove { .. } => {
 791                let _did_find_pane = this.panes.remove(&source_pane).is_ok();
 792                debug_assert!(_did_find_pane);
 793                cx.notify();
 794            }
 795            Event::Focus => {
 796                this.active_pane = Some(source_pane.clone());
 797            }
 798            Event::ZoomIn => {
 799                source_pane.update(cx, |pane, cx| {
 800                    pane.set_zoomed(true, cx);
 801                });
 802                cx.notify();
 803            }
 804            Event::ZoomOut => {
 805                source_pane.update(cx, |pane, cx| {
 806                    pane.set_zoomed(false, cx);
 807                });
 808                cx.notify();
 809            }
 810            _ => {}
 811        }
 812    }
 813
 814    pub(crate) fn activate_pane_in_direction(
 815        &mut self,
 816        direction: SplitDirection,
 817        window: &mut Window,
 818        cx: &mut Context<Self>,
 819    ) {
 820        if let Some(pane) = self
 821            .active_pane
 822            .as_ref()
 823            .and_then(|pane| self.panes.find_pane_in_direction(pane, direction, cx))
 824        {
 825            window.focus(&pane.focus_handle(cx));
 826        } else {
 827            self.workspace
 828                .update(cx, |workspace, cx| {
 829                    workspace.activate_pane_in_direction(direction, window, cx)
 830                })
 831                .ok();
 832        }
 833    }
 834
 835    pub(crate) fn go_to_selected_stack_frame(&self, window: &Window, cx: &mut Context<Self>) {
 836        if self.thread_id.is_some() {
 837            self.stack_frame_list
 838                .update(cx, |list, cx| list.go_to_selected_stack_frame(window, cx));
 839        }
 840    }
 841
 842    pub(crate) fn has_open_context_menu(&self, cx: &App) -> bool {
 843        self.variable_list.read(cx).has_open_context_menu()
 844    }
 845
 846    pub fn session(&self) -> &Entity<Session> {
 847        &self.session
 848    }
 849
 850    pub fn session_id(&self) -> SessionId {
 851        self.session_id
 852    }
 853
 854    pub(crate) fn selected_stack_frame_id(&self, cx: &App) -> Option<dap::StackFrameId> {
 855        self.stack_frame_list.read(cx).selected_stack_frame_id()
 856    }
 857
 858    #[cfg(test)]
 859    pub fn stack_frame_list(&self) -> &Entity<StackFrameList> {
 860        &self.stack_frame_list
 861    }
 862
 863    #[cfg(test)]
 864    pub fn console(&self) -> &Entity<Console> {
 865        &self._console
 866    }
 867
 868    #[cfg(test)]
 869    pub(crate) fn module_list(&self) -> &Entity<ModuleList> {
 870        &self.module_list
 871    }
 872
 873    pub(crate) fn activate_item(&self, item: DebuggerPaneItem, window: &mut Window, cx: &mut App) {
 874        let (variable_list_position, pane) = self
 875            .panes
 876            .panes()
 877            .into_iter()
 878            .find_map(|pane| {
 879                pane.read(cx)
 880                    .items_of_type::<SubView>()
 881                    .position(|view| view.read(cx).view_kind() == item)
 882                    .map(|view| (view, pane))
 883            })
 884            .unwrap();
 885        pane.update(cx, |this, cx| {
 886            this.activate_item(variable_list_position, true, true, window, cx);
 887        })
 888    }
 889
 890    #[cfg(test)]
 891    pub(crate) fn variable_list(&self) -> &Entity<VariableList> {
 892        &self.variable_list
 893    }
 894
 895    pub fn capabilities(&self, cx: &App) -> Capabilities {
 896        self.session().read(cx).capabilities().clone()
 897    }
 898
 899    pub fn select_current_thread(
 900        &mut self,
 901        threads: &Vec<(Thread, ThreadStatus)>,
 902        window: &mut Window,
 903        cx: &mut Context<Self>,
 904    ) {
 905        let selected_thread = self
 906            .thread_id
 907            .and_then(|thread_id| threads.iter().find(|(thread, _)| thread.id == thread_id.0))
 908            .or_else(|| threads.first());
 909
 910        let Some((selected_thread, _)) = selected_thread else {
 911            return;
 912        };
 913
 914        if Some(ThreadId(selected_thread.id)) != self.thread_id {
 915            self.select_thread(ThreadId(selected_thread.id), window, cx);
 916        }
 917    }
 918
 919    pub(crate) fn selected_thread_id(&self) -> Option<ThreadId> {
 920        self.thread_id
 921    }
 922
 923    pub fn thread_status(&self, cx: &App) -> Option<ThreadStatus> {
 924        self.thread_id
 925            .map(|id| self.session().read(cx).thread_status(id))
 926    }
 927
 928    fn select_thread(&mut self, thread_id: ThreadId, window: &mut Window, cx: &mut Context<Self>) {
 929        if self.thread_id.is_some_and(|id| id == thread_id) {
 930            return;
 931        }
 932
 933        self.thread_id = Some(thread_id);
 934
 935        self.stack_frame_list
 936            .update(cx, |list, cx| list.schedule_refresh(true, window, cx));
 937    }
 938
 939    pub fn continue_thread(&mut self, cx: &mut Context<Self>) {
 940        let Some(thread_id) = self.thread_id else {
 941            return;
 942        };
 943
 944        self.session().update(cx, |state, cx| {
 945            state.continue_thread(thread_id, cx);
 946        });
 947    }
 948
 949    pub fn step_over(&mut self, cx: &mut Context<Self>) {
 950        let Some(thread_id) = self.thread_id else {
 951            return;
 952        };
 953
 954        let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
 955
 956        self.session().update(cx, |state, cx| {
 957            state.step_over(thread_id, granularity, cx);
 958        });
 959    }
 960
 961    pub(crate) fn step_in(&mut self, cx: &mut Context<Self>) {
 962        let Some(thread_id) = self.thread_id else {
 963            return;
 964        };
 965
 966        let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
 967
 968        self.session().update(cx, |state, cx| {
 969            state.step_in(thread_id, granularity, cx);
 970        });
 971    }
 972
 973    pub(crate) fn step_out(&mut self, cx: &mut Context<Self>) {
 974        let Some(thread_id) = self.thread_id else {
 975            return;
 976        };
 977
 978        let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
 979
 980        self.session().update(cx, |state, cx| {
 981            state.step_out(thread_id, granularity, cx);
 982        });
 983    }
 984
 985    pub(crate) fn step_back(&mut self, cx: &mut Context<Self>) {
 986        let Some(thread_id) = self.thread_id else {
 987            return;
 988        };
 989
 990        let granularity = DebuggerSettings::get_global(cx).stepping_granularity;
 991
 992        self.session().update(cx, |state, cx| {
 993            state.step_back(thread_id, granularity, cx);
 994        });
 995    }
 996
 997    pub fn restart_session(&self, cx: &mut Context<Self>) {
 998        self.session().update(cx, |state, cx| {
 999            state.restart(None, cx);
1000        });
1001    }
1002
1003    pub fn pause_thread(&self, cx: &mut Context<Self>) {
1004        let Some(thread_id) = self.thread_id else {
1005            return;
1006        };
1007
1008        self.session().update(cx, |state, cx| {
1009            state.pause_thread(thread_id, cx);
1010        });
1011    }
1012
1013    pub(crate) fn shutdown(&mut self, cx: &mut Context<Self>) {
1014        self.workspace
1015            .update(cx, |workspace, cx| {
1016                workspace
1017                    .project()
1018                    .read(cx)
1019                    .breakpoint_store()
1020                    .update(cx, |store, cx| {
1021                        store.remove_active_position(Some(self.session_id), cx)
1022                    })
1023            })
1024            .log_err();
1025
1026        self.session.update(cx, |session, cx| {
1027            session.shutdown(cx).detach();
1028        })
1029    }
1030
1031    pub fn stop_thread(&self, cx: &mut Context<Self>) {
1032        let Some(thread_id) = self.thread_id else {
1033            return;
1034        };
1035
1036        self.workspace
1037            .update(cx, |workspace, cx| {
1038                workspace
1039                    .project()
1040                    .read(cx)
1041                    .breakpoint_store()
1042                    .update(cx, |store, cx| {
1043                        store.remove_active_position(Some(self.session_id), cx)
1044                    })
1045            })
1046            .log_err();
1047
1048        self.session().update(cx, |state, cx| {
1049            state.terminate_threads(Some(vec![thread_id; 1]), cx);
1050        });
1051    }
1052
1053    #[expect(
1054        unused,
1055        reason = "Support for disconnecting a client is not wired through yet"
1056    )]
1057    pub fn disconnect_client(&self, cx: &mut Context<Self>) {
1058        self.session().update(cx, |state, cx| {
1059            state.disconnect_client(cx);
1060        });
1061    }
1062
1063    pub fn toggle_ignore_breakpoints(&mut self, cx: &mut Context<Self>) {
1064        self.session.update(cx, |session, cx| {
1065            session.toggle_ignore_breakpoints(cx).detach();
1066        });
1067    }
1068
1069    pub(crate) fn thread_dropdown(
1070        &self,
1071        window: &mut Window,
1072        cx: &mut Context<'_, RunningState>,
1073    ) -> DropdownMenu {
1074        let state = cx.entity();
1075        let threads = self.session.update(cx, |this, cx| this.threads(cx));
1076        let selected_thread_name = threads
1077            .iter()
1078            .find(|(thread, _)| self.thread_id.map(|id| id.0) == Some(thread.id))
1079            .map(|(thread, _)| thread.name.clone())
1080            .unwrap_or("Threads".to_owned());
1081        DropdownMenu::new(
1082            ("thread-list", self.session_id.0),
1083            selected_thread_name,
1084            ContextMenu::build_eager(window, cx, move |mut this, _, _| {
1085                for (thread, _) in threads {
1086                    let state = state.clone();
1087                    let thread_id = thread.id;
1088                    this = this.entry(thread.name, None, move |window, cx| {
1089                        state.update(cx, |state, cx| {
1090                            state.select_thread(ThreadId(thread_id), window, cx);
1091                        });
1092                    });
1093                }
1094                this
1095            }),
1096        )
1097    }
1098
1099    fn default_pane_layout(
1100        project: Entity<Project>,
1101        workspace: &WeakEntity<Workspace>,
1102        stack_frame_list: &Entity<StackFrameList>,
1103        variable_list: &Entity<VariableList>,
1104        module_list: &Entity<ModuleList>,
1105        loaded_source_list: &Entity<LoadedSourceList>,
1106        console: &Entity<Console>,
1107        breakpoints: &Entity<BreakpointList>,
1108        subscriptions: &mut HashMap<EntityId, Subscription>,
1109        window: &mut Window,
1110        cx: &mut Context<'_, RunningState>,
1111    ) -> Member {
1112        let leftmost_pane = new_debugger_pane(workspace.clone(), project.clone(), window, cx);
1113        leftmost_pane.update(cx, |this, cx| {
1114            this.add_item(
1115                Box::new(SubView::new(
1116                    this.focus_handle(cx),
1117                    stack_frame_list.clone().into(),
1118                    DebuggerPaneItem::Frames,
1119                    None,
1120                    cx,
1121                )),
1122                true,
1123                false,
1124                None,
1125                window,
1126                cx,
1127            );
1128            this.add_item(
1129                Box::new(SubView::new(
1130                    breakpoints.focus_handle(cx),
1131                    breakpoints.clone().into(),
1132                    DebuggerPaneItem::BreakpointList,
1133                    None,
1134                    cx,
1135                )),
1136                true,
1137                false,
1138                None,
1139                window,
1140                cx,
1141            );
1142            this.activate_item(0, false, false, window, cx);
1143        });
1144        let center_pane = new_debugger_pane(workspace.clone(), project.clone(), window, cx);
1145
1146        center_pane.update(cx, |this, cx| {
1147            this.add_item(
1148                Box::new(SubView::new(
1149                    variable_list.focus_handle(cx),
1150                    variable_list.clone().into(),
1151                    DebuggerPaneItem::Variables,
1152                    None,
1153                    cx,
1154                )),
1155                true,
1156                false,
1157                None,
1158                window,
1159                cx,
1160            );
1161            this.add_item(
1162                Box::new(SubView::new(
1163                    module_list.focus_handle(cx),
1164                    module_list.clone().into(),
1165                    DebuggerPaneItem::Modules,
1166                    None,
1167                    cx,
1168                )),
1169                false,
1170                false,
1171                None,
1172                window,
1173                cx,
1174            );
1175
1176            this.add_item(
1177                Box::new(SubView::new(
1178                    loaded_source_list.focus_handle(cx),
1179                    loaded_source_list.clone().into(),
1180                    DebuggerPaneItem::LoadedSources,
1181                    None,
1182                    cx,
1183                )),
1184                false,
1185                false,
1186                None,
1187                window,
1188                cx,
1189            );
1190            this.activate_item(0, false, false, window, cx);
1191        });
1192
1193        let rightmost_pane = new_debugger_pane(workspace.clone(), project.clone(), window, cx);
1194        rightmost_pane.update(cx, |this, cx| {
1195            let weak_console = console.downgrade();
1196            this.add_item(
1197                Box::new(SubView::new(
1198                    this.focus_handle(cx),
1199                    console.clone().into(),
1200                    DebuggerPaneItem::Console,
1201                    Some(Box::new(move |cx| {
1202                        weak_console
1203                            .read_with(cx, |console, cx| console.show_indicator(cx))
1204                            .unwrap_or_default()
1205                    })),
1206                    cx,
1207                )),
1208                true,
1209                false,
1210                None,
1211                window,
1212                cx,
1213            );
1214        });
1215
1216        subscriptions.extend(
1217            [&leftmost_pane, &center_pane, &rightmost_pane]
1218                .into_iter()
1219                .map(|entity| {
1220                    (
1221                        entity.entity_id(),
1222                        cx.subscribe_in(entity, window, Self::handle_pane_event),
1223                    )
1224                }),
1225        );
1226
1227        let group_root = workspace::PaneAxis::new(
1228            gpui::Axis::Horizontal,
1229            [leftmost_pane, center_pane, rightmost_pane]
1230                .into_iter()
1231                .map(workspace::Member::Pane)
1232                .collect(),
1233        );
1234
1235        Member::Axis(group_root)
1236    }
1237}
1238
1239impl EventEmitter<DebugPanelItemEvent> for RunningState {}
1240
1241impl Focusable for RunningState {
1242    fn focus_handle(&self, _: &App) -> FocusHandle {
1243        self.focus_handle.clone()
1244    }
1245}