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, window: &mut Window, cx: &mut Context<Self>) {
419        let Some(session) = self
420            .sessions
421            .iter()
422            .find(|other| entity_id == other.entity_id())
423            .cloned()
424        else {
425            return;
426        };
427
428        let session_id = session.update(cx, |this, cx| this.session_id(cx));
429        let should_prompt = self
430            .project
431            .update(cx, |this, cx| {
432                let session = this.dap_store().read(cx).session_by_id(session_id);
433                session.map(|session| !session.read(cx).is_terminated())
434            })
435            .ok()
436            .flatten()
437            .unwrap_or_default();
438
439        cx.spawn_in(window, async move |this, cx| {
440            if should_prompt {
441                let response = cx.prompt(
442                    gpui::PromptLevel::Warning,
443                    "This Debug Session is still running. Are you sure you want to terminate it?",
444                    None,
445                    &["Yes", "No"],
446                );
447                if response.await == Ok(1) {
448                    return;
449                }
450            }
451            session.update(cx, |session, cx| session.shutdown(cx)).ok();
452            this.update(cx, |this, cx| {
453                this.sessions.retain(|other| entity_id != other.entity_id());
454
455                if let Some(active_session_id) = this
456                    .active_session
457                    .as_ref()
458                    .map(|session| session.entity_id())
459                {
460                    if active_session_id == entity_id {
461                        this.active_session = this.sessions.first().cloned();
462                    }
463                }
464                cx.notify()
465            })
466            .ok();
467        })
468        .detach();
469    }
470    fn sessions_drop_down_menu(
471        &self,
472        active_session: &Entity<DebugSession>,
473        window: &mut Window,
474        cx: &mut Context<Self>,
475    ) -> DropdownMenu {
476        let sessions = self.sessions.clone();
477        let weak = cx.weak_entity();
478        let label = active_session.read(cx).label_element(cx);
479
480        DropdownMenu::new_with_element(
481            "debugger-session-list",
482            label,
483            ContextMenu::build(window, cx, move |mut this, _, cx| {
484                let context_menu = cx.weak_entity();
485                for session in sessions.into_iter() {
486                    let weak_session = session.downgrade();
487                    let weak_session_id = weak_session.entity_id();
488
489                    this = this.custom_entry(
490                        {
491                            let weak = weak.clone();
492                            let context_menu = context_menu.clone();
493                            move |_, cx| {
494                                weak_session
495                                    .read_with(cx, |session, cx| {
496                                        let context_menu = context_menu.clone();
497                                        let id: SharedString =
498                                            format!("debug-session-{}", session.session_id(cx).0)
499                                                .into();
500                                        h_flex()
501                                            .w_full()
502                                            .group(id.clone())
503                                            .justify_between()
504                                            .child(session.label_element(cx))
505                                            .child(
506                                                IconButton::new(
507                                                    "close-debug-session",
508                                                    IconName::Close,
509                                                )
510                                                .visible_on_hover(id.clone())
511                                                .icon_size(IconSize::Small)
512                                                .on_click({
513                                                    let weak = weak.clone();
514                                                    move |_, window, cx| {
515                                                        weak.update(cx, |panel, cx| {
516                                                            panel.close_session(
517                                                                weak_session_id,
518                                                                window,
519                                                                cx,
520                                                            );
521                                                        })
522                                                        .ok();
523                                                        context_menu
524                                                            .update(cx, |this, cx| {
525                                                                this.cancel(
526                                                                    &Default::default(),
527                                                                    window,
528                                                                    cx,
529                                                                );
530                                                            })
531                                                            .ok();
532                                                    }
533                                                }),
534                                            )
535                                            .into_any_element()
536                                    })
537                                    .unwrap_or_else(|_| div().into_any_element())
538                            }
539                        },
540                        {
541                            let weak = weak.clone();
542                            move |window, cx| {
543                                weak.update(cx, |panel, cx| {
544                                    panel.activate_session(session.clone(), window, cx);
545                                })
546                                .ok();
547                            }
548                        },
549                    );
550                }
551                this
552            }),
553        )
554    }
555
556    fn top_controls_strip(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
557        let active_session = self.active_session.clone();
558
559        Some(
560            h_flex()
561                .border_b_1()
562                .border_color(cx.theme().colors().border)
563                .p_1()
564                .justify_between()
565                .w_full()
566                .child(
567                    h_flex().gap_2().w_full().when_some(
568                        active_session
569                            .as_ref()
570                            .and_then(|session| session.read(cx).mode().as_running()),
571                        |this, running_session| {
572                            let thread_status = running_session
573                                .read(cx)
574                                .thread_status(cx)
575                                .unwrap_or(project::debugger::session::ThreadStatus::Exited);
576                            let capabilities = running_session.read(cx).capabilities(cx);
577                            this.map(|this| {
578                                if thread_status == ThreadStatus::Running {
579                                    this.child(
580                                        IconButton::new("debug-pause", IconName::DebugPause)
581                                            .icon_size(IconSize::XSmall)
582                                            .shape(ui::IconButtonShape::Square)
583                                            .on_click(window.listener_for(
584                                                &running_session,
585                                                |this, _, _window, cx| {
586                                                    this.pause_thread(cx);
587                                                },
588                                            ))
589                                            .tooltip(move |window, cx| {
590                                                Tooltip::text("Pause program")(window, cx)
591                                            }),
592                                    )
593                                } else {
594                                    this.child(
595                                        IconButton::new("debug-continue", IconName::DebugContinue)
596                                            .icon_size(IconSize::XSmall)
597                                            .shape(ui::IconButtonShape::Square)
598                                            .on_click(window.listener_for(
599                                                &running_session,
600                                                |this, _, _window, cx| this.continue_thread(cx),
601                                            ))
602                                            .disabled(thread_status != ThreadStatus::Stopped)
603                                            .tooltip(move |window, cx| {
604                                                Tooltip::text("Continue program")(window, cx)
605                                            }),
606                                    )
607                                }
608                            })
609                            .child(
610                                IconButton::new("debug-step-over", IconName::ArrowRight)
611                                    .icon_size(IconSize::XSmall)
612                                    .shape(ui::IconButtonShape::Square)
613                                    .on_click(window.listener_for(
614                                        &running_session,
615                                        |this, _, _window, cx| {
616                                            this.step_over(cx);
617                                        },
618                                    ))
619                                    .disabled(thread_status != ThreadStatus::Stopped)
620                                    .tooltip(move |window, cx| {
621                                        Tooltip::text("Step over")(window, cx)
622                                    }),
623                            )
624                            .child(
625                                IconButton::new("debug-step-out", IconName::ArrowUpRight)
626                                    .icon_size(IconSize::XSmall)
627                                    .shape(ui::IconButtonShape::Square)
628                                    .on_click(window.listener_for(
629                                        &running_session,
630                                        |this, _, _window, cx| {
631                                            this.step_out(cx);
632                                        },
633                                    ))
634                                    .disabled(thread_status != ThreadStatus::Stopped)
635                                    .tooltip(move |window, cx| {
636                                        Tooltip::text("Step out")(window, cx)
637                                    }),
638                            )
639                            .child(
640                                IconButton::new("debug-step-into", IconName::ArrowDownRight)
641                                    .icon_size(IconSize::XSmall)
642                                    .shape(ui::IconButtonShape::Square)
643                                    .on_click(window.listener_for(
644                                        &running_session,
645                                        |this, _, _window, cx| {
646                                            this.step_in(cx);
647                                        },
648                                    ))
649                                    .disabled(thread_status != ThreadStatus::Stopped)
650                                    .tooltip(move |window, cx| {
651                                        Tooltip::text("Step in")(window, cx)
652                                    }),
653                            )
654                            .child(Divider::vertical())
655                            .child(
656                                IconButton::new(
657                                    "debug-enable-breakpoint",
658                                    IconName::DebugDisabledBreakpoint,
659                                )
660                                .icon_size(IconSize::XSmall)
661                                .shape(ui::IconButtonShape::Square)
662                                .disabled(thread_status != ThreadStatus::Stopped),
663                            )
664                            .child(
665                                IconButton::new("debug-disable-breakpoint", IconName::CircleOff)
666                                    .icon_size(IconSize::XSmall)
667                                    .shape(ui::IconButtonShape::Square)
668                                    .disabled(thread_status != ThreadStatus::Stopped),
669                            )
670                            .child(
671                                IconButton::new("debug-disable-all-breakpoints", IconName::BugOff)
672                                    .icon_size(IconSize::XSmall)
673                                    .shape(ui::IconButtonShape::Square)
674                                    .disabled(
675                                        thread_status == ThreadStatus::Exited
676                                            || thread_status == ThreadStatus::Ended,
677                                    )
678                                    .on_click(window.listener_for(
679                                        &running_session,
680                                        |this, _, _window, cx| {
681                                            this.toggle_ignore_breakpoints(cx);
682                                        },
683                                    ))
684                                    .tooltip(move |window, cx| {
685                                        Tooltip::text("Disable all breakpoints")(window, cx)
686                                    }),
687                            )
688                            .child(Divider::vertical())
689                            .child(
690                                IconButton::new("debug-restart", IconName::DebugRestart)
691                                    .icon_size(IconSize::XSmall)
692                                    .on_click(window.listener_for(
693                                        &running_session,
694                                        |this, _, _window, cx| {
695                                            this.restart_session(cx);
696                                        },
697                                    ))
698                                    .disabled(
699                                        !capabilities.supports_restart_request.unwrap_or_default(),
700                                    )
701                                    .tooltip(move |window, cx| {
702                                        Tooltip::text("Restart")(window, cx)
703                                    }),
704                            )
705                            .child(
706                                IconButton::new("debug-stop", IconName::Power)
707                                    .icon_size(IconSize::XSmall)
708                                    .on_click(window.listener_for(
709                                        &running_session,
710                                        |this, _, _window, cx| {
711                                            this.stop_thread(cx);
712                                        },
713                                    ))
714                                    .disabled(
715                                        thread_status != ThreadStatus::Stopped
716                                            && thread_status != ThreadStatus::Running,
717                                    )
718                                    .tooltip({
719                                        let label = if capabilities
720                                            .supports_terminate_threads_request
721                                            .unwrap_or_default()
722                                        {
723                                            "Terminate Thread"
724                                        } else {
725                                            "Terminate all Threads"
726                                        };
727                                        move |window, cx| Tooltip::text(label)(window, cx)
728                                    }),
729                            )
730                        },
731                    ),
732                )
733                .child(
734                    h_flex()
735                        .gap_2()
736                        .when_some(
737                            active_session
738                                .as_ref()
739                                .and_then(|session| session.read(cx).mode().as_running())
740                                .cloned(),
741                            |this, session| {
742                                this.child(
743                                    session.update(cx, |this, cx| this.thread_dropdown(window, cx)),
744                                )
745                                .child(Divider::vertical())
746                            },
747                        )
748                        .when_some(active_session.as_ref(), |this, session| {
749                            let context_menu = self.sessions_drop_down_menu(session, window, cx);
750                            this.child(context_menu).child(Divider::vertical())
751                        })
752                        .child(
753                            IconButton::new("debug-new-session", IconName::Plus)
754                                .icon_size(IconSize::Small)
755                                .on_click({
756                                    let workspace = self.workspace.clone();
757                                    let weak_panel = cx.weak_entity();
758                                    let past_debug_definition = self.past_debug_definition.clone();
759                                    move |_, window, cx| {
760                                        let weak_panel = weak_panel.clone();
761                                        let past_debug_definition = past_debug_definition.clone();
762
763                                        let _ = workspace.update(cx, |this, cx| {
764                                            let workspace = cx.weak_entity();
765                                            this.toggle_modal(window, cx, |window, cx| {
766                                                NewSessionModal::new(
767                                                    past_debug_definition,
768                                                    weak_panel,
769                                                    workspace,
770                                                    window,
771                                                    cx,
772                                                )
773                                            });
774                                        });
775                                    }
776                                })
777                                .tooltip(|window, cx| {
778                                    Tooltip::for_action(
779                                        "New Debug Session",
780                                        &CreateDebuggingSession,
781                                        window,
782                                        cx,
783                                    )
784                                }),
785                        ),
786                ),
787        )
788    }
789
790    fn activate_session(
791        &mut self,
792        session_item: Entity<DebugSession>,
793        window: &mut Window,
794        cx: &mut Context<Self>,
795    ) {
796        debug_assert!(self.sessions.contains(&session_item));
797        session_item.focus_handle(cx).focus(window);
798        session_item.update(cx, |this, cx| {
799            if let Some(running) = this.mode().as_running() {
800                running.update(cx, |this, cx| {
801                    this.go_to_selected_stack_frame(window, cx);
802                });
803            }
804        });
805        self.active_session = Some(session_item);
806        cx.notify();
807    }
808}
809
810impl EventEmitter<PanelEvent> for DebugPanel {}
811impl EventEmitter<DebugPanelEvent> for DebugPanel {}
812impl EventEmitter<project::Event> for DebugPanel {}
813
814impl Focusable for DebugPanel {
815    fn focus_handle(&self, _: &App) -> FocusHandle {
816        self.focus_handle.clone()
817    }
818}
819
820impl Panel for DebugPanel {
821    fn persistent_name() -> &'static str {
822        "DebugPanel"
823    }
824
825    fn position(&self, _window: &Window, _cx: &App) -> DockPosition {
826        DockPosition::Bottom
827    }
828
829    fn position_is_valid(&self, position: DockPosition) -> bool {
830        position == DockPosition::Bottom
831    }
832
833    fn set_position(
834        &mut self,
835        _position: DockPosition,
836        _window: &mut Window,
837        _cx: &mut Context<Self>,
838    ) {
839    }
840
841    fn size(&self, _window: &Window, _: &App) -> Pixels {
842        self.size
843    }
844
845    fn set_size(&mut self, size: Option<Pixels>, _window: &mut Window, _cx: &mut Context<Self>) {
846        self.size = size.unwrap();
847    }
848
849    fn remote_id() -> Option<proto::PanelId> {
850        Some(proto::PanelId::DebugPanel)
851    }
852
853    fn icon(&self, _window: &Window, _cx: &App) -> Option<IconName> {
854        Some(IconName::Debug)
855    }
856
857    fn icon_tooltip(&self, _window: &Window, cx: &App) -> Option<&'static str> {
858        if DebuggerSettings::get_global(cx).button {
859            Some("Debug Panel")
860        } else {
861            None
862        }
863    }
864
865    fn toggle_action(&self) -> Box<dyn Action> {
866        Box::new(ToggleFocus)
867    }
868
869    fn activation_priority(&self) -> u32 {
870        9
871    }
872    fn set_active(&mut self, _: bool, _: &mut Window, _: &mut Context<Self>) {}
873}
874
875impl Render for DebugPanel {
876    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
877        let has_sessions = self.sessions.len() > 0;
878        debug_assert_eq!(has_sessions, self.active_session.is_some());
879
880        v_flex()
881            .size_full()
882            .key_context("DebugPanel")
883            .child(h_flex().children(self.top_controls_strip(window, cx)))
884            .track_focus(&self.focus_handle(cx))
885            .map(|this| {
886                if has_sessions {
887                    this.children(self.active_session.clone())
888                } else {
889                    this.child(
890                        v_flex()
891                            .h_full()
892                            .gap_1()
893                            .items_center()
894                            .justify_center()
895                            .child(
896                                h_flex().child(
897                                    Label::new("No Debugging Sessions")
898                                        .size(LabelSize::Small)
899                                        .color(Color::Muted),
900                                ),
901                            )
902                            .child(
903                                h_flex().flex_shrink().child(
904                                    Button::new("spawn-new-session-empty-state", "New Session")
905                                        .size(ButtonSize::Large)
906                                        .on_click(|_, window, cx| {
907                                            window.dispatch_action(
908                                                CreateDebuggingSession.boxed_clone(),
909                                                cx,
910                                            );
911                                        }),
912                                ),
913                            ),
914                    )
915                }
916            })
917            .into_any()
918    }
919}