debugger_panel.rs

  1use crate::{
  2    ClearAllBreakpoints, Continue, CreateDebuggingSession, Disconnect, Pause, Restart, StepBack,
  3    StepInto, StepOut, StepOver, Stop, ToggleIgnoreBreakpoints, persistence,
  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 adapter_name = session.read(cx).adapter_name();
297
298                let session_id = *session_id;
299                cx.spawn_in(window, async move |this, cx| {
300                    let serialized_layout =
301                        persistence::get_serialized_pane_layout(adapter_name).await;
302
303                    this.update_in(cx, |this, window, cx| {
304                        let Some(project) = this.project.upgrade() else {
305                            return log::error!(
306                                "Debug Panel out lived it's weak reference to Project"
307                            );
308                        };
309
310                        if this
311                            .sessions
312                            .iter()
313                            .any(|item| item.read(cx).session_id(cx) == session_id)
314                        {
315                            // We already have an item for this session.
316                            return;
317                        }
318                        let session_item = DebugSession::running(
319                            project,
320                            this.workspace.clone(),
321                            session,
322                            cx.weak_entity(),
323                            serialized_layout,
324                            window,
325                            cx,
326                        );
327
328                        if let Some(running) = session_item.read(cx).mode().as_running().cloned() {
329                            // We might want to make this an event subscription and only notify when a new thread is selected
330                            // This is used to filter the command menu correctly
331                            cx.observe(&running, |_, _, cx| cx.notify()).detach();
332                        }
333
334                        this.sessions.push(session_item.clone());
335                        this.activate_session(session_item, window, cx);
336                    })
337                })
338                .detach();
339            }
340            dap_store::DapStoreEvent::RunInTerminal {
341                title,
342                cwd,
343                command,
344                args,
345                envs,
346                sender,
347                ..
348            } => {
349                self.handle_run_in_terminal_request(
350                    title.clone(),
351                    cwd.clone(),
352                    command.clone(),
353                    args.clone(),
354                    envs.clone(),
355                    sender.clone(),
356                    window,
357                    cx,
358                )
359                .detach_and_log_err(cx);
360            }
361            _ => {}
362        }
363    }
364
365    fn handle_run_in_terminal_request(
366        &self,
367        title: Option<String>,
368        cwd: Option<Arc<Path>>,
369        command: Option<String>,
370        args: Vec<String>,
371        envs: HashMap<String, String>,
372        mut sender: mpsc::Sender<Result<u32>>,
373        window: &mut Window,
374        cx: &mut App,
375    ) -> Task<Result<()>> {
376        let terminal_task = self.workspace.update(cx, |workspace, cx| {
377            let terminal_panel = workspace.panel::<TerminalPanel>(cx).ok_or_else(|| {
378                anyhow!("RunInTerminal DAP request failed because TerminalPanel wasn't found")
379            });
380
381            let terminal_panel = match terminal_panel {
382                Ok(panel) => panel,
383                Err(err) => return Task::ready(Err(err)),
384            };
385
386            terminal_panel.update(cx, |terminal_panel, cx| {
387                let terminal_task = terminal_panel.add_terminal(
388                    TerminalKind::Debug {
389                        command,
390                        args,
391                        envs,
392                        cwd,
393                        title,
394                    },
395                    task::RevealStrategy::Always,
396                    window,
397                    cx,
398                );
399
400                cx.spawn(async move |_, cx| {
401                    let pid_task = async move {
402                        let terminal = terminal_task.await?;
403
404                        terminal.read_with(cx, |terminal, _| terminal.pty_info.pid())
405                    };
406
407                    pid_task.await
408                })
409            })
410        });
411
412        cx.background_spawn(async move {
413            match terminal_task {
414                Ok(pid_task) => match pid_task.await {
415                    Ok(Some(pid)) => sender.send(Ok(pid.as_u32())).await?,
416                    Ok(None) => {
417                        sender
418                            .send(Err(anyhow!(
419                                "Terminal was spawned but PID was not available"
420                            )))
421                            .await?
422                    }
423                    Err(error) => sender.send(Err(anyhow!(error))).await?,
424                },
425                Err(error) => sender.send(Err(anyhow!(error))).await?,
426            };
427
428            Ok(())
429        })
430    }
431
432    fn close_session(&mut self, entity_id: EntityId, window: &mut Window, cx: &mut Context<Self>) {
433        let Some(session) = self
434            .sessions
435            .iter()
436            .find(|other| entity_id == other.entity_id())
437            .cloned()
438        else {
439            return;
440        };
441
442        let session_id = session.update(cx, |this, cx| this.session_id(cx));
443        let should_prompt = self
444            .project
445            .update(cx, |this, cx| {
446                let session = this.dap_store().read(cx).session_by_id(session_id);
447                session.map(|session| !session.read(cx).is_terminated())
448            })
449            .ok()
450            .flatten()
451            .unwrap_or_default();
452
453        cx.spawn_in(window, async move |this, cx| {
454            if should_prompt {
455                let response = cx.prompt(
456                    gpui::PromptLevel::Warning,
457                    "This Debug Session is still running. Are you sure you want to terminate it?",
458                    None,
459                    &["Yes", "No"],
460                );
461                if response.await == Ok(1) {
462                    return;
463                }
464            }
465            session.update(cx, |session, cx| session.shutdown(cx)).ok();
466            this.update(cx, |this, cx| {
467                this.sessions.retain(|other| entity_id != other.entity_id());
468
469                if let Some(active_session_id) = this
470                    .active_session
471                    .as_ref()
472                    .map(|session| session.entity_id())
473                {
474                    if active_session_id == entity_id {
475                        this.active_session = this.sessions.first().cloned();
476                    }
477                }
478                cx.notify()
479            })
480            .ok();
481        })
482        .detach();
483    }
484    fn sessions_drop_down_menu(
485        &self,
486        active_session: &Entity<DebugSession>,
487        window: &mut Window,
488        cx: &mut Context<Self>,
489    ) -> DropdownMenu {
490        let sessions = self.sessions.clone();
491        let weak = cx.weak_entity();
492        let label = active_session.read(cx).label_element(cx);
493
494        DropdownMenu::new_with_element(
495            "debugger-session-list",
496            label,
497            ContextMenu::build(window, cx, move |mut this, _, cx| {
498                let context_menu = cx.weak_entity();
499                for session in sessions.into_iter() {
500                    let weak_session = session.downgrade();
501                    let weak_session_id = weak_session.entity_id();
502
503                    this = this.custom_entry(
504                        {
505                            let weak = weak.clone();
506                            let context_menu = context_menu.clone();
507                            move |_, cx| {
508                                weak_session
509                                    .read_with(cx, |session, cx| {
510                                        let context_menu = context_menu.clone();
511                                        let id: SharedString =
512                                            format!("debug-session-{}", session.session_id(cx).0)
513                                                .into();
514                                        h_flex()
515                                            .w_full()
516                                            .group(id.clone())
517                                            .justify_between()
518                                            .child(session.label_element(cx))
519                                            .child(
520                                                IconButton::new(
521                                                    "close-debug-session",
522                                                    IconName::Close,
523                                                )
524                                                .visible_on_hover(id.clone())
525                                                .icon_size(IconSize::Small)
526                                                .on_click({
527                                                    let weak = weak.clone();
528                                                    move |_, window, cx| {
529                                                        weak.update(cx, |panel, cx| {
530                                                            panel.close_session(
531                                                                weak_session_id,
532                                                                window,
533                                                                cx,
534                                                            );
535                                                        })
536                                                        .ok();
537                                                        context_menu
538                                                            .update(cx, |this, cx| {
539                                                                this.cancel(
540                                                                    &Default::default(),
541                                                                    window,
542                                                                    cx,
543                                                                );
544                                                            })
545                                                            .ok();
546                                                    }
547                                                }),
548                                            )
549                                            .into_any_element()
550                                    })
551                                    .unwrap_or_else(|_| div().into_any_element())
552                            }
553                        },
554                        {
555                            let weak = weak.clone();
556                            move |window, cx| {
557                                weak.update(cx, |panel, cx| {
558                                    panel.activate_session(session.clone(), window, cx);
559                                })
560                                .ok();
561                            }
562                        },
563                    );
564                }
565                this
566            }),
567        )
568    }
569
570    fn top_controls_strip(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<Div> {
571        let active_session = self.active_session.clone();
572
573        Some(
574            h_flex()
575                .border_b_1()
576                .border_color(cx.theme().colors().border)
577                .p_1()
578                .justify_between()
579                .w_full()
580                .child(
581                    h_flex().gap_2().w_full().when_some(
582                        active_session
583                            .as_ref()
584                            .and_then(|session| session.read(cx).mode().as_running()),
585                        |this, running_session| {
586                            let thread_status = running_session
587                                .read(cx)
588                                .thread_status(cx)
589                                .unwrap_or(project::debugger::session::ThreadStatus::Exited);
590                            let capabilities = running_session.read(cx).capabilities(cx);
591                            this.map(|this| {
592                                if thread_status == ThreadStatus::Running {
593                                    this.child(
594                                        IconButton::new("debug-pause", IconName::DebugPause)
595                                            .icon_size(IconSize::XSmall)
596                                            .shape(ui::IconButtonShape::Square)
597                                            .on_click(window.listener_for(
598                                                &running_session,
599                                                |this, _, _window, cx| {
600                                                    this.pause_thread(cx);
601                                                },
602                                            ))
603                                            .tooltip(move |window, cx| {
604                                                Tooltip::text("Pause program")(window, cx)
605                                            }),
606                                    )
607                                } else {
608                                    this.child(
609                                        IconButton::new("debug-continue", IconName::DebugContinue)
610                                            .icon_size(IconSize::XSmall)
611                                            .shape(ui::IconButtonShape::Square)
612                                            .on_click(window.listener_for(
613                                                &running_session,
614                                                |this, _, _window, cx| this.continue_thread(cx),
615                                            ))
616                                            .disabled(thread_status != ThreadStatus::Stopped)
617                                            .tooltip(move |window, cx| {
618                                                Tooltip::text("Continue program")(window, cx)
619                                            }),
620                                    )
621                                }
622                            })
623                            .child(
624                                IconButton::new("debug-step-over", IconName::ArrowRight)
625                                    .icon_size(IconSize::XSmall)
626                                    .shape(ui::IconButtonShape::Square)
627                                    .on_click(window.listener_for(
628                                        &running_session,
629                                        |this, _, _window, cx| {
630                                            this.step_over(cx);
631                                        },
632                                    ))
633                                    .disabled(thread_status != ThreadStatus::Stopped)
634                                    .tooltip(move |window, cx| {
635                                        Tooltip::text("Step over")(window, cx)
636                                    }),
637                            )
638                            .child(
639                                IconButton::new("debug-step-out", IconName::ArrowUpRight)
640                                    .icon_size(IconSize::XSmall)
641                                    .shape(ui::IconButtonShape::Square)
642                                    .on_click(window.listener_for(
643                                        &running_session,
644                                        |this, _, _window, cx| {
645                                            this.step_out(cx);
646                                        },
647                                    ))
648                                    .disabled(thread_status != ThreadStatus::Stopped)
649                                    .tooltip(move |window, cx| {
650                                        Tooltip::text("Step out")(window, cx)
651                                    }),
652                            )
653                            .child(
654                                IconButton::new("debug-step-into", IconName::ArrowDownRight)
655                                    .icon_size(IconSize::XSmall)
656                                    .shape(ui::IconButtonShape::Square)
657                                    .on_click(window.listener_for(
658                                        &running_session,
659                                        |this, _, _window, cx| {
660                                            this.step_in(cx);
661                                        },
662                                    ))
663                                    .disabled(thread_status != ThreadStatus::Stopped)
664                                    .tooltip(move |window, cx| {
665                                        Tooltip::text("Step in")(window, cx)
666                                    }),
667                            )
668                            .child(Divider::vertical())
669                            .child(
670                                IconButton::new(
671                                    "debug-enable-breakpoint",
672                                    IconName::DebugDisabledBreakpoint,
673                                )
674                                .icon_size(IconSize::XSmall)
675                                .shape(ui::IconButtonShape::Square)
676                                .disabled(thread_status != ThreadStatus::Stopped),
677                            )
678                            .child(
679                                IconButton::new("debug-disable-breakpoint", IconName::CircleOff)
680                                    .icon_size(IconSize::XSmall)
681                                    .shape(ui::IconButtonShape::Square)
682                                    .disabled(thread_status != ThreadStatus::Stopped),
683                            )
684                            .child(
685                                IconButton::new("debug-disable-all-breakpoints", IconName::BugOff)
686                                    .icon_size(IconSize::XSmall)
687                                    .shape(ui::IconButtonShape::Square)
688                                    .disabled(
689                                        thread_status == ThreadStatus::Exited
690                                            || thread_status == ThreadStatus::Ended,
691                                    )
692                                    .on_click(window.listener_for(
693                                        &running_session,
694                                        |this, _, _window, cx| {
695                                            this.toggle_ignore_breakpoints(cx);
696                                        },
697                                    ))
698                                    .tooltip(move |window, cx| {
699                                        Tooltip::text("Disable all breakpoints")(window, cx)
700                                    }),
701                            )
702                            .child(Divider::vertical())
703                            .child(
704                                IconButton::new("debug-restart", IconName::DebugRestart)
705                                    .icon_size(IconSize::XSmall)
706                                    .on_click(window.listener_for(
707                                        &running_session,
708                                        |this, _, _window, cx| {
709                                            this.restart_session(cx);
710                                        },
711                                    ))
712                                    .disabled(
713                                        !capabilities.supports_restart_request.unwrap_or_default(),
714                                    )
715                                    .tooltip(move |window, cx| {
716                                        Tooltip::text("Restart")(window, cx)
717                                    }),
718                            )
719                            .child(
720                                IconButton::new("debug-stop", IconName::Power)
721                                    .icon_size(IconSize::XSmall)
722                                    .on_click(window.listener_for(
723                                        &running_session,
724                                        |this, _, _window, cx| {
725                                            this.stop_thread(cx);
726                                        },
727                                    ))
728                                    .disabled(
729                                        thread_status != ThreadStatus::Stopped
730                                            && thread_status != ThreadStatus::Running,
731                                    )
732                                    .tooltip({
733                                        let label = if capabilities
734                                            .supports_terminate_threads_request
735                                            .unwrap_or_default()
736                                        {
737                                            "Terminate Thread"
738                                        } else {
739                                            "Terminate all Threads"
740                                        };
741                                        move |window, cx| Tooltip::text(label)(window, cx)
742                                    }),
743                            )
744                        },
745                    ),
746                )
747                .child(
748                    h_flex()
749                        .gap_2()
750                        .when_some(
751                            active_session
752                                .as_ref()
753                                .and_then(|session| session.read(cx).mode().as_running())
754                                .cloned(),
755                            |this, session| {
756                                this.child(
757                                    session.update(cx, |this, cx| this.thread_dropdown(window, cx)),
758                                )
759                                .child(Divider::vertical())
760                            },
761                        )
762                        .when_some(active_session.as_ref(), |this, session| {
763                            let context_menu = self.sessions_drop_down_menu(session, window, cx);
764                            this.child(context_menu).child(Divider::vertical())
765                        })
766                        .child(
767                            IconButton::new("debug-new-session", IconName::Plus)
768                                .icon_size(IconSize::Small)
769                                .on_click({
770                                    let workspace = self.workspace.clone();
771                                    let weak_panel = cx.weak_entity();
772                                    let past_debug_definition = self.past_debug_definition.clone();
773                                    move |_, window, cx| {
774                                        let weak_panel = weak_panel.clone();
775                                        let past_debug_definition = past_debug_definition.clone();
776
777                                        let _ = workspace.update(cx, |this, cx| {
778                                            let workspace = cx.weak_entity();
779                                            this.toggle_modal(window, cx, |window, cx| {
780                                                NewSessionModal::new(
781                                                    past_debug_definition,
782                                                    weak_panel,
783                                                    workspace,
784                                                    window,
785                                                    cx,
786                                                )
787                                            });
788                                        });
789                                    }
790                                })
791                                .tooltip(|window, cx| {
792                                    Tooltip::for_action(
793                                        "New Debug Session",
794                                        &CreateDebuggingSession,
795                                        window,
796                                        cx,
797                                    )
798                                }),
799                        ),
800                ),
801        )
802    }
803
804    fn activate_session(
805        &mut self,
806        session_item: Entity<DebugSession>,
807        window: &mut Window,
808        cx: &mut Context<Self>,
809    ) {
810        debug_assert!(self.sessions.contains(&session_item));
811        session_item.focus_handle(cx).focus(window);
812        session_item.update(cx, |this, cx| {
813            if let Some(running) = this.mode().as_running() {
814                running.update(cx, |this, cx| {
815                    this.go_to_selected_stack_frame(window, cx);
816                });
817            }
818        });
819        self.active_session = Some(session_item);
820        cx.notify();
821    }
822}
823
824impl EventEmitter<PanelEvent> for DebugPanel {}
825impl EventEmitter<DebugPanelEvent> for DebugPanel {}
826impl EventEmitter<project::Event> for DebugPanel {}
827
828impl Focusable for DebugPanel {
829    fn focus_handle(&self, _: &App) -> FocusHandle {
830        self.focus_handle.clone()
831    }
832}
833
834impl Panel for DebugPanel {
835    fn persistent_name() -> &'static str {
836        "DebugPanel"
837    }
838
839    fn position(&self, _window: &Window, _cx: &App) -> DockPosition {
840        DockPosition::Bottom
841    }
842
843    fn position_is_valid(&self, position: DockPosition) -> bool {
844        position == DockPosition::Bottom
845    }
846
847    fn set_position(
848        &mut self,
849        _position: DockPosition,
850        _window: &mut Window,
851        _cx: &mut Context<Self>,
852    ) {
853    }
854
855    fn size(&self, _window: &Window, _: &App) -> Pixels {
856        self.size
857    }
858
859    fn set_size(&mut self, size: Option<Pixels>, _window: &mut Window, _cx: &mut Context<Self>) {
860        self.size = size.unwrap();
861    }
862
863    fn remote_id() -> Option<proto::PanelId> {
864        Some(proto::PanelId::DebugPanel)
865    }
866
867    fn icon(&self, _window: &Window, _cx: &App) -> Option<IconName> {
868        Some(IconName::Debug)
869    }
870
871    fn icon_tooltip(&self, _window: &Window, cx: &App) -> Option<&'static str> {
872        if DebuggerSettings::get_global(cx).button {
873            Some("Debug Panel")
874        } else {
875            None
876        }
877    }
878
879    fn toggle_action(&self) -> Box<dyn Action> {
880        Box::new(ToggleFocus)
881    }
882
883    fn activation_priority(&self) -> u32 {
884        9
885    }
886    fn set_active(&mut self, _: bool, _: &mut Window, _: &mut Context<Self>) {}
887}
888
889impl Render for DebugPanel {
890    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
891        let has_sessions = self.sessions.len() > 0;
892        debug_assert_eq!(has_sessions, self.active_session.is_some());
893
894        v_flex()
895            .size_full()
896            .key_context("DebugPanel")
897            .child(h_flex().children(self.top_controls_strip(window, cx)))
898            .track_focus(&self.focus_handle(cx))
899            .map(|this| {
900                if has_sessions {
901                    this.children(self.active_session.clone())
902                } else {
903                    this.child(
904                        v_flex()
905                            .h_full()
906                            .gap_1()
907                            .items_center()
908                            .justify_center()
909                            .child(
910                                h_flex().child(
911                                    Label::new("No Debugging Sessions")
912                                        .size(LabelSize::Small)
913                                        .color(Color::Muted),
914                                ),
915                            )
916                            .child(
917                                h_flex().flex_shrink().child(
918                                    Button::new("spawn-new-session-empty-state", "New Session")
919                                        .size(ButtonSize::Large)
920                                        .on_click(|_, window, cx| {
921                                            window.dispatch_action(
922                                                CreateDebuggingSession.boxed_clone(),
923                                                cx,
924                                            );
925                                        }),
926                                ),
927                            ),
928                    )
929                }
930            })
931            .into_any()
932    }
933}