debugger_panel.rs

   1use crate::persistence::DebuggerPaneItem;
   2use crate::session::DebugSession;
   3use crate::session::running::RunningState;
   4use crate::{
   5    ClearAllBreakpoints, Continue, Detach, FocusBreakpointList, FocusConsole, FocusFrames,
   6    FocusLoadedSources, FocusModules, FocusTerminal, FocusVariables, Pause, Restart,
   7    ShowStackTrace, StepBack, StepInto, StepOut, StepOver, Stop, ToggleIgnoreBreakpoints,
   8    ToggleSessionPicker, ToggleThreadPicker, persistence,
   9};
  10use anyhow::{Context as _, Result, anyhow};
  11use command_palette_hooks::CommandPaletteFilter;
  12use dap::StartDebuggingRequestArguments;
  13use dap::adapters::DebugAdapterName;
  14use dap::debugger_settings::DebugPanelDockPosition;
  15use dap::{
  16    ContinuedEvent, LoadedSourceEvent, ModuleEvent, OutputEvent, StoppedEvent, ThreadEvent,
  17    client::SessionId, debugger_settings::DebuggerSettings,
  18};
  19use gpui::{
  20    Action, App, AsyncWindowContext, Context, DismissEvent, Entity, EntityId, EventEmitter,
  21    FocusHandle, Focusable, MouseButton, MouseDownEvent, Point, Subscription, Task, WeakEntity,
  22    actions, anchored, deferred,
  23};
  24
  25use language::Buffer;
  26use project::debugger::session::{Session, SessionStateEvent};
  27use project::{Fs, ProjectPath, WorktreeId};
  28use project::{Project, debugger::session::ThreadStatus};
  29use rpc::proto::{self};
  30use settings::Settings;
  31use std::any::TypeId;
  32use std::sync::Arc;
  33use task::{DebugScenario, TaskContext};
  34use ui::{ContextMenu, Divider, PopoverMenuHandle, Tooltip, prelude::*};
  35use workspace::SplitDirection;
  36use workspace::{
  37    Pane, Workspace,
  38    dock::{DockPosition, Panel, PanelEvent},
  39};
  40
  41pub enum DebugPanelEvent {
  42    Exited(SessionId),
  43    Terminated(SessionId),
  44    Stopped {
  45        client_id: SessionId,
  46        event: StoppedEvent,
  47        go_to_stack_frame: bool,
  48    },
  49    Thread((SessionId, ThreadEvent)),
  50    Continued((SessionId, ContinuedEvent)),
  51    Output((SessionId, OutputEvent)),
  52    Module((SessionId, ModuleEvent)),
  53    LoadedSource((SessionId, LoadedSourceEvent)),
  54    ClientShutdown(SessionId),
  55    CapabilitiesChanged(SessionId),
  56}
  57
  58actions!(debug_panel, [ToggleFocus]);
  59
  60pub struct DebugPanel {
  61    size: Pixels,
  62    sessions: Vec<Entity<DebugSession>>,
  63    active_session: Option<Entity<DebugSession>>,
  64    project: Entity<Project>,
  65    workspace: WeakEntity<Workspace>,
  66    focus_handle: FocusHandle,
  67    context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,
  68    pub(crate) thread_picker_menu_handle: PopoverMenuHandle<ContextMenu>,
  69    pub(crate) session_picker_menu_handle: PopoverMenuHandle<ContextMenu>,
  70    fs: Arc<dyn Fs>,
  71}
  72
  73impl DebugPanel {
  74    pub fn new(
  75        workspace: &Workspace,
  76        _window: &mut Window,
  77        cx: &mut Context<Workspace>,
  78    ) -> Entity<Self> {
  79        cx.new(|cx| {
  80            let project = workspace.project().clone();
  81            let focus_handle = cx.focus_handle();
  82            let thread_picker_menu_handle = PopoverMenuHandle::default();
  83            let session_picker_menu_handle = PopoverMenuHandle::default();
  84
  85            Self {
  86                size: px(300.),
  87                sessions: vec![],
  88                active_session: None,
  89                focus_handle,
  90                project,
  91                workspace: workspace.weak_handle(),
  92                context_menu: None,
  93                fs: workspace.app_state().fs.clone(),
  94                thread_picker_menu_handle,
  95                session_picker_menu_handle,
  96            }
  97        })
  98    }
  99
 100    pub(crate) fn focus_active_item(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 101        let Some(session) = self.active_session.clone() else {
 102            return;
 103        };
 104        let Some(active_pane) = session
 105            .read(cx)
 106            .running_state()
 107            .read(cx)
 108            .active_pane()
 109            .cloned()
 110        else {
 111            return;
 112        };
 113        active_pane.update(cx, |pane, cx| {
 114            pane.focus_active_item(window, cx);
 115        });
 116    }
 117
 118    pub(crate) fn sessions(&self) -> Vec<Entity<DebugSession>> {
 119        self.sessions.clone()
 120    }
 121
 122    pub fn active_session(&self) -> Option<Entity<DebugSession>> {
 123        self.active_session.clone()
 124    }
 125
 126    pub(crate) fn running_state(&self, cx: &mut App) -> Option<Entity<RunningState>> {
 127        self.active_session()
 128            .map(|session| session.read(cx).running_state().clone())
 129    }
 130
 131    pub(crate) fn filter_action_types(&self, cx: &mut App) {
 132        let (has_active_session, supports_restart, support_step_back, status) = self
 133            .active_session()
 134            .map(|item| {
 135                let running = item.read(cx).running_state().clone();
 136                let caps = running.read(cx).capabilities(cx);
 137                (
 138                    !running.read(cx).session().read(cx).is_terminated(),
 139                    caps.supports_restart_request.unwrap_or_default(),
 140                    caps.supports_step_back.unwrap_or_default(),
 141                    running.read(cx).thread_status(cx),
 142                )
 143            })
 144            .unwrap_or((false, false, false, None));
 145
 146        let filter = CommandPaletteFilter::global_mut(cx);
 147        let debugger_action_types = [
 148            TypeId::of::<Detach>(),
 149            TypeId::of::<Stop>(),
 150            TypeId::of::<ToggleIgnoreBreakpoints>(),
 151        ];
 152
 153        let running_action_types = [TypeId::of::<Pause>()];
 154
 155        let stopped_action_type = [
 156            TypeId::of::<Continue>(),
 157            TypeId::of::<StepOver>(),
 158            TypeId::of::<StepInto>(),
 159            TypeId::of::<StepOut>(),
 160            TypeId::of::<ShowStackTrace>(),
 161            TypeId::of::<editor::actions::DebuggerRunToCursor>(),
 162            TypeId::of::<editor::actions::DebuggerEvaluateSelectedText>(),
 163        ];
 164
 165        let step_back_action_type = [TypeId::of::<StepBack>()];
 166        let restart_action_type = [TypeId::of::<Restart>()];
 167
 168        if has_active_session {
 169            filter.show_action_types(debugger_action_types.iter());
 170
 171            if supports_restart {
 172                filter.show_action_types(restart_action_type.iter());
 173            } else {
 174                filter.hide_action_types(&restart_action_type);
 175            }
 176
 177            if support_step_back {
 178                filter.show_action_types(step_back_action_type.iter());
 179            } else {
 180                filter.hide_action_types(&step_back_action_type);
 181            }
 182
 183            match status {
 184                Some(ThreadStatus::Running) => {
 185                    filter.show_action_types(running_action_types.iter());
 186                    filter.hide_action_types(&stopped_action_type);
 187                }
 188                Some(ThreadStatus::Stopped) => {
 189                    filter.show_action_types(stopped_action_type.iter());
 190                    filter.hide_action_types(&running_action_types);
 191                }
 192                _ => {
 193                    filter.hide_action_types(&running_action_types);
 194                    filter.hide_action_types(&stopped_action_type);
 195                }
 196            }
 197        } else {
 198            // show only the `debug: start`
 199            filter.hide_action_types(&debugger_action_types);
 200            filter.hide_action_types(&step_back_action_type);
 201            filter.hide_action_types(&restart_action_type);
 202            filter.hide_action_types(&running_action_types);
 203            filter.hide_action_types(&stopped_action_type);
 204        }
 205    }
 206
 207    pub fn load(
 208        workspace: WeakEntity<Workspace>,
 209        cx: &mut AsyncWindowContext,
 210    ) -> Task<Result<Entity<Self>>> {
 211        cx.spawn(async move |cx| {
 212            workspace.update_in(cx, |workspace, window, cx| {
 213                let debug_panel = DebugPanel::new(workspace, window, cx);
 214
 215                workspace.register_action(|workspace, _: &ClearAllBreakpoints, _, cx| {
 216                    workspace.project().read(cx).breakpoint_store().update(
 217                        cx,
 218                        |breakpoint_store, cx| {
 219                            breakpoint_store.clear_breakpoints(cx);
 220                        },
 221                    )
 222                });
 223
 224                cx.observe_new::<DebugPanel>(|debug_panel, _, cx| {
 225                    Self::filter_action_types(debug_panel, cx);
 226                })
 227                .detach();
 228
 229                cx.observe(&debug_panel, |_, debug_panel, cx| {
 230                    debug_panel.update(cx, |debug_panel, cx| {
 231                        Self::filter_action_types(debug_panel, cx);
 232                    });
 233                })
 234                .detach();
 235                workspace.set_debugger_provider(DebuggerProvider(debug_panel.clone()));
 236
 237                debug_panel
 238            })
 239        })
 240    }
 241
 242    pub fn start_session(
 243        &mut self,
 244        scenario: DebugScenario,
 245        task_context: TaskContext,
 246        active_buffer: Option<Entity<Buffer>>,
 247        worktree_id: Option<WorktreeId>,
 248        window: &mut Window,
 249        cx: &mut Context<Self>,
 250    ) {
 251        let dap_store = self.project.read(cx).dap_store();
 252        let session = dap_store.update(cx, |dap_store, cx| {
 253            dap_store.new_session(
 254                scenario.label.clone(),
 255                DebugAdapterName(scenario.adapter.clone()),
 256                None,
 257                cx,
 258            )
 259        });
 260        if let Some(inventory) = self
 261            .project
 262            .read(cx)
 263            .task_store()
 264            .read(cx)
 265            .task_inventory()
 266            .cloned()
 267        {
 268            inventory.update(cx, |inventory, _| {
 269                inventory.scenario_scheduled(scenario.clone());
 270            })
 271        }
 272        let task = cx.spawn_in(window, {
 273            let session = session.clone();
 274            async move |this, cx| {
 275                let debug_session =
 276                    Self::register_session(this.clone(), session.clone(), cx).await?;
 277                let definition = debug_session
 278                    .update_in(cx, |debug_session, window, cx| {
 279                        debug_session.running_state().update(cx, |running, cx| {
 280                            running.resolve_scenario(
 281                                scenario,
 282                                task_context,
 283                                active_buffer,
 284                                worktree_id,
 285                                window,
 286                                cx,
 287                            )
 288                        })
 289                    })?
 290                    .await?;
 291
 292                dap_store
 293                    .update(cx, |dap_store, cx| {
 294                        dap_store.boot_session(session.clone(), definition, cx)
 295                    })?
 296                    .await
 297            }
 298        });
 299
 300        cx.spawn(async move |_, cx| {
 301            if let Err(error) = task.await {
 302                log::error!("{error}");
 303                session
 304                    .update(cx, |session, cx| {
 305                        session
 306                            .console_output(cx)
 307                            .unbounded_send(format!("error: {}", error))
 308                            .ok();
 309                        session.shutdown(cx)
 310                    })?
 311                    .await;
 312            }
 313            anyhow::Ok(())
 314        })
 315        .detach_and_log_err(cx);
 316    }
 317
 318    pub(crate) async fn register_session(
 319        this: WeakEntity<Self>,
 320        session: Entity<Session>,
 321        cx: &mut AsyncWindowContext,
 322    ) -> Result<Entity<DebugSession>> {
 323        let adapter_name = session.update(cx, |session, _| session.adapter())?;
 324        this.update_in(cx, |_, window, cx| {
 325            cx.subscribe_in(
 326                &session,
 327                window,
 328                move |this, session, event: &SessionStateEvent, window, cx| match event {
 329                    SessionStateEvent::Restart => {
 330                        this.handle_restart_request(session.clone(), window, cx);
 331                    }
 332                    SessionStateEvent::SpawnChildSession { request } => {
 333                        this.handle_start_debugging_request(request, session.clone(), window, cx);
 334                    }
 335                    _ => {}
 336                },
 337            )
 338            .detach();
 339        })
 340        .ok();
 341
 342        let serialized_layout = persistence::get_serialized_layout(adapter_name).await;
 343
 344        let (debug_session, workspace) = this.update_in(cx, |this, window, cx| {
 345            this.sessions.retain(|session| {
 346                !session
 347                    .read(cx)
 348                    .running_state()
 349                    .read(cx)
 350                    .session()
 351                    .read(cx)
 352                    .is_terminated()
 353            });
 354
 355            let debug_session = DebugSession::running(
 356                this.project.clone(),
 357                this.workspace.clone(),
 358                session,
 359                cx.weak_entity(),
 360                serialized_layout,
 361                this.position(window, cx).axis(),
 362                window,
 363                cx,
 364            );
 365
 366            // We might want to make this an event subscription and only notify when a new thread is selected
 367            // This is used to filter the command menu correctly
 368            cx.observe(
 369                &debug_session.read(cx).running_state().clone(),
 370                |_, _, cx| cx.notify(),
 371            )
 372            .detach();
 373
 374            this.sessions.push(debug_session.clone());
 375            this.activate_session(debug_session.clone(), window, cx);
 376
 377            (debug_session, this.workspace.clone())
 378        })?;
 379
 380        workspace.update_in(cx, |workspace, window, cx| {
 381            workspace.focus_panel::<Self>(window, cx);
 382        })?;
 383
 384        Ok(debug_session)
 385    }
 386
 387    pub(crate) fn handle_restart_request(
 388        &mut self,
 389        mut curr_session: Entity<Session>,
 390        window: &mut Window,
 391        cx: &mut Context<Self>,
 392    ) {
 393        while let Some(parent_session) =
 394            curr_session.read_with(cx, |session, _| session.parent_session().cloned())
 395        {
 396            curr_session = parent_session;
 397        }
 398
 399        let Some(worktree) = curr_session.read(cx).worktree() else {
 400            log::error!("Attempted to start a child session from non local debug session");
 401            return;
 402        };
 403
 404        let dap_store_handle = self.project.read(cx).dap_store().clone();
 405        let label = curr_session.read(cx).label().clone();
 406        let adapter = curr_session.read(cx).adapter().clone();
 407        let binary = curr_session.read(cx).binary().clone();
 408        let task = curr_session.update(cx, |session, cx| session.shutdown(cx));
 409
 410        cx.spawn_in(window, async move |this, cx| {
 411            task.await;
 412
 413            let (session, task) = dap_store_handle.update(cx, |dap_store, cx| {
 414                let session = dap_store.new_session(label, adapter, None, cx);
 415
 416                let task = session.update(cx, |session, cx| {
 417                    session.boot(binary, worktree, dap_store_handle.downgrade(), cx)
 418                });
 419                (session, task)
 420            })?;
 421            Self::register_session(this, session, cx).await?;
 422            task.await
 423        })
 424        .detach_and_log_err(cx);
 425    }
 426
 427    pub fn handle_start_debugging_request(
 428        &mut self,
 429        request: &StartDebuggingRequestArguments,
 430        parent_session: Entity<Session>,
 431        window: &mut Window,
 432        cx: &mut Context<Self>,
 433    ) {
 434        let Some(worktree) = parent_session.read(cx).worktree() else {
 435            log::error!("Attempted to start a child session from non local debug session");
 436            return;
 437        };
 438
 439        let dap_store_handle = self.project.read(cx).dap_store().clone();
 440        let label = parent_session.read(cx).label().clone();
 441        let adapter = parent_session.read(cx).adapter().clone();
 442        let mut binary = parent_session.read(cx).binary().clone();
 443        binary.request_args = request.clone();
 444
 445        cx.spawn_in(window, async move |this, cx| {
 446            let (session, task) = dap_store_handle.update(cx, |dap_store, cx| {
 447                let session =
 448                    dap_store.new_session(label, adapter, Some(parent_session.clone()), cx);
 449
 450                let task = session.update(cx, |session, cx| {
 451                    session.boot(binary, worktree, dap_store_handle.downgrade(), cx)
 452                });
 453                (session, task)
 454            })?;
 455            Self::register_session(this, session, cx).await?;
 456            task.await
 457        })
 458        .detach_and_log_err(cx);
 459    }
 460
 461    pub(crate) fn close_session(
 462        &mut self,
 463        entity_id: EntityId,
 464        window: &mut Window,
 465        cx: &mut Context<Self>,
 466    ) {
 467        let Some(session) = self
 468            .sessions
 469            .iter()
 470            .find(|other| entity_id == other.entity_id())
 471            .cloned()
 472        else {
 473            return;
 474        };
 475        session.update(cx, |this, cx| {
 476            this.running_state().update(cx, |this, cx| {
 477                this.serialize_layout(window, cx);
 478            });
 479        });
 480        let session_id = session.update(cx, |this, cx| this.session_id(cx));
 481        let should_prompt = self
 482            .project
 483            .update(cx, |this, cx| {
 484                let session = this.dap_store().read(cx).session_by_id(session_id);
 485                session.map(|session| !session.read(cx).is_terminated())
 486            })
 487            .unwrap_or_default();
 488
 489        cx.spawn_in(window, async move |this, cx| {
 490            if should_prompt {
 491                let response = cx.prompt(
 492                    gpui::PromptLevel::Warning,
 493                    "This Debug Session is still running. Are you sure you want to terminate it?",
 494                    None,
 495                    &["Yes", "No"],
 496                );
 497                if response.await == Ok(1) {
 498                    return;
 499                }
 500            }
 501            session.update(cx, |session, cx| session.shutdown(cx)).ok();
 502            this.update(cx, |this, cx| {
 503                this.sessions.retain(|other| entity_id != other.entity_id());
 504
 505                if let Some(active_session_id) = this
 506                    .active_session
 507                    .as_ref()
 508                    .map(|session| session.entity_id())
 509                {
 510                    if active_session_id == entity_id {
 511                        this.active_session = this.sessions.first().cloned();
 512                    }
 513                }
 514                cx.notify()
 515            })
 516            .ok();
 517        })
 518        .detach();
 519    }
 520
 521    pub(crate) fn deploy_context_menu(
 522        &mut self,
 523        position: Point<Pixels>,
 524        window: &mut Window,
 525        cx: &mut Context<Self>,
 526    ) {
 527        if let Some(running_state) = self
 528            .active_session
 529            .as_ref()
 530            .map(|session| session.read(cx).running_state().clone())
 531        {
 532            let pane_items_status = running_state.read(cx).pane_items_status(cx);
 533            let this = cx.weak_entity();
 534
 535            let context_menu = ContextMenu::build(window, cx, |mut menu, _window, _cx| {
 536                for (item_kind, is_visible) in pane_items_status.into_iter() {
 537                    menu = menu.toggleable_entry(item_kind, is_visible, IconPosition::End, None, {
 538                        let this = this.clone();
 539                        move |window, cx| {
 540                            this.update(cx, |this, cx| {
 541                                if let Some(running_state) = this
 542                                    .active_session
 543                                    .as_ref()
 544                                    .map(|session| session.read(cx).running_state().clone())
 545                                {
 546                                    running_state.update(cx, |state, cx| {
 547                                        if is_visible {
 548                                            state.remove_pane_item(item_kind, window, cx);
 549                                        } else {
 550                                            state.add_pane_item(item_kind, position, window, cx);
 551                                        }
 552                                    })
 553                                }
 554                            })
 555                            .ok();
 556                        }
 557                    });
 558                }
 559
 560                menu
 561            });
 562
 563            window.focus(&context_menu.focus_handle(cx));
 564            let subscription = cx.subscribe(&context_menu, |this, _, _: &DismissEvent, cx| {
 565                this.context_menu.take();
 566                cx.notify();
 567            });
 568            self.context_menu = Some((context_menu, position, subscription));
 569        }
 570    }
 571
 572    pub(crate) fn top_controls_strip(
 573        &mut self,
 574        window: &mut Window,
 575        cx: &mut Context<Self>,
 576    ) -> Option<Div> {
 577        let active_session = self.active_session.clone();
 578        let focus_handle = self.focus_handle.clone();
 579        let is_side = self.position(window, cx).axis() == gpui::Axis::Horizontal;
 580        let div = if is_side { v_flex() } else { h_flex() };
 581
 582        let new_session_button = || {
 583            IconButton::new("debug-new-session", IconName::Plus)
 584                .icon_size(IconSize::Small)
 585                .on_click({
 586                    move |_, window, cx| window.dispatch_action(crate::Start.boxed_clone(), cx)
 587                })
 588                .tooltip({
 589                    let focus_handle = focus_handle.clone();
 590                    move |window, cx| {
 591                        Tooltip::for_action_in(
 592                            "Start Debug Session",
 593                            &crate::Start,
 594                            &focus_handle,
 595                            window,
 596                            cx,
 597                        )
 598                    }
 599                })
 600        };
 601
 602        Some(
 603            div.border_b_1()
 604                .border_color(cx.theme().colors().border)
 605                .p_1()
 606                .justify_between()
 607                .w_full()
 608                .when(is_side, |this| this.gap_1())
 609                .child(
 610                    h_flex()
 611                        .child(
 612                            h_flex().gap_2().w_full().when_some(
 613                                active_session
 614                                    .as_ref()
 615                                    .map(|session| session.read(cx).running_state()),
 616                                |this, running_state| {
 617                                    let thread_status =
 618                                        running_state.read(cx).thread_status(cx).unwrap_or(
 619                                            project::debugger::session::ThreadStatus::Exited,
 620                                        );
 621                                    let capabilities = running_state.read(cx).capabilities(cx);
 622                                    this.map(|this| {
 623                                        if thread_status == ThreadStatus::Running {
 624                                            this.child(
 625                                                IconButton::new(
 626                                                    "debug-pause",
 627                                                    IconName::DebugPause,
 628                                                )
 629                                                .icon_size(IconSize::XSmall)
 630                                                .shape(ui::IconButtonShape::Square)
 631                                                .on_click(window.listener_for(
 632                                                    &running_state,
 633                                                    |this, _, _window, cx| {
 634                                                        this.pause_thread(cx);
 635                                                    },
 636                                                ))
 637                                                .tooltip({
 638                                                    let focus_handle = focus_handle.clone();
 639                                                    move |window, cx| {
 640                                                        Tooltip::for_action_in(
 641                                                            "Pause program",
 642                                                            &Pause,
 643                                                            &focus_handle,
 644                                                            window,
 645                                                            cx,
 646                                                        )
 647                                                    }
 648                                                }),
 649                                            )
 650                                        } else {
 651                                            this.child(
 652                                                IconButton::new(
 653                                                    "debug-continue",
 654                                                    IconName::DebugContinue,
 655                                                )
 656                                                .icon_size(IconSize::XSmall)
 657                                                .shape(ui::IconButtonShape::Square)
 658                                                .on_click(window.listener_for(
 659                                                    &running_state,
 660                                                    |this, _, _window, cx| this.continue_thread(cx),
 661                                                ))
 662                                                .disabled(thread_status != ThreadStatus::Stopped)
 663                                                .tooltip({
 664                                                    let focus_handle = focus_handle.clone();
 665                                                    move |window, cx| {
 666                                                        Tooltip::for_action_in(
 667                                                            "Continue program",
 668                                                            &Continue,
 669                                                            &focus_handle,
 670                                                            window,
 671                                                            cx,
 672                                                        )
 673                                                    }
 674                                                }),
 675                                            )
 676                                        }
 677                                    })
 678                                    .child(
 679                                        IconButton::new("debug-step-over", IconName::ArrowRight)
 680                                            .icon_size(IconSize::XSmall)
 681                                            .shape(ui::IconButtonShape::Square)
 682                                            .on_click(window.listener_for(
 683                                                &running_state,
 684                                                |this, _, _window, cx| {
 685                                                    this.step_over(cx);
 686                                                },
 687                                            ))
 688                                            .disabled(thread_status != ThreadStatus::Stopped)
 689                                            .tooltip({
 690                                                let focus_handle = focus_handle.clone();
 691                                                move |window, cx| {
 692                                                    Tooltip::for_action_in(
 693                                                        "Step over",
 694                                                        &StepOver,
 695                                                        &focus_handle,
 696                                                        window,
 697                                                        cx,
 698                                                    )
 699                                                }
 700                                            }),
 701                                    )
 702                                    .child(
 703                                        IconButton::new("debug-step-out", IconName::ArrowUpRight)
 704                                            .icon_size(IconSize::XSmall)
 705                                            .shape(ui::IconButtonShape::Square)
 706                                            .on_click(window.listener_for(
 707                                                &running_state,
 708                                                |this, _, _window, cx| {
 709                                                    this.step_out(cx);
 710                                                },
 711                                            ))
 712                                            .disabled(thread_status != ThreadStatus::Stopped)
 713                                            .tooltip({
 714                                                let focus_handle = focus_handle.clone();
 715                                                move |window, cx| {
 716                                                    Tooltip::for_action_in(
 717                                                        "Step out",
 718                                                        &StepOut,
 719                                                        &focus_handle,
 720                                                        window,
 721                                                        cx,
 722                                                    )
 723                                                }
 724                                            }),
 725                                    )
 726                                    .child(
 727                                        IconButton::new(
 728                                            "debug-step-into",
 729                                            IconName::ArrowDownRight,
 730                                        )
 731                                        .icon_size(IconSize::XSmall)
 732                                        .shape(ui::IconButtonShape::Square)
 733                                        .on_click(window.listener_for(
 734                                            &running_state,
 735                                            |this, _, _window, cx| {
 736                                                this.step_in(cx);
 737                                            },
 738                                        ))
 739                                        .disabled(thread_status != ThreadStatus::Stopped)
 740                                        .tooltip({
 741                                            let focus_handle = focus_handle.clone();
 742                                            move |window, cx| {
 743                                                Tooltip::for_action_in(
 744                                                    "Step in",
 745                                                    &StepInto,
 746                                                    &focus_handle,
 747                                                    window,
 748                                                    cx,
 749                                                )
 750                                            }
 751                                        }),
 752                                    )
 753                                    .child(Divider::vertical())
 754                                    .child(
 755                                        IconButton::new("debug-restart", IconName::DebugRestart)
 756                                            .icon_size(IconSize::XSmall)
 757                                            .on_click(window.listener_for(
 758                                                &running_state,
 759                                                |this, _, _window, cx| {
 760                                                    this.restart_session(cx);
 761                                                },
 762                                            ))
 763                                            .tooltip({
 764                                                let focus_handle = focus_handle.clone();
 765                                                move |window, cx| {
 766                                                    Tooltip::for_action_in(
 767                                                        "Restart",
 768                                                        &Restart,
 769                                                        &focus_handle,
 770                                                        window,
 771                                                        cx,
 772                                                    )
 773                                                }
 774                                            }),
 775                                    )
 776                                    .child(
 777                                        IconButton::new("debug-stop", IconName::Power)
 778                                            .icon_size(IconSize::XSmall)
 779                                            .on_click(window.listener_for(
 780                                                &running_state,
 781                                                |this, _, _window, cx| {
 782                                                    this.stop_thread(cx);
 783                                                },
 784                                            ))
 785                                            .disabled(
 786                                                thread_status != ThreadStatus::Stopped
 787                                                    && thread_status != ThreadStatus::Running,
 788                                            )
 789                                            .tooltip({
 790                                                let focus_handle = focus_handle.clone();
 791                                                let label = if capabilities
 792                                                    .supports_terminate_threads_request
 793                                                    .unwrap_or_default()
 794                                                {
 795                                                    "Terminate Thread"
 796                                                } else {
 797                                                    "Terminate All Threads"
 798                                                };
 799                                                move |window, cx| {
 800                                                    Tooltip::for_action_in(
 801                                                        label,
 802                                                        &Stop,
 803                                                        &focus_handle,
 804                                                        window,
 805                                                        cx,
 806                                                    )
 807                                                }
 808                                            }),
 809                                    )
 810                                    .child(
 811                                        IconButton::new("debug-disconnect", IconName::DebugDetach)
 812                                            .icon_size(IconSize::XSmall)
 813                                            .on_click(window.listener_for(
 814                                                &running_state,
 815                                                |this, _, _, cx| {
 816                                                    this.detach_client(cx);
 817                                                },
 818                                            ))
 819                                            .tooltip({
 820                                                let focus_handle = focus_handle.clone();
 821                                                move |window, cx| {
 822                                                    Tooltip::for_action_in(
 823                                                        "Detach",
 824                                                        &Detach,
 825                                                        &focus_handle,
 826                                                        window,
 827                                                        cx,
 828                                                    )
 829                                                }
 830                                            }),
 831                                    )
 832                                },
 833                            ),
 834                        )
 835                        .justify_around()
 836                        .when(is_side, |this| this.child(new_session_button())),
 837                )
 838                .child(
 839                    h_flex()
 840                        .gap_2()
 841                        .when(is_side, |this| this.justify_between())
 842                        .child(
 843                            h_flex().when_some(
 844                                active_session
 845                                    .as_ref()
 846                                    .map(|session| session.read(cx).running_state())
 847                                    .cloned(),
 848                                |this, running_state| {
 849                                    this.children({
 850                                        let running_state = running_state.clone();
 851                                        let threads =
 852                                            running_state.update(cx, |running_state, cx| {
 853                                                let session = running_state.session();
 854                                                session
 855                                                    .update(cx, |session, cx| session.threads(cx))
 856                                            });
 857
 858                                        self.render_thread_dropdown(
 859                                            &running_state,
 860                                            threads,
 861                                            window,
 862                                            cx,
 863                                        )
 864                                    })
 865                                    .when(!is_side, |this| this.gap_2().child(Divider::vertical()))
 866                                },
 867                            ),
 868                        )
 869                        .child(
 870                            h_flex()
 871                                .children(self.render_session_menu(
 872                                    self.active_session(),
 873                                    self.running_state(cx),
 874                                    window,
 875                                    cx,
 876                                ))
 877                                .when(!is_side, |this| this.child(new_session_button())),
 878                        ),
 879                ),
 880        )
 881    }
 882
 883    pub(crate) fn activate_pane_in_direction(
 884        &mut self,
 885        direction: SplitDirection,
 886        window: &mut Window,
 887        cx: &mut Context<Self>,
 888    ) {
 889        if let Some(session) = self.active_session() {
 890            session.update(cx, |session, cx| {
 891                session.running_state().update(cx, |running, cx| {
 892                    running.activate_pane_in_direction(direction, window, cx);
 893                })
 894            });
 895        }
 896    }
 897
 898    pub(crate) fn activate_item(
 899        &mut self,
 900        item: DebuggerPaneItem,
 901        window: &mut Window,
 902        cx: &mut Context<Self>,
 903    ) {
 904        if let Some(session) = self.active_session() {
 905            session.update(cx, |session, cx| {
 906                session.running_state().update(cx, |running, cx| {
 907                    running.activate_item(item, window, cx);
 908                });
 909            });
 910        }
 911    }
 912
 913    pub(crate) fn activate_session(
 914        &mut self,
 915        session_item: Entity<DebugSession>,
 916        window: &mut Window,
 917        cx: &mut Context<Self>,
 918    ) {
 919        debug_assert!(self.sessions.contains(&session_item));
 920        session_item.focus_handle(cx).focus(window);
 921        session_item.update(cx, |this, cx| {
 922            this.running_state().update(cx, |this, cx| {
 923                this.go_to_selected_stack_frame(window, cx);
 924            });
 925        });
 926        self.active_session = Some(session_item.clone());
 927        cx.notify();
 928    }
 929
 930    pub(crate) fn save_scenario(
 931        &self,
 932        scenario: &DebugScenario,
 933        worktree_id: WorktreeId,
 934        window: &mut Window,
 935        cx: &mut App,
 936    ) -> Task<Result<ProjectPath>> {
 937        self.workspace
 938            .update(cx, |workspace, cx| {
 939                let Some(mut path) = workspace.absolute_path_of_worktree(worktree_id, cx) else {
 940                    return Task::ready(Err(anyhow!("Couldn't get worktree path")));
 941                };
 942
 943                let serialized_scenario = serde_json::to_value(scenario);
 944
 945                cx.spawn_in(window, async move |workspace, cx| {
 946                    let serialized_scenario = serialized_scenario?;
 947                    let fs =
 948                        workspace.update(cx, |workspace, _| workspace.app_state().fs.clone())?;
 949
 950                    path.push(paths::local_settings_folder_relative_path());
 951                    if !fs.is_dir(path.as_path()).await {
 952                        fs.create_dir(path.as_path()).await?;
 953                    }
 954                    path.pop();
 955
 956                    path.push(paths::local_debug_file_relative_path());
 957                    let path = path.as_path();
 958
 959                    if !fs.is_file(path).await {
 960                        let content =
 961                            serde_json::to_string_pretty(&serde_json::Value::Array(vec![
 962                                serialized_scenario,
 963                            ]))?;
 964
 965                        fs.create_file(path, Default::default()).await?;
 966                        fs.save(path, &content.into(), Default::default()).await?;
 967                    } else {
 968                        let content = fs.load(path).await?;
 969                        let mut values = serde_json::from_str::<Vec<serde_json::Value>>(&content)?;
 970                        values.push(serialized_scenario);
 971                        fs.save(
 972                            path,
 973                            &serde_json::to_string_pretty(&values).map(Into::into)?,
 974                            Default::default(),
 975                        )
 976                        .await?;
 977                    }
 978
 979                    workspace.update(cx, |workspace, cx| {
 980                        workspace
 981                            .project()
 982                            .read(cx)
 983                            .project_path_for_absolute_path(&path, cx)
 984                            .context(
 985                                "Couldn't get project path for .zed/debug.json in active worktree",
 986                            )
 987                    })?
 988                })
 989            })
 990            .unwrap_or_else(|err| Task::ready(Err(err)))
 991    }
 992
 993    pub(crate) fn toggle_thread_picker(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 994        self.thread_picker_menu_handle.toggle(window, cx);
 995    }
 996
 997    pub(crate) fn toggle_session_picker(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 998        self.session_picker_menu_handle.toggle(window, cx);
 999    }
1000}
1001
1002impl EventEmitter<PanelEvent> for DebugPanel {}
1003impl EventEmitter<DebugPanelEvent> for DebugPanel {}
1004
1005impl Focusable for DebugPanel {
1006    fn focus_handle(&self, _: &App) -> FocusHandle {
1007        self.focus_handle.clone()
1008    }
1009}
1010
1011impl Panel for DebugPanel {
1012    fn persistent_name() -> &'static str {
1013        "DebugPanel"
1014    }
1015
1016    fn position(&self, _window: &Window, cx: &App) -> DockPosition {
1017        match DebuggerSettings::get_global(cx).dock {
1018            DebugPanelDockPosition::Left => DockPosition::Left,
1019            DebugPanelDockPosition::Bottom => DockPosition::Bottom,
1020            DebugPanelDockPosition::Right => DockPosition::Right,
1021        }
1022    }
1023
1024    fn position_is_valid(&self, _: DockPosition) -> bool {
1025        true
1026    }
1027
1028    fn set_position(
1029        &mut self,
1030        position: DockPosition,
1031        window: &mut Window,
1032        cx: &mut Context<Self>,
1033    ) {
1034        if position.axis() != self.position(window, cx).axis() {
1035            self.sessions.iter().for_each(|session_item| {
1036                session_item.update(cx, |item, cx| {
1037                    item.running_state()
1038                        .update(cx, |state, _| state.invert_axies())
1039                })
1040            });
1041        }
1042
1043        settings::update_settings_file::<DebuggerSettings>(
1044            self.fs.clone(),
1045            cx,
1046            move |settings, _| {
1047                let dock = match position {
1048                    DockPosition::Left => DebugPanelDockPosition::Left,
1049                    DockPosition::Bottom => DebugPanelDockPosition::Bottom,
1050                    DockPosition::Right => DebugPanelDockPosition::Right,
1051                };
1052                settings.dock = dock;
1053            },
1054        );
1055    }
1056
1057    fn size(&self, _window: &Window, _: &App) -> Pixels {
1058        self.size
1059    }
1060
1061    fn set_size(&mut self, size: Option<Pixels>, _window: &mut Window, _cx: &mut Context<Self>) {
1062        self.size = size.unwrap_or(px(300.));
1063    }
1064
1065    fn remote_id() -> Option<proto::PanelId> {
1066        Some(proto::PanelId::DebugPanel)
1067    }
1068
1069    fn icon(&self, _window: &Window, _cx: &App) -> Option<IconName> {
1070        Some(IconName::Debug)
1071    }
1072
1073    fn icon_tooltip(&self, _window: &Window, cx: &App) -> Option<&'static str> {
1074        if DebuggerSettings::get_global(cx).button {
1075            Some("Debug Panel")
1076        } else {
1077            None
1078        }
1079    }
1080
1081    fn toggle_action(&self) -> Box<dyn Action> {
1082        Box::new(ToggleFocus)
1083    }
1084
1085    fn pane(&self) -> Option<Entity<Pane>> {
1086        None
1087    }
1088
1089    fn activation_priority(&self) -> u32 {
1090        9
1091    }
1092
1093    fn set_active(&mut self, _: bool, _: &mut Window, _: &mut Context<Self>) {}
1094}
1095
1096impl Render for DebugPanel {
1097    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1098        let has_sessions = self.sessions.len() > 0;
1099        let this = cx.weak_entity();
1100        debug_assert_eq!(has_sessions, self.active_session.is_some());
1101
1102        if self
1103            .active_session
1104            .as_ref()
1105            .map(|session| session.read(cx).running_state())
1106            .map(|state| state.read(cx).has_open_context_menu(cx))
1107            .unwrap_or(false)
1108        {
1109            self.context_menu.take();
1110        }
1111
1112        v_flex()
1113            .size_full()
1114            .key_context("DebugPanel")
1115            .child(h_flex().children(self.top_controls_strip(window, cx)))
1116            .track_focus(&self.focus_handle(cx))
1117            .on_action({
1118                let this = this.clone();
1119                move |_: &workspace::ActivatePaneLeft, window, cx| {
1120                    this.update(cx, |this, cx| {
1121                        this.activate_pane_in_direction(SplitDirection::Left, window, cx);
1122                    })
1123                    .ok();
1124                }
1125            })
1126            .on_action({
1127                let this = this.clone();
1128                move |_: &workspace::ActivatePaneRight, window, cx| {
1129                    this.update(cx, |this, cx| {
1130                        this.activate_pane_in_direction(SplitDirection::Right, window, cx);
1131                    })
1132                    .ok();
1133                }
1134            })
1135            .on_action({
1136                let this = this.clone();
1137                move |_: &workspace::ActivatePaneUp, window, cx| {
1138                    this.update(cx, |this, cx| {
1139                        this.activate_pane_in_direction(SplitDirection::Up, window, cx);
1140                    })
1141                    .ok();
1142                }
1143            })
1144            .on_action({
1145                let this = this.clone();
1146                move |_: &workspace::ActivatePaneDown, window, cx| {
1147                    this.update(cx, |this, cx| {
1148                        this.activate_pane_in_direction(SplitDirection::Down, window, cx);
1149                    })
1150                    .ok();
1151                }
1152            })
1153            .on_action({
1154                let this = this.clone();
1155                move |_: &FocusConsole, window, cx| {
1156                    this.update(cx, |this, cx| {
1157                        this.activate_item(DebuggerPaneItem::Console, window, cx);
1158                    })
1159                    .ok();
1160                }
1161            })
1162            .on_action({
1163                let this = this.clone();
1164                move |_: &FocusVariables, window, cx| {
1165                    this.update(cx, |this, cx| {
1166                        this.activate_item(DebuggerPaneItem::Variables, window, cx);
1167                    })
1168                    .ok();
1169                }
1170            })
1171            .on_action({
1172                let this = this.clone();
1173                move |_: &FocusBreakpointList, window, cx| {
1174                    this.update(cx, |this, cx| {
1175                        this.activate_item(DebuggerPaneItem::BreakpointList, window, cx);
1176                    })
1177                    .ok();
1178                }
1179            })
1180            .on_action({
1181                let this = this.clone();
1182                move |_: &FocusFrames, window, cx| {
1183                    this.update(cx, |this, cx| {
1184                        this.activate_item(DebuggerPaneItem::Frames, window, cx);
1185                    })
1186                    .ok();
1187                }
1188            })
1189            .on_action({
1190                let this = this.clone();
1191                move |_: &FocusModules, window, cx| {
1192                    this.update(cx, |this, cx| {
1193                        this.activate_item(DebuggerPaneItem::Modules, window, cx);
1194                    })
1195                    .ok();
1196                }
1197            })
1198            .on_action({
1199                let this = this.clone();
1200                move |_: &FocusLoadedSources, window, cx| {
1201                    this.update(cx, |this, cx| {
1202                        this.activate_item(DebuggerPaneItem::LoadedSources, window, cx);
1203                    })
1204                    .ok();
1205                }
1206            })
1207            .on_action({
1208                let this = this.clone();
1209                move |_: &FocusTerminal, window, cx| {
1210                    this.update(cx, |this, cx| {
1211                        this.activate_item(DebuggerPaneItem::Terminal, window, cx);
1212                    })
1213                    .ok();
1214                }
1215            })
1216            .on_action({
1217                let this = this.clone();
1218                move |_: &ToggleThreadPicker, window, cx| {
1219                    this.update(cx, |this, cx| {
1220                        this.toggle_thread_picker(window, cx);
1221                    })
1222                    .ok();
1223                }
1224            })
1225            .on_action({
1226                let this = this.clone();
1227                move |_: &ToggleSessionPicker, window, cx| {
1228                    this.update(cx, |this, cx| {
1229                        this.toggle_session_picker(window, cx);
1230                    })
1231                    .ok();
1232                }
1233            })
1234            .when(self.active_session.is_some(), |this| {
1235                this.on_mouse_down(
1236                    MouseButton::Right,
1237                    cx.listener(|this, event: &MouseDownEvent, window, cx| {
1238                        if this
1239                            .active_session
1240                            .as_ref()
1241                            .map(|session| {
1242                                let state = session.read(cx).running_state();
1243                                state.read(cx).has_pane_at_position(event.position)
1244                            })
1245                            .unwrap_or(false)
1246                        {
1247                            this.deploy_context_menu(event.position, window, cx);
1248                        }
1249                    }),
1250                )
1251                .children(self.context_menu.as_ref().map(|(menu, position, _)| {
1252                    deferred(
1253                        anchored()
1254                            .position(*position)
1255                            .anchor(gpui::Corner::TopLeft)
1256                            .child(menu.clone()),
1257                    )
1258                    .with_priority(1)
1259                }))
1260            })
1261            .map(|this| {
1262                if has_sessions {
1263                    this.children(self.active_session.clone())
1264                } else {
1265                    this.child(
1266                        v_flex()
1267                            .h_full()
1268                            .gap_1()
1269                            .items_center()
1270                            .justify_center()
1271                            .child(
1272                                h_flex().child(
1273                                    Label::new("No Debugging Sessions")
1274                                        .size(LabelSize::Small)
1275                                        .color(Color::Muted),
1276                                ),
1277                            )
1278                            .child(
1279                                h_flex().flex_shrink().child(
1280                                    Button::new("spawn-new-session-empty-state", "New Session")
1281                                        .size(ButtonSize::Large)
1282                                        .on_click(|_, window, cx| {
1283                                            window.dispatch_action(crate::Start.boxed_clone(), cx);
1284                                        }),
1285                                ),
1286                            ),
1287                    )
1288                }
1289            })
1290            .into_any()
1291    }
1292}
1293
1294struct DebuggerProvider(Entity<DebugPanel>);
1295
1296impl workspace::DebuggerProvider for DebuggerProvider {
1297    fn start_session(
1298        &self,
1299        definition: DebugScenario,
1300        context: TaskContext,
1301        buffer: Option<Entity<Buffer>>,
1302        window: &mut Window,
1303        cx: &mut App,
1304    ) {
1305        self.0.update(cx, |_, cx| {
1306            cx.defer_in(window, |this, window, cx| {
1307                this.start_session(definition, context, buffer, None, window, cx);
1308            })
1309        })
1310    }
1311}