debugger_panel.rs

  1use crate::{
  2    ClearAllBreakpoints, Continue, CreateDebuggingSession, Disconnect, Pause, Restart, StepBack,
  3    StepInto, StepOut, StepOver, Stop, ToggleIgnoreBreakpoints,
  4};
  5use crate::{new_session_modal::NewSessionModal, session::DebugSession};
  6use anyhow::{Result, anyhow};
  7use collections::HashMap;
  8use command_palette_hooks::CommandPaletteFilter;
  9use dap::{
 10    ContinuedEvent, LoadedSourceEvent, ModuleEvent, OutputEvent, StoppedEvent, ThreadEvent,
 11    client::SessionId, debugger_settings::DebuggerSettings,
 12};
 13use futures::{SinkExt as _, channel::mpsc};
 14use gpui::{
 15    Action, App, AsyncWindowContext, Context, Entity, EntityId, EventEmitter, FocusHandle,
 16    Focusable, Subscription, Task, WeakEntity, actions,
 17};
 18
 19use project::{
 20    Project,
 21    debugger::{
 22        dap_store::{self, DapStore},
 23        session::ThreadStatus,
 24    },
 25    terminals::TerminalKind,
 26};
 27use rpc::proto::{self};
 28use settings::Settings;
 29use std::any::TypeId;
 30use std::path::Path;
 31use std::sync::Arc;
 32use task::DebugTaskDefinition;
 33use terminal_view::terminal_panel::TerminalPanel;
 34use ui::{ContextMenu, Divider, DropdownMenu, Tooltip, prelude::*};
 35use workspace::{
 36    Workspace,
 37    dock::{DockPosition, Panel, PanelEvent},
 38};
 39
 40pub enum DebugPanelEvent {
 41    Exited(SessionId),
 42    Terminated(SessionId),
 43    Stopped {
 44        client_id: SessionId,
 45        event: StoppedEvent,
 46        go_to_stack_frame: bool,
 47    },
 48    Thread((SessionId, ThreadEvent)),
 49    Continued((SessionId, ContinuedEvent)),
 50    Output((SessionId, OutputEvent)),
 51    Module((SessionId, ModuleEvent)),
 52    LoadedSource((SessionId, LoadedSourceEvent)),
 53    ClientShutdown(SessionId),
 54    CapabilitiesChanged(SessionId),
 55}
 56
 57actions!(debug_panel, [ToggleFocus]);
 58pub struct DebugPanel {
 59    size: Pixels,
 60    sessions: Vec<Entity<DebugSession>>,
 61    active_session: Option<Entity<DebugSession>>,
 62    /// This represents the last debug definition that was created in the new session modal
 63    pub(crate) past_debug_definition: Option<DebugTaskDefinition>,
 64    project: WeakEntity<Project>,
 65    workspace: WeakEntity<Workspace>,
 66    focus_handle: FocusHandle,
 67    _subscriptions: Vec<Subscription>,
 68}
 69
 70impl DebugPanel {
 71    pub fn new(
 72        workspace: &Workspace,
 73        window: &mut Window,
 74        cx: &mut Context<Workspace>,
 75    ) -> Entity<Self> {
 76        cx.new(|cx| {
 77            let project = workspace.project().clone();
 78            let dap_store = project.read(cx).dap_store();
 79
 80            let weak = cx.weak_entity();
 81
 82            let modal_subscription =
 83                cx.observe_new::<tasks_ui::TasksModal>(move |_, window, cx| {
 84                    let modal_entity = cx.entity();
 85
 86                    weak.update(cx, |_: &mut DebugPanel, cx| {
 87                        let Some(window) = window else {
 88                            log::error!("Debug panel couldn't subscribe to tasks modal because there was no window");
 89                            return;
 90                        };
 91
 92                        cx.subscribe_in(
 93                            &modal_entity,
 94                            window,
 95                            |panel, _, event: &tasks_ui::ShowAttachModal, window, cx| {
 96                                panel.workspace.update(cx, |workspace, cx| {
 97                                    let project = workspace.project().clone();
 98                                    workspace.toggle_modal(window, cx, |window, cx| {
 99                                        crate::attach_modal::AttachModal::new(
100                                            project,
101                                            event.debug_config.clone(),
102                                            true,
103                                            window,
104                                            cx,
105                                        )
106                                    });
107                                }).ok();
108                            },
109                        )
110                        .detach();
111                    })
112                    .ok();
113                });
114
115            let _subscriptions = vec![
116                cx.subscribe_in(&dap_store, window, Self::handle_dap_store_event),
117                modal_subscription,
118            ];
119
120            let debug_panel = Self {
121                size: px(300.),
122                sessions: vec![],
123                active_session: None,
124                _subscriptions,
125                past_debug_definition: None,
126                focus_handle: cx.focus_handle(),
127                project: project.downgrade(),
128                workspace: workspace.weak_handle(),
129            };
130
131            debug_panel
132        })
133    }
134
135    fn filter_action_types(&self, cx: &mut App) {
136        let (has_active_session, supports_restart, support_step_back, status) = self
137            .active_session()
138            .map(|item| {
139                let running = item.read(cx).mode().as_running().cloned();
140
141                match running {
142                    Some(running) => {
143                        let caps = running.read(cx).capabilities(cx);
144                        (
145                            !running.read(cx).session().read(cx).is_terminated(),
146                            caps.supports_restart_request.unwrap_or_default(),
147                            caps.supports_step_back.unwrap_or_default(),
148                            running.read(cx).thread_status(cx),
149                        )
150                    }
151                    None => (false, false, false, None),
152                }
153            })
154            .unwrap_or((false, false, false, None));
155
156        let filter = CommandPaletteFilter::global_mut(cx);
157        let debugger_action_types = [
158            TypeId::of::<Disconnect>(),
159            TypeId::of::<Stop>(),
160            TypeId::of::<ToggleIgnoreBreakpoints>(),
161        ];
162
163        let running_action_types = [TypeId::of::<Pause>()];
164
165        let stopped_action_type = [
166            TypeId::of::<Continue>(),
167            TypeId::of::<StepOver>(),
168            TypeId::of::<StepInto>(),
169            TypeId::of::<StepOut>(),
170            TypeId::of::<editor::actions::DebuggerRunToCursor>(),
171            TypeId::of::<editor::actions::DebuggerEvaluateSelectedText>(),
172        ];
173
174        let step_back_action_type = [TypeId::of::<StepBack>()];
175        let restart_action_type = [TypeId::of::<Restart>()];
176
177        if has_active_session {
178            filter.show_action_types(debugger_action_types.iter());
179
180            if supports_restart {
181                filter.show_action_types(restart_action_type.iter());
182            } else {
183                filter.hide_action_types(&restart_action_type);
184            }
185
186            if support_step_back {
187                filter.show_action_types(step_back_action_type.iter());
188            } else {
189                filter.hide_action_types(&step_back_action_type);
190            }
191
192            match status {
193                Some(ThreadStatus::Running) => {
194                    filter.show_action_types(running_action_types.iter());
195                    filter.hide_action_types(&stopped_action_type);
196                }
197                Some(ThreadStatus::Stopped) => {
198                    filter.show_action_types(stopped_action_type.iter());
199                    filter.hide_action_types(&running_action_types);
200                }
201                _ => {
202                    filter.hide_action_types(&running_action_types);
203                    filter.hide_action_types(&stopped_action_type);
204                }
205            }
206        } else {
207            // show only the `debug: start`
208            filter.hide_action_types(&debugger_action_types);
209            filter.hide_action_types(&step_back_action_type);
210            filter.hide_action_types(&restart_action_type);
211            filter.hide_action_types(&running_action_types);
212            filter.hide_action_types(&stopped_action_type);
213        }
214    }
215
216    pub fn load(
217        workspace: WeakEntity<Workspace>,
218        cx: AsyncWindowContext,
219    ) -> Task<Result<Entity<Self>>> {
220        cx.spawn(async move |cx| {
221            workspace.update_in(cx, |workspace, window, cx| {
222                let debug_panel = DebugPanel::new(workspace, window, cx);
223
224                workspace.register_action(|workspace, _: &ClearAllBreakpoints, _, cx| {
225                    workspace.project().read(cx).breakpoint_store().update(
226                        cx,
227                        |breakpoint_store, cx| {
228                            breakpoint_store.clear_breakpoints(cx);
229                        },
230                    )
231                });
232
233                cx.observe_new::<DebugPanel>(|debug_panel, _, cx| {
234                    Self::filter_action_types(debug_panel, cx);
235                })
236                .detach();
237
238                cx.observe(&debug_panel, |_, debug_panel, cx| {
239                    debug_panel.update(cx, |debug_panel, cx| {
240                        Self::filter_action_types(debug_panel, cx);
241                    });
242                })
243                .detach();
244
245                debug_panel
246            })
247        })
248    }
249
250    pub fn active_session(&self) -> Option<Entity<DebugSession>> {
251        self.active_session.clone()
252    }
253
254    pub fn debug_panel_items_by_client(
255        &self,
256        client_id: &SessionId,
257        cx: &Context<Self>,
258    ) -> Vec<Entity<DebugSession>> {
259        self.sessions
260            .iter()
261            .filter(|item| item.read(cx).session_id(cx) == *client_id)
262            .map(|item| item.clone())
263            .collect()
264    }
265
266    pub fn debug_panel_item_by_client(
267        &self,
268        client_id: SessionId,
269        cx: &mut Context<Self>,
270    ) -> Option<Entity<DebugSession>> {
271        self.sessions
272            .iter()
273            .find(|item| {
274                let item = item.read(cx);
275
276                item.session_id(cx) == client_id
277            })
278            .cloned()
279    }
280
281    fn handle_dap_store_event(
282        &mut self,
283        dap_store: &Entity<DapStore>,
284        event: &dap_store::DapStoreEvent,
285        window: &mut Window,
286        cx: &mut Context<Self>,
287    ) {
288        match event {
289            dap_store::DapStoreEvent::DebugSessionInitialized(session_id) => {
290                let Some(session) = dap_store.read(cx).session_by_id(session_id) else {
291                    return log::error!(
292                        "Couldn't get session with id: {session_id:?} from DebugClientStarted event"
293                    );
294                };
295
296                let Some(project) = self.project.upgrade() else {
297                    return log::error!("Debug Panel out lived it's weak reference to Project");
298                };
299
300                if self
301                    .sessions
302                    .iter()
303                    .any(|item| item.read(cx).session_id(cx) == *session_id)
304                {
305                    // We already have an item for this session.
306                    return;
307                }
308                let session_item = DebugSession::running(
309                    project,
310                    self.workspace.clone(),
311                    session,
312                    cx.weak_entity(),
313                    window,
314                    cx,
315                );
316
317                if let Some(running) = session_item.read(cx).mode().as_running().cloned() {
318                    // We might want to make this an event subscription and only notify when a new thread is selected
319                    // This is used to filter the command menu correctly
320                    cx.observe(&running, |_, _, cx| cx.notify()).detach();
321                }
322
323                self.sessions.push(session_item.clone());
324                self.activate_session(session_item, window, cx);
325            }
326            dap_store::DapStoreEvent::RunInTerminal {
327                title,
328                cwd,
329                command,
330                args,
331                envs,
332                sender,
333                ..
334            } => {
335                self.handle_run_in_terminal_request(
336                    title.clone(),
337                    cwd.clone(),
338                    command.clone(),
339                    args.clone(),
340                    envs.clone(),
341                    sender.clone(),
342                    window,
343                    cx,
344                )
345                .detach_and_log_err(cx);
346            }
347            _ => {}
348        }
349    }
350
351    fn handle_run_in_terminal_request(
352        &self,
353        title: Option<String>,
354        cwd: Option<Arc<Path>>,
355        command: Option<String>,
356        args: Vec<String>,
357        envs: HashMap<String, String>,
358        mut sender: mpsc::Sender<Result<u32>>,
359        window: &mut Window,
360        cx: &mut App,
361    ) -> Task<Result<()>> {
362        let terminal_task = self.workspace.update(cx, |workspace, cx| {
363            let terminal_panel = workspace.panel::<TerminalPanel>(cx).ok_or_else(|| {
364                anyhow!("RunInTerminal DAP request failed because TerminalPanel wasn't found")
365            });
366
367            let terminal_panel = match terminal_panel {
368                Ok(panel) => panel,
369                Err(err) => return Task::ready(Err(err)),
370            };
371
372            terminal_panel.update(cx, |terminal_panel, cx| {
373                let terminal_task = terminal_panel.add_terminal(
374                    TerminalKind::Debug {
375                        command,
376                        args,
377                        envs,
378                        cwd,
379                        title,
380                    },
381                    task::RevealStrategy::Always,
382                    window,
383                    cx,
384                );
385
386                cx.spawn(async move |_, cx| {
387                    let pid_task = async move {
388                        let terminal = terminal_task.await?;
389
390                        terminal.read_with(cx, |terminal, _| terminal.pty_info.pid())
391                    };
392
393                    pid_task.await
394                })
395            })
396        });
397
398        cx.background_spawn(async move {
399            match terminal_task {
400                Ok(pid_task) => match pid_task.await {
401                    Ok(Some(pid)) => sender.send(Ok(pid.as_u32())).await?,
402                    Ok(None) => {
403                        sender
404                            .send(Err(anyhow!(
405                                "Terminal was spawned but PID was not available"
406                            )))
407                            .await?
408                    }
409                    Err(error) => sender.send(Err(anyhow!(error))).await?,
410                },
411                Err(error) => sender.send(Err(anyhow!(error))).await?,
412            };
413
414            Ok(())
415        })
416    }
417
418    fn close_session(&mut self, entity_id: EntityId, cx: &mut Context<Self>) {
419        let Some(session) = self
420            .sessions
421            .iter()
422            .find(|other| entity_id == other.entity_id())
423        else {
424            return;
425        };
426
427        session.update(cx, |session, cx| session.shutdown(cx));
428
429        self.sessions.retain(|other| entity_id != other.entity_id());
430
431        if let Some(active_session_id) = self
432            .active_session
433            .as_ref()
434            .map(|session| session.entity_id())
435        {
436            if active_session_id == entity_id {
437                self.active_session = self.sessions.first().cloned();
438            }
439        }
440
441        cx.notify();
442    }
443
444    fn sessions_drop_down_menu(
445        &self,
446        active_session: &Entity<DebugSession>,
447        window: &mut Window,
448        cx: &mut Context<Self>,
449    ) -> DropdownMenu {
450        let sessions = self.sessions.clone();
451        let weak = cx.weak_entity();
452        let label = active_session.read(cx).label_element(cx);
453
454        DropdownMenu::new_with_element(
455            "debugger-session-list",
456            label,
457            ContextMenu::build(window, cx, move |mut this, _, cx| {
458                let context_menu = cx.weak_entity();
459                for session in sessions.into_iter() {
460                    let weak_session = session.downgrade();
461                    let weak_session_id = weak_session.entity_id();
462
463                    this = this.custom_entry(
464                        {
465                            let weak = weak.clone();
466                            let context_menu = context_menu.clone();
467                            move |_, cx| {
468                                weak_session
469                                    .read_with(cx, |session, cx| {
470                                        let context_menu = context_menu.clone();
471                                        let id: SharedString =
472                                            format!("debug-session-{}", session.session_id(cx).0)
473                                                .into();
474                                        h_flex()
475                                            .w_full()
476                                            .group(id.clone())
477                                            .justify_between()
478                                            .child(session.label_element(cx))
479                                            .child(
480                                                IconButton::new(
481                                                    "close-debug-session",
482                                                    IconName::Close,
483                                                )
484                                                .visible_on_hover(id.clone())
485                                                .icon_size(IconSize::Small)
486                                                .on_click({
487                                                    let weak = weak.clone();
488                                                    move |_, window, cx| {
489                                                        weak.update(cx, |panel, cx| {
490                                                            panel
491                                                                .close_session(weak_session_id, cx);
492                                                        })
493                                                        .ok();
494                                                        context_menu
495                                                            .update(cx, |this, cx| {
496                                                                this.cancel(
497                                                                    &Default::default(),
498                                                                    window,
499                                                                    cx,
500                                                                );
501                                                            })
502                                                            .ok();
503                                                    }
504                                                }),
505                                            )
506                                            .into_any_element()
507                                    })
508                                    .unwrap_or_else(|_| div().into_any_element())
509                            }
510                        },
511                        {
512                            let weak = weak.clone();
513                            move |window, cx| {
514                                weak.update(cx, |panel, cx| {
515                                    panel.activate_session(session.clone(), window, cx);
516                                })
517                                .ok();
518                            }
519                        },
520                    );
521                }
522                this
523            }),
524        )
525    }
526
527    fn top_controls_strip(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
528        let active_session = self.active_session.clone();
529
530        Some(
531            h_flex()
532                .border_b_1()
533                .border_color(cx.theme().colors().border)
534                .p_1()
535                .justify_between()
536                .w_full()
537                .child(
538                    h_flex().gap_2().w_full().when_some(
539                        active_session
540                            .as_ref()
541                            .and_then(|session| session.read(cx).mode().as_running()),
542                        |this, running_session| {
543                            let thread_status = running_session
544                                .read(cx)
545                                .thread_status(cx)
546                                .unwrap_or(project::debugger::session::ThreadStatus::Exited);
547                            let capabilities = running_session.read(cx).capabilities(cx);
548                            this.map(|this| {
549                                if thread_status == ThreadStatus::Running {
550                                    this.child(
551                                        IconButton::new("debug-pause", IconName::DebugPause)
552                                            .icon_size(IconSize::XSmall)
553                                            .shape(ui::IconButtonShape::Square)
554                                            .on_click(window.listener_for(
555                                                &running_session,
556                                                |this, _, _window, cx| {
557                                                    this.pause_thread(cx);
558                                                },
559                                            ))
560                                            .tooltip(move |window, cx| {
561                                                Tooltip::text("Pause program")(window, cx)
562                                            }),
563                                    )
564                                } else {
565                                    this.child(
566                                        IconButton::new("debug-continue", IconName::DebugContinue)
567                                            .icon_size(IconSize::XSmall)
568                                            .shape(ui::IconButtonShape::Square)
569                                            .on_click(window.listener_for(
570                                                &running_session,
571                                                |this, _, _window, cx| this.continue_thread(cx),
572                                            ))
573                                            .disabled(thread_status != ThreadStatus::Stopped)
574                                            .tooltip(move |window, cx| {
575                                                Tooltip::text("Continue program")(window, cx)
576                                            }),
577                                    )
578                                }
579                            })
580                            .child(
581                                IconButton::new("debug-step-over", IconName::ArrowRight)
582                                    .icon_size(IconSize::XSmall)
583                                    .shape(ui::IconButtonShape::Square)
584                                    .on_click(window.listener_for(
585                                        &running_session,
586                                        |this, _, _window, cx| {
587                                            this.step_over(cx);
588                                        },
589                                    ))
590                                    .disabled(thread_status != ThreadStatus::Stopped)
591                                    .tooltip(move |window, cx| {
592                                        Tooltip::text("Step over")(window, cx)
593                                    }),
594                            )
595                            .child(
596                                IconButton::new("debug-step-out", IconName::ArrowUpRight)
597                                    .icon_size(IconSize::XSmall)
598                                    .shape(ui::IconButtonShape::Square)
599                                    .on_click(window.listener_for(
600                                        &running_session,
601                                        |this, _, _window, cx| {
602                                            this.step_out(cx);
603                                        },
604                                    ))
605                                    .disabled(thread_status != ThreadStatus::Stopped)
606                                    .tooltip(move |window, cx| {
607                                        Tooltip::text("Step out")(window, cx)
608                                    }),
609                            )
610                            .child(
611                                IconButton::new("debug-step-into", IconName::ArrowDownRight)
612                                    .icon_size(IconSize::XSmall)
613                                    .shape(ui::IconButtonShape::Square)
614                                    .on_click(window.listener_for(
615                                        &running_session,
616                                        |this, _, _window, cx| {
617                                            this.step_in(cx);
618                                        },
619                                    ))
620                                    .disabled(thread_status != ThreadStatus::Stopped)
621                                    .tooltip(move |window, cx| {
622                                        Tooltip::text("Step in")(window, cx)
623                                    }),
624                            )
625                            .child(Divider::vertical())
626                            .child(
627                                IconButton::new(
628                                    "debug-enable-breakpoint",
629                                    IconName::DebugDisabledBreakpoint,
630                                )
631                                .icon_size(IconSize::XSmall)
632                                .shape(ui::IconButtonShape::Square)
633                                .disabled(thread_status != ThreadStatus::Stopped),
634                            )
635                            .child(
636                                IconButton::new("debug-disable-breakpoint", IconName::CircleOff)
637                                    .icon_size(IconSize::XSmall)
638                                    .shape(ui::IconButtonShape::Square)
639                                    .disabled(thread_status != ThreadStatus::Stopped),
640                            )
641                            .child(
642                                IconButton::new("debug-disable-all-breakpoints", IconName::BugOff)
643                                    .icon_size(IconSize::XSmall)
644                                    .shape(ui::IconButtonShape::Square)
645                                    .disabled(
646                                        thread_status == ThreadStatus::Exited
647                                            || thread_status == ThreadStatus::Ended,
648                                    )
649                                    .on_click(window.listener_for(
650                                        &running_session,
651                                        |this, _, _window, cx| {
652                                            this.toggle_ignore_breakpoints(cx);
653                                        },
654                                    ))
655                                    .tooltip(move |window, cx| {
656                                        Tooltip::text("Disable all breakpoints")(window, cx)
657                                    }),
658                            )
659                            .child(Divider::vertical())
660                            .child(
661                                IconButton::new("debug-restart", IconName::DebugRestart)
662                                    .icon_size(IconSize::XSmall)
663                                    .on_click(window.listener_for(
664                                        &running_session,
665                                        |this, _, _window, cx| {
666                                            this.restart_session(cx);
667                                        },
668                                    ))
669                                    .disabled(
670                                        !capabilities.supports_restart_request.unwrap_or_default(),
671                                    )
672                                    .tooltip(move |window, cx| {
673                                        Tooltip::text("Restart")(window, cx)
674                                    }),
675                            )
676                            .child(
677                                IconButton::new("debug-stop", IconName::Power)
678                                    .icon_size(IconSize::XSmall)
679                                    .on_click(window.listener_for(
680                                        &running_session,
681                                        |this, _, _window, cx| {
682                                            this.stop_thread(cx);
683                                        },
684                                    ))
685                                    .disabled(
686                                        thread_status != ThreadStatus::Stopped
687                                            && thread_status != ThreadStatus::Running,
688                                    )
689                                    .tooltip({
690                                        let label = if capabilities
691                                            .supports_terminate_threads_request
692                                            .unwrap_or_default()
693                                        {
694                                            "Terminate Thread"
695                                        } else {
696                                            "Terminate all Threads"
697                                        };
698                                        move |window, cx| Tooltip::text(label)(window, cx)
699                                    }),
700                            )
701                        },
702                    ),
703                )
704                .child(
705                    h_flex()
706                        .gap_2()
707                        .when_some(
708                            active_session
709                                .as_ref()
710                                .and_then(|session| session.read(cx).mode().as_running())
711                                .cloned(),
712                            |this, session| {
713                                this.child(
714                                    session.update(cx, |this, cx| this.thread_dropdown(window, cx)),
715                                )
716                                .child(Divider::vertical())
717                            },
718                        )
719                        .when_some(active_session.as_ref(), |this, session| {
720                            let context_menu = self.sessions_drop_down_menu(session, window, cx);
721                            this.child(context_menu).child(Divider::vertical())
722                        })
723                        .child(
724                            IconButton::new("debug-new-session", IconName::Plus)
725                                .icon_size(IconSize::Small)
726                                .on_click({
727                                    let workspace = self.workspace.clone();
728                                    let weak_panel = cx.weak_entity();
729                                    let past_debug_definition = self.past_debug_definition.clone();
730                                    move |_, window, cx| {
731                                        let weak_panel = weak_panel.clone();
732                                        let past_debug_definition = past_debug_definition.clone();
733
734                                        let _ = workspace.update(cx, |this, cx| {
735                                            let workspace = cx.weak_entity();
736                                            this.toggle_modal(window, cx, |window, cx| {
737                                                NewSessionModal::new(
738                                                    past_debug_definition,
739                                                    weak_panel,
740                                                    workspace,
741                                                    window,
742                                                    cx,
743                                                )
744                                            });
745                                        });
746                                    }
747                                })
748                                .tooltip(|window, cx| {
749                                    Tooltip::for_action(
750                                        "New Debug Session",
751                                        &CreateDebuggingSession,
752                                        window,
753                                        cx,
754                                    )
755                                }),
756                        ),
757                ),
758        )
759    }
760
761    fn activate_session(
762        &mut self,
763        session_item: Entity<DebugSession>,
764        window: &mut Window,
765        cx: &mut Context<Self>,
766    ) {
767        debug_assert!(self.sessions.contains(&session_item));
768        session_item.focus_handle(cx).focus(window);
769        session_item.update(cx, |this, cx| {
770            if let Some(running) = this.mode().as_running() {
771                running.update(cx, |this, cx| {
772                    this.go_to_selected_stack_frame(window, cx);
773                });
774            }
775        });
776        self.active_session = Some(session_item);
777        cx.notify();
778    }
779}
780
781impl EventEmitter<PanelEvent> for DebugPanel {}
782impl EventEmitter<DebugPanelEvent> for DebugPanel {}
783impl EventEmitter<project::Event> for DebugPanel {}
784
785impl Focusable for DebugPanel {
786    fn focus_handle(&self, _: &App) -> FocusHandle {
787        self.focus_handle.clone()
788    }
789}
790
791impl Panel for DebugPanel {
792    fn persistent_name() -> &'static str {
793        "DebugPanel"
794    }
795
796    fn position(&self, _window: &Window, _cx: &App) -> DockPosition {
797        DockPosition::Bottom
798    }
799
800    fn position_is_valid(&self, position: DockPosition) -> bool {
801        position == DockPosition::Bottom
802    }
803
804    fn set_position(
805        &mut self,
806        _position: DockPosition,
807        _window: &mut Window,
808        _cx: &mut Context<Self>,
809    ) {
810    }
811
812    fn size(&self, _window: &Window, _: &App) -> Pixels {
813        self.size
814    }
815
816    fn set_size(&mut self, size: Option<Pixels>, _window: &mut Window, _cx: &mut Context<Self>) {
817        self.size = size.unwrap();
818    }
819
820    fn remote_id() -> Option<proto::PanelId> {
821        Some(proto::PanelId::DebugPanel)
822    }
823
824    fn icon(&self, _window: &Window, _cx: &App) -> Option<IconName> {
825        Some(IconName::Debug)
826    }
827
828    fn icon_tooltip(&self, _window: &Window, cx: &App) -> Option<&'static str> {
829        if DebuggerSettings::get_global(cx).button {
830            Some("Debug Panel")
831        } else {
832            None
833        }
834    }
835
836    fn toggle_action(&self) -> Box<dyn Action> {
837        Box::new(ToggleFocus)
838    }
839
840    fn activation_priority(&self) -> u32 {
841        9
842    }
843    fn set_active(&mut self, _: bool, _: &mut Window, _: &mut Context<Self>) {}
844}
845
846impl Render for DebugPanel {
847    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
848        let has_sessions = self.sessions.len() > 0;
849        debug_assert_eq!(has_sessions, self.active_session.is_some());
850
851        v_flex()
852            .size_full()
853            .key_context("DebugPanel")
854            .child(h_flex().children(self.top_controls_strip(window, cx)))
855            .track_focus(&self.focus_handle(cx))
856            .map(|this| {
857                if has_sessions {
858                    this.children(self.active_session.clone())
859                } else {
860                    this.child(
861                        v_flex()
862                            .h_full()
863                            .gap_1()
864                            .items_center()
865                            .justify_center()
866                            .child(
867                                h_flex().child(
868                                    Label::new("No Debugging Sessions")
869                                        .size(LabelSize::Small)
870                                        .color(Color::Muted),
871                                ),
872                            )
873                            .child(
874                                h_flex().flex_shrink().child(
875                                    Button::new("spawn-new-session-empty-state", "New Session")
876                                        .size(ButtonSize::Large)
877                                        .on_click(|_, window, cx| {
878                                            window.dispatch_action(
879                                                CreateDebuggingSession.boxed_clone(),
880                                                cx,
881                                            );
882                                        }),
883                                ),
884                            ),
885                    )
886                }
887            })
888            .into_any()
889    }
890}