1use std::path::Path;
2use std::sync::Arc;
3use std::time::Duration;
4
5use anyhow::{Context as _, Result, anyhow};
6use dap::StackFrameId;
7use gpui::{
8 AnyElement, Entity, EventEmitter, FocusHandle, Focusable, ListState, MouseButton, Stateful,
9 Subscription, Task, WeakEntity, list,
10};
11
12use crate::StackTraceView;
13use language::PointUtf16;
14use project::debugger::breakpoint_store::ActiveStackFrame;
15use project::debugger::session::{Session, SessionEvent, StackFrame};
16use project::{ProjectItem, ProjectPath};
17use ui::{Scrollbar, ScrollbarState, Tooltip, prelude::*};
18use workspace::{ItemHandle, Workspace};
19
20use super::RunningState;
21
22#[derive(Debug)]
23pub enum StackFrameListEvent {
24 SelectedStackFrameChanged(StackFrameId),
25 BuiltEntries,
26}
27
28pub struct StackFrameList {
29 focus_handle: FocusHandle,
30 _subscription: Subscription,
31 session: Entity<Session>,
32 state: WeakEntity<RunningState>,
33 entries: Vec<StackFrameEntry>,
34 workspace: WeakEntity<Workspace>,
35 selected_ix: Option<usize>,
36 opened_stack_frame_id: Option<StackFrameId>,
37 scrollbar_state: ScrollbarState,
38 list_state: ListState,
39 _refresh_task: Task<()>,
40}
41
42#[derive(Debug, PartialEq, Eq)]
43pub enum StackFrameEntry {
44 Normal(dap::StackFrame),
45 Collapsed(Vec<dap::StackFrame>),
46}
47
48impl StackFrameList {
49 pub fn new(
50 workspace: WeakEntity<Workspace>,
51 session: Entity<Session>,
52 state: WeakEntity<RunningState>,
53 window: &mut Window,
54 cx: &mut Context<Self>,
55 ) -> Self {
56 let focus_handle = cx.focus_handle();
57
58 let _subscription =
59 cx.subscribe_in(&session, window, |this, _, event, window, cx| match event {
60 SessionEvent::Threads => {
61 this.schedule_refresh(false, window, cx);
62 }
63 SessionEvent::Stopped(..) | SessionEvent::StackTrace => {
64 this.schedule_refresh(true, window, cx);
65 }
66 _ => {}
67 });
68
69 let list_state = ListState::new(0, gpui::ListAlignment::Top, px(1000.), {
70 let this = cx.weak_entity();
71 move |ix, _window, cx| {
72 this.update(cx, |this, cx| this.render_entry(ix, cx))
73 .unwrap_or(div().into_any())
74 }
75 });
76 let scrollbar_state = ScrollbarState::new(list_state.clone());
77
78 let mut this = Self {
79 session,
80 workspace,
81 focus_handle,
82 state,
83 _subscription,
84 entries: Default::default(),
85 selected_ix: None,
86 opened_stack_frame_id: None,
87 list_state,
88 scrollbar_state,
89 _refresh_task: Task::ready(()),
90 };
91 this.schedule_refresh(true, window, cx);
92 this
93 }
94
95 #[cfg(test)]
96 pub(crate) fn entries(&self) -> &Vec<StackFrameEntry> {
97 &self.entries
98 }
99
100 pub(crate) fn flatten_entries(&self, show_collapsed: bool) -> Vec<dap::StackFrame> {
101 self.entries
102 .iter()
103 .flat_map(|frame| match frame {
104 StackFrameEntry::Normal(frame) => vec![frame.clone()],
105 StackFrameEntry::Collapsed(frames) => {
106 if show_collapsed {
107 frames.clone()
108 } else {
109 vec![]
110 }
111 }
112 })
113 .collect::<Vec<_>>()
114 }
115
116 fn stack_frames(&self, cx: &mut App) -> Vec<StackFrame> {
117 self.state
118 .read_with(cx, |state, _| state.thread_id)
119 .ok()
120 .flatten()
121 .map(|thread_id| {
122 self.session
123 .update(cx, |this, cx| this.stack_frames(thread_id, cx))
124 })
125 .unwrap_or_default()
126 }
127
128 #[cfg(test)]
129 pub(crate) fn dap_stack_frames(&self, cx: &mut App) -> Vec<dap::StackFrame> {
130 self.stack_frames(cx)
131 .into_iter()
132 .map(|stack_frame| stack_frame.dap.clone())
133 .collect()
134 }
135
136 pub fn opened_stack_frame_id(&self) -> Option<StackFrameId> {
137 self.opened_stack_frame_id
138 }
139
140 pub(super) fn schedule_refresh(
141 &mut self,
142 select_first: bool,
143 window: &mut Window,
144 cx: &mut Context<Self>,
145 ) {
146 const REFRESH_DEBOUNCE: Duration = Duration::from_millis(20);
147
148 self._refresh_task = cx.spawn_in(window, async move |this, cx| {
149 let debounce = this
150 .update(cx, |this, cx| {
151 let new_stack_frames = this.stack_frames(cx);
152 new_stack_frames.is_empty() && !this.entries.is_empty()
153 })
154 .ok()
155 .unwrap_or_default();
156
157 if debounce {
158 cx.background_executor().timer(REFRESH_DEBOUNCE).await;
159 }
160 this.update_in(cx, |this, window, cx| {
161 this.build_entries(select_first, window, cx);
162 cx.notify();
163 })
164 .ok();
165 })
166 }
167
168 pub fn build_entries(
169 &mut self,
170 open_first_stack_frame: bool,
171 window: &mut Window,
172 cx: &mut Context<Self>,
173 ) {
174 let old_selected_frame_id = self
175 .selected_ix
176 .and_then(|ix| self.entries.get(ix))
177 .and_then(|entry| match entry {
178 StackFrameEntry::Normal(stack_frame) => Some(stack_frame.id),
179 StackFrameEntry::Collapsed(stack_frames) => {
180 stack_frames.first().map(|stack_frame| stack_frame.id)
181 }
182 });
183 let mut entries = Vec::new();
184 let mut collapsed_entries = Vec::new();
185 let mut first_stack_frame = None;
186
187 let stack_frames = self.stack_frames(cx);
188 for stack_frame in &stack_frames {
189 match stack_frame.dap.presentation_hint {
190 Some(dap::StackFramePresentationHint::Deemphasize) => {
191 collapsed_entries.push(stack_frame.dap.clone());
192 }
193 _ => {
194 let collapsed_entries = std::mem::take(&mut collapsed_entries);
195 if !collapsed_entries.is_empty() {
196 entries.push(StackFrameEntry::Collapsed(collapsed_entries.clone()));
197 }
198
199 first_stack_frame.get_or_insert(entries.len());
200 entries.push(StackFrameEntry::Normal(stack_frame.dap.clone()));
201 }
202 }
203 }
204
205 let collapsed_entries = std::mem::take(&mut collapsed_entries);
206 if !collapsed_entries.is_empty() {
207 entries.push(StackFrameEntry::Collapsed(collapsed_entries.clone()));
208 }
209
210 std::mem::swap(&mut self.entries, &mut entries);
211
212 if let Some(ix) = first_stack_frame.filter(|_| open_first_stack_frame) {
213 self.select_ix(Some(ix), cx);
214 self.activate_selected_entry(window, cx);
215 } else if let Some(old_selected_frame_id) = old_selected_frame_id {
216 let ix = self.entries.iter().position(|entry| match entry {
217 StackFrameEntry::Normal(frame) => frame.id == old_selected_frame_id,
218 StackFrameEntry::Collapsed(frames) => {
219 frames.iter().any(|frame| frame.id == old_selected_frame_id)
220 }
221 });
222 self.selected_ix = ix;
223 }
224
225 self.list_state.reset(self.entries.len());
226 cx.emit(StackFrameListEvent::BuiltEntries);
227 cx.notify();
228 }
229
230 pub fn go_to_stack_frame(
231 &mut self,
232 stack_frame_id: StackFrameId,
233 window: &mut Window,
234 cx: &mut Context<Self>,
235 ) -> Task<Result<()>> {
236 let Some(stack_frame) = self
237 .entries
238 .iter()
239 .flat_map(|entry| match entry {
240 StackFrameEntry::Normal(stack_frame) => std::slice::from_ref(stack_frame),
241 StackFrameEntry::Collapsed(stack_frames) => stack_frames.as_slice(),
242 })
243 .find(|stack_frame| stack_frame.id == stack_frame_id)
244 .cloned()
245 else {
246 return Task::ready(Err(anyhow!("No stack frame for ID")));
247 };
248 self.go_to_stack_frame_inner(stack_frame, window, cx)
249 }
250
251 fn go_to_stack_frame_inner(
252 &mut self,
253 stack_frame: dap::StackFrame,
254 window: &mut Window,
255 cx: &mut Context<Self>,
256 ) -> Task<Result<()>> {
257 let stack_frame_id = stack_frame.id;
258 self.opened_stack_frame_id = Some(stack_frame_id);
259 let Some(abs_path) = Self::abs_path_from_stack_frame(&stack_frame) else {
260 return Task::ready(Err(anyhow!("Project path not found")));
261 };
262 let row = stack_frame.line.saturating_sub(1) as u32;
263 cx.emit(StackFrameListEvent::SelectedStackFrameChanged(
264 stack_frame_id,
265 ));
266 cx.spawn_in(window, async move |this, cx| {
267 let (worktree, relative_path) = this
268 .update(cx, |this, cx| {
269 this.workspace.update(cx, |workspace, cx| {
270 workspace.project().update(cx, |this, cx| {
271 this.find_or_create_worktree(&abs_path, false, cx)
272 })
273 })
274 })??
275 .await?;
276 let buffer = this
277 .update(cx, |this, cx| {
278 this.workspace.update(cx, |this, cx| {
279 this.project().update(cx, |this, cx| {
280 let worktree_id = worktree.read(cx).id();
281 this.open_buffer(
282 ProjectPath {
283 worktree_id,
284 path: relative_path.into(),
285 },
286 cx,
287 )
288 })
289 })
290 })??
291 .await?;
292 let position = buffer.read_with(cx, |this, _| {
293 this.snapshot().anchor_after(PointUtf16::new(row, 0))
294 })?;
295 this.update_in(cx, |this, window, cx| {
296 this.workspace.update(cx, |workspace, cx| {
297 let project_path = buffer
298 .read(cx)
299 .project_path(cx)
300 .context("Could not select a stack frame for unnamed buffer")?;
301
302 let open_preview = !workspace
303 .item_of_type::<StackTraceView>(cx)
304 .map(|viewer| {
305 workspace
306 .active_item(cx)
307 .is_some_and(|item| item.item_id() == viewer.item_id())
308 })
309 .unwrap_or_default();
310
311 anyhow::Ok(workspace.open_path_preview(
312 project_path,
313 None,
314 true,
315 true,
316 open_preview,
317 window,
318 cx,
319 ))
320 })
321 })???
322 .await?;
323
324 this.update(cx, |this, cx| {
325 let thread_id = this.state.read_with(cx, |state, _| {
326 state.thread_id.context("No selected thread ID found")
327 })??;
328
329 this.workspace.update(cx, |workspace, cx| {
330 let breakpoint_store = workspace.project().read(cx).breakpoint_store();
331
332 breakpoint_store.update(cx, |store, cx| {
333 store.set_active_position(
334 ActiveStackFrame {
335 session_id: this.session.read(cx).session_id(),
336 thread_id,
337 stack_frame_id,
338 path: abs_path,
339 position,
340 },
341 cx,
342 );
343 })
344 })
345 })?
346 })
347 }
348
349 pub(crate) fn abs_path_from_stack_frame(stack_frame: &dap::StackFrame) -> Option<Arc<Path>> {
350 stack_frame.source.as_ref().and_then(|s| {
351 s.path
352 .as_deref()
353 .map(|path| Arc::<Path>::from(Path::new(path)))
354 .filter(|path| path.is_absolute())
355 })
356 }
357
358 pub fn restart_stack_frame(&mut self, stack_frame_id: u64, cx: &mut Context<Self>) {
359 self.session.update(cx, |state, cx| {
360 state.restart_stack_frame(stack_frame_id, cx)
361 });
362 }
363
364 fn render_normal_entry(
365 &self,
366 ix: usize,
367 stack_frame: &dap::StackFrame,
368 cx: &mut Context<Self>,
369 ) -> AnyElement {
370 let source = stack_frame.source.clone();
371 let is_selected_frame = Some(ix) == self.selected_ix;
372
373 let path = source.clone().and_then(|s| s.path.or(s.name));
374 let formatted_path = path.map(|path| format!("{}:{}", path, stack_frame.line,));
375 let formatted_path = formatted_path.map(|path| {
376 Label::new(path)
377 .size(LabelSize::XSmall)
378 .line_height_style(LineHeightStyle::UiLabel)
379 .truncate()
380 .color(Color::Muted)
381 });
382
383 let supports_frame_restart = self
384 .session
385 .read(cx)
386 .capabilities()
387 .supports_restart_frame
388 .unwrap_or_default();
389
390 let should_deemphasize = matches!(
391 stack_frame.presentation_hint,
392 Some(
393 dap::StackFramePresentationHint::Subtle
394 | dap::StackFramePresentationHint::Deemphasize
395 )
396 );
397 h_flex()
398 .rounded_md()
399 .justify_between()
400 .w_full()
401 .group("")
402 .id(("stack-frame", stack_frame.id))
403 .p_1()
404 .when(is_selected_frame, |this| {
405 this.bg(cx.theme().colors().element_hover)
406 })
407 .on_any_mouse_down(|_, _, cx| {
408 cx.stop_propagation();
409 })
410 .on_click(cx.listener(move |this, _, window, cx| {
411 this.selected_ix = Some(ix);
412 this.activate_selected_entry(window, cx);
413 }))
414 .hover(|style| style.bg(cx.theme().colors().element_hover).cursor_pointer())
415 .child(
416 v_flex()
417 .gap_0p5()
418 .child(
419 Label::new(stack_frame.name.clone())
420 .size(LabelSize::Small)
421 .truncate()
422 .when(should_deemphasize, |this| this.color(Color::Muted)),
423 )
424 .children(formatted_path),
425 )
426 .when(
427 supports_frame_restart && stack_frame.can_restart.unwrap_or(true),
428 |this| {
429 this.child(
430 h_flex()
431 .id(("restart-stack-frame", stack_frame.id))
432 .visible_on_hover("")
433 .absolute()
434 .right_2()
435 .overflow_hidden()
436 .rounded_md()
437 .border_1()
438 .border_color(cx.theme().colors().element_selected)
439 .bg(cx.theme().colors().element_background)
440 .hover(|style| {
441 style
442 .bg(cx.theme().colors().ghost_element_hover)
443 .cursor_pointer()
444 })
445 .child(
446 IconButton::new(
447 ("restart-stack-frame", stack_frame.id),
448 IconName::DebugRestart,
449 )
450 .icon_size(IconSize::Small)
451 .on_click(cx.listener({
452 let stack_frame_id = stack_frame.id;
453 move |this, _, _window, cx| {
454 this.restart_stack_frame(stack_frame_id, cx);
455 }
456 }))
457 .tooltip(move |window, cx| {
458 Tooltip::text("Restart Stack Frame")(window, cx)
459 }),
460 ),
461 )
462 },
463 )
464 .into_any()
465 }
466
467 pub(crate) fn expand_collapsed_entry(&mut self, ix: usize) {
468 let Some(StackFrameEntry::Collapsed(stack_frames)) = self.entries.get_mut(ix) else {
469 return;
470 };
471 let entries = std::mem::take(stack_frames)
472 .into_iter()
473 .map(StackFrameEntry::Normal);
474 self.entries.splice(ix..ix + 1, entries);
475 self.selected_ix = Some(ix);
476 }
477
478 fn render_collapsed_entry(
479 &self,
480 ix: usize,
481 stack_frames: &Vec<dap::StackFrame>,
482 cx: &mut Context<Self>,
483 ) -> AnyElement {
484 let first_stack_frame = &stack_frames[0];
485 let is_selected = Some(ix) == self.selected_ix;
486
487 h_flex()
488 .rounded_md()
489 .justify_between()
490 .w_full()
491 .group("")
492 .id(("stack-frame", first_stack_frame.id))
493 .p_1()
494 .when(is_selected, |this| {
495 this.bg(cx.theme().colors().element_hover)
496 })
497 .on_any_mouse_down(|_, _, cx| {
498 cx.stop_propagation();
499 })
500 .on_click(cx.listener(move |this, _, window, cx| {
501 this.selected_ix = Some(ix);
502 this.activate_selected_entry(window, cx);
503 }))
504 .hover(|style| style.bg(cx.theme().colors().element_hover).cursor_pointer())
505 .child(
506 v_flex()
507 .text_ui_sm(cx)
508 .truncate()
509 .text_color(cx.theme().colors().text_muted)
510 .child(format!(
511 "Show {} more{}",
512 stack_frames.len(),
513 first_stack_frame
514 .source
515 .as_ref()
516 .and_then(|source| source.origin.as_ref())
517 .map_or(String::new(), |origin| format!(": {}", origin))
518 )),
519 )
520 .into_any()
521 }
522
523 fn render_entry(&self, ix: usize, cx: &mut Context<Self>) -> AnyElement {
524 match &self.entries[ix] {
525 StackFrameEntry::Normal(stack_frame) => self.render_normal_entry(ix, stack_frame, cx),
526 StackFrameEntry::Collapsed(stack_frames) => {
527 self.render_collapsed_entry(ix, stack_frames, cx)
528 }
529 }
530 }
531
532 fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Stateful<Div> {
533 div()
534 .occlude()
535 .id("stack-frame-list-vertical-scrollbar")
536 .on_mouse_move(cx.listener(|_, _, _, cx| {
537 cx.notify();
538 cx.stop_propagation()
539 }))
540 .on_hover(|_, _, cx| {
541 cx.stop_propagation();
542 })
543 .on_any_mouse_down(|_, _, cx| {
544 cx.stop_propagation();
545 })
546 .on_mouse_up(
547 MouseButton::Left,
548 cx.listener(|_, _, _, cx| {
549 cx.stop_propagation();
550 }),
551 )
552 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
553 cx.notify();
554 }))
555 .h_full()
556 .absolute()
557 .right_1()
558 .top_1()
559 .bottom_0()
560 .w(px(12.))
561 .cursor_default()
562 .children(Scrollbar::vertical(self.scrollbar_state.clone()))
563 }
564
565 fn select_ix(&mut self, ix: Option<usize>, cx: &mut Context<Self>) {
566 self.selected_ix = ix;
567 cx.notify();
568 }
569
570 fn select_next(&mut self, _: &menu::SelectNext, _window: &mut Window, cx: &mut Context<Self>) {
571 let ix = match self.selected_ix {
572 _ if self.entries.len() == 0 => None,
573 None => Some(0),
574 Some(ix) => {
575 if ix == self.entries.len() - 1 {
576 Some(0)
577 } else {
578 Some(ix + 1)
579 }
580 }
581 };
582 self.select_ix(ix, cx);
583 }
584
585 fn select_previous(
586 &mut self,
587 _: &menu::SelectPrevious,
588 _window: &mut Window,
589 cx: &mut Context<Self>,
590 ) {
591 let ix = match self.selected_ix {
592 _ if self.entries.len() == 0 => None,
593 None => Some(self.entries.len() - 1),
594 Some(ix) => {
595 if ix == 0 {
596 Some(self.entries.len() - 1)
597 } else {
598 Some(ix - 1)
599 }
600 }
601 };
602 self.select_ix(ix, cx);
603 }
604
605 fn select_first(
606 &mut self,
607 _: &menu::SelectFirst,
608 _window: &mut Window,
609 cx: &mut Context<Self>,
610 ) {
611 let ix = if self.entries.len() > 0 {
612 Some(0)
613 } else {
614 None
615 };
616 self.select_ix(ix, cx);
617 }
618
619 fn select_last(&mut self, _: &menu::SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
620 let ix = if self.entries.len() > 0 {
621 Some(self.entries.len() - 1)
622 } else {
623 None
624 };
625 self.select_ix(ix, cx);
626 }
627
628 fn activate_selected_entry(&mut self, window: &mut Window, cx: &mut Context<Self>) {
629 let Some(ix) = self.selected_ix else {
630 return;
631 };
632 let Some(entry) = self.entries.get_mut(ix) else {
633 return;
634 };
635 match entry {
636 StackFrameEntry::Normal(stack_frame) => {
637 let stack_frame = stack_frame.clone();
638 self.go_to_stack_frame_inner(stack_frame, window, cx)
639 .detach_and_log_err(cx)
640 }
641 StackFrameEntry::Collapsed(_) => self.expand_collapsed_entry(ix),
642 }
643 cx.notify();
644 }
645
646 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
647 self.activate_selected_entry(window, cx);
648 }
649
650 fn render_list(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
651 list(self.list_state.clone()).size_full()
652 }
653}
654
655impl Render for StackFrameList {
656 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
657 div()
658 .track_focus(&self.focus_handle)
659 .size_full()
660 .p_1()
661 .on_action(cx.listener(Self::select_next))
662 .on_action(cx.listener(Self::select_previous))
663 .on_action(cx.listener(Self::select_first))
664 .on_action(cx.listener(Self::select_last))
665 .on_action(cx.listener(Self::confirm))
666 .child(self.render_list(window, cx))
667 .child(self.render_vertical_scrollbar(cx))
668 }
669}
670
671impl Focusable for StackFrameList {
672 fn focus_handle(&self, _: &gpui::App) -> gpui::FocusHandle {
673 self.focus_handle.clone()
674 }
675}
676
677impl EventEmitter<StackFrameListEvent> for StackFrameList {}