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