1use std::path::Path;
2use std::sync::Arc;
3use std::time::Duration;
4
5use anyhow::{Context as _, Result, anyhow};
6use dap::StackFrameId;
7use db::kvp::KEY_VALUE_STORE;
8use gpui::{
9 Action, AnyElement, Entity, EventEmitter, FocusHandle, Focusable, FontWeight, ListState,
10 Subscription, Task, WeakEntity, list,
11};
12use util::{
13 debug_panic,
14 paths::{PathStyle, is_absolute},
15};
16
17use crate::{StackTraceView, ToggleUserFrames};
18use language::PointUtf16;
19use project::debugger::breakpoint_store::ActiveStackFrame;
20use project::debugger::session::{Session, SessionEvent, StackFrame, ThreadStatus};
21use project::{ProjectItem, ProjectPath};
22use ui::{Tooltip, WithScrollbar, prelude::*};
23use workspace::{ItemHandle, Workspace};
24
25use super::RunningState;
26
27#[derive(Debug)]
28pub enum StackFrameListEvent {
29 SelectedStackFrameChanged(StackFrameId),
30 BuiltEntries,
31}
32
33/// Represents the filter applied to the stack frame list
34#[derive(PartialEq, Eq, Copy, Clone, Debug)]
35pub(crate) enum StackFrameFilter {
36 /// Show all frames
37 All,
38 /// Show only frames from the user's code
39 OnlyUserFrames,
40}
41
42impl StackFrameFilter {
43 fn from_str_or_default(s: impl AsRef<str>) -> Self {
44 match s.as_ref() {
45 "user" => StackFrameFilter::OnlyUserFrames,
46 "all" => StackFrameFilter::All,
47 _ => StackFrameFilter::All,
48 }
49 }
50}
51
52impl From<StackFrameFilter> for String {
53 fn from(filter: StackFrameFilter) -> Self {
54 match filter {
55 StackFrameFilter::All => "all".to_string(),
56 StackFrameFilter::OnlyUserFrames => "user".to_string(),
57 }
58 }
59}
60
61pub struct StackFrameList {
62 focus_handle: FocusHandle,
63 _subscription: Subscription,
64 session: Entity<Session>,
65 state: WeakEntity<RunningState>,
66 entries: Vec<StackFrameEntry>,
67 workspace: WeakEntity<Workspace>,
68 selected_ix: Option<usize>,
69 opened_stack_frame_id: Option<StackFrameId>,
70 list_state: ListState,
71 list_filter: StackFrameFilter,
72 filter_entries_indices: Vec<usize>,
73 error: Option<SharedString>,
74 _refresh_task: Task<()>,
75}
76
77#[derive(Debug, PartialEq, Eq)]
78pub enum StackFrameEntry {
79 Normal(dap::StackFrame),
80 /// Used to indicate that the frame is artificial and is a visual label or separator
81 Label(dap::StackFrame),
82 Collapsed(Vec<dap::StackFrame>),
83}
84
85impl StackFrameList {
86 pub fn new(
87 workspace: WeakEntity<Workspace>,
88 session: Entity<Session>,
89 state: WeakEntity<RunningState>,
90 window: &mut Window,
91 cx: &mut Context<Self>,
92 ) -> Self {
93 let focus_handle = cx.focus_handle();
94
95 let _subscription =
96 cx.subscribe_in(&session, window, |this, _, event, window, cx| match event {
97 SessionEvent::Threads => {
98 this.schedule_refresh(false, window, cx);
99 }
100 SessionEvent::Stopped(..) | SessionEvent::StackTrace => {
101 this.schedule_refresh(true, window, cx);
102 }
103 _ => {}
104 });
105
106 let list_state = ListState::new(0, gpui::ListAlignment::Top, px(1000.));
107
108 let list_filter = KEY_VALUE_STORE
109 .read_kvp(&format!(
110 "stack-frame-list-filter-{}",
111 session.read(cx).adapter().0
112 ))
113 .ok()
114 .flatten()
115 .map(StackFrameFilter::from_str_or_default)
116 .unwrap_or(StackFrameFilter::All);
117
118 let mut this = Self {
119 session,
120 workspace,
121 focus_handle,
122 state,
123 _subscription,
124 entries: Default::default(),
125 filter_entries_indices: Vec::default(),
126 error: None,
127 selected_ix: None,
128 opened_stack_frame_id: None,
129 list_filter,
130 list_state,
131 _refresh_task: Task::ready(()),
132 };
133 this.schedule_refresh(true, window, cx);
134 this
135 }
136
137 #[cfg(test)]
138 pub(crate) fn entries(&self) -> &Vec<StackFrameEntry> {
139 &self.entries
140 }
141
142 pub(crate) fn flatten_entries(
143 &self,
144 show_collapsed: bool,
145 show_labels: bool,
146 ) -> Vec<dap::StackFrame> {
147 self.entries
148 .iter()
149 .enumerate()
150 .filter(|(ix, _)| {
151 self.list_filter == StackFrameFilter::All
152 || self
153 .filter_entries_indices
154 .binary_search_by_key(&ix, |ix| ix)
155 .is_ok()
156 })
157 .flat_map(|(_, frame)| match frame {
158 StackFrameEntry::Normal(frame) => vec![frame.clone()],
159 StackFrameEntry::Label(frame) if show_labels => vec![frame.clone()],
160 StackFrameEntry::Collapsed(frames) if show_collapsed => frames.clone(),
161 _ => vec![],
162 })
163 .collect::<Vec<_>>()
164 }
165
166 fn stack_frames(&self, cx: &mut App) -> Result<Vec<StackFrame>> {
167 if let Ok(Some(thread_id)) = self.state.read_with(cx, |state, _| state.thread_id) {
168 self.session
169 .update(cx, |this, cx| this.stack_frames(thread_id, cx))
170 } else {
171 Ok(Vec::default())
172 }
173 }
174
175 #[cfg(test)]
176 pub(crate) fn dap_stack_frames(&self, cx: &mut App) -> Vec<dap::StackFrame> {
177 match self.list_filter {
178 StackFrameFilter::All => self
179 .stack_frames(cx)
180 .unwrap_or_default()
181 .into_iter()
182 .map(|stack_frame| stack_frame.dap)
183 .collect(),
184 StackFrameFilter::OnlyUserFrames => self
185 .filter_entries_indices
186 .iter()
187 .map(|ix| match &self.entries[*ix] {
188 StackFrameEntry::Label(label) => label,
189 StackFrameEntry::Collapsed(_) => panic!("Collapsed tabs should not be visible"),
190 StackFrameEntry::Normal(frame) => frame,
191 })
192 .cloned()
193 .collect(),
194 }
195 }
196
197 #[cfg(test)]
198 pub(crate) fn list_filter(&self) -> StackFrameFilter {
199 self.list_filter
200 }
201
202 pub fn opened_stack_frame_id(&self) -> Option<StackFrameId> {
203 self.opened_stack_frame_id
204 }
205
206 pub(super) fn schedule_refresh(
207 &mut self,
208 select_first: bool,
209 window: &mut Window,
210 cx: &mut Context<Self>,
211 ) {
212 const REFRESH_DEBOUNCE: Duration = Duration::from_millis(20);
213
214 self._refresh_task = cx.spawn_in(window, async move |this, cx| {
215 let debounce = this
216 .update(cx, |this, cx| {
217 let new_stack_frames = this.stack_frames(cx);
218 new_stack_frames.unwrap_or_default().is_empty() && !this.entries.is_empty()
219 })
220 .ok()
221 .unwrap_or_default();
222
223 if debounce {
224 cx.background_executor().timer(REFRESH_DEBOUNCE).await;
225 }
226 this.update_in(cx, |this, window, cx| {
227 this.build_entries(select_first, window, cx);
228 cx.notify();
229 })
230 .ok();
231 })
232 }
233
234 pub fn build_entries(
235 &mut self,
236 open_first_stack_frame: bool,
237 window: &mut Window,
238 cx: &mut Context<Self>,
239 ) {
240 let old_selected_frame_id = self
241 .selected_ix
242 .and_then(|ix| self.entries.get(ix))
243 .and_then(|entry| match entry {
244 StackFrameEntry::Normal(stack_frame) => Some(stack_frame.id),
245 StackFrameEntry::Collapsed(_) | StackFrameEntry::Label(_) => None,
246 });
247 let mut entries = Vec::new();
248 let mut collapsed_entries = Vec::new();
249 let mut first_stack_frame = None;
250 let mut first_stack_frame_with_path = None;
251
252 let stack_frames = match self.stack_frames(cx) {
253 Ok(stack_frames) => stack_frames,
254 Err(e) => {
255 self.error = Some(format!("{}", e).into());
256 self.entries.clear();
257 self.selected_ix = None;
258 self.list_state.reset(0);
259 self.filter_entries_indices.clear();
260 cx.emit(StackFrameListEvent::BuiltEntries);
261 cx.notify();
262 return;
263 }
264 };
265
266 let worktree_prefixes: Vec<_> = self
267 .workspace
268 .read_with(cx, |workspace, cx| {
269 workspace
270 .visible_worktrees(cx)
271 .map(|tree| tree.read(cx).abs_path())
272 .collect()
273 })
274 .unwrap_or_default();
275
276 let mut filter_entries_indices = Vec::default();
277 for stack_frame in stack_frames.iter() {
278 let frame_in_visible_worktree = stack_frame.dap.source.as_ref().is_some_and(|source| {
279 source.path.as_ref().is_some_and(|path| {
280 worktree_prefixes
281 .iter()
282 .filter_map(|tree| tree.to_str())
283 .any(|tree| path.starts_with(tree))
284 })
285 });
286
287 match stack_frame.dap.presentation_hint {
288 Some(dap::StackFramePresentationHint::Deemphasize)
289 | Some(dap::StackFramePresentationHint::Subtle) => {
290 collapsed_entries.push(stack_frame.dap.clone());
291 }
292 Some(dap::StackFramePresentationHint::Label) => {
293 entries.push(StackFrameEntry::Label(stack_frame.dap.clone()));
294 }
295 _ => {
296 let collapsed_entries = std::mem::take(&mut collapsed_entries);
297 if !collapsed_entries.is_empty() {
298 entries.push(StackFrameEntry::Collapsed(collapsed_entries.clone()));
299 }
300
301 first_stack_frame.get_or_insert(entries.len());
302
303 if stack_frame
304 .dap
305 .source
306 .as_ref()
307 .is_some_and(|source| source.path.is_some())
308 {
309 first_stack_frame_with_path.get_or_insert(entries.len());
310 }
311 entries.push(StackFrameEntry::Normal(stack_frame.dap.clone()));
312 if frame_in_visible_worktree {
313 filter_entries_indices.push(entries.len() - 1);
314 }
315 }
316 }
317 }
318
319 let collapsed_entries = std::mem::take(&mut collapsed_entries);
320 if !collapsed_entries.is_empty() {
321 entries.push(StackFrameEntry::Collapsed(collapsed_entries));
322 }
323 self.entries = entries;
324 self.filter_entries_indices = filter_entries_indices;
325
326 if let Some(ix) = first_stack_frame_with_path
327 .or(first_stack_frame)
328 .filter(|_| open_first_stack_frame)
329 {
330 self.select_ix(Some(ix), cx);
331 self.activate_selected_entry(window, cx);
332 } else if let Some(old_selected_frame_id) = old_selected_frame_id {
333 let ix = self.entries.iter().position(|entry| match entry {
334 StackFrameEntry::Normal(frame) => frame.id == old_selected_frame_id,
335 StackFrameEntry::Collapsed(_) | StackFrameEntry::Label(_) => false,
336 });
337 self.selected_ix = ix;
338 }
339
340 match self.list_filter {
341 StackFrameFilter::All => {
342 self.list_state.reset(self.entries.len());
343 }
344 StackFrameFilter::OnlyUserFrames => {
345 self.list_state.reset(self.filter_entries_indices.len());
346 }
347 }
348 cx.emit(StackFrameListEvent::BuiltEntries);
349 cx.notify();
350 }
351
352 pub fn go_to_stack_frame(
353 &mut self,
354 stack_frame_id: StackFrameId,
355 window: &mut Window,
356 cx: &mut Context<Self>,
357 ) -> Task<Result<()>> {
358 let Some(stack_frame) = self
359 .entries
360 .iter()
361 .flat_map(|entry| match entry {
362 StackFrameEntry::Label(stack_frame) => std::slice::from_ref(stack_frame),
363 StackFrameEntry::Normal(stack_frame) => std::slice::from_ref(stack_frame),
364 StackFrameEntry::Collapsed(stack_frames) => stack_frames.as_slice(),
365 })
366 .find(|stack_frame| stack_frame.id == stack_frame_id)
367 .cloned()
368 else {
369 return Task::ready(Err(anyhow!("No stack frame for ID")));
370 };
371 self.go_to_stack_frame_inner(stack_frame, window, cx)
372 }
373
374 fn go_to_stack_frame_inner(
375 &mut self,
376 stack_frame: dap::StackFrame,
377 window: &mut Window,
378 cx: &mut Context<Self>,
379 ) -> Task<Result<()>> {
380 let stack_frame_id = stack_frame.id;
381 self.opened_stack_frame_id = Some(stack_frame_id);
382 let Some(abs_path) = Self::abs_path_from_stack_frame(&stack_frame) else {
383 return Task::ready(Err(anyhow!("Project path not found")));
384 };
385 let row = stack_frame.line.saturating_sub(1) as u32;
386 cx.emit(StackFrameListEvent::SelectedStackFrameChanged(
387 stack_frame_id,
388 ));
389 cx.spawn_in(window, async move |this, cx| {
390 let (worktree, relative_path) = this
391 .update(cx, |this, cx| {
392 this.workspace.update(cx, |workspace, cx| {
393 workspace.project().update(cx, |this, cx| {
394 this.find_or_create_worktree(&abs_path, false, cx)
395 })
396 })
397 })??
398 .await?;
399 let buffer = this
400 .update(cx, |this, cx| {
401 this.workspace.update(cx, |this, cx| {
402 this.project().update(cx, |this, cx| {
403 let worktree_id = worktree.read(cx).id();
404 this.open_buffer(
405 ProjectPath {
406 worktree_id,
407 path: relative_path,
408 },
409 cx,
410 )
411 })
412 })
413 })??
414 .await?;
415 let position = buffer.read_with(cx, |this, _| {
416 this.snapshot().anchor_after(PointUtf16::new(row, 0))
417 })?;
418 this.update_in(cx, |this, window, cx| {
419 this.workspace.update(cx, |workspace, cx| {
420 let project_path = buffer
421 .read(cx)
422 .project_path(cx)
423 .context("Could not select a stack frame for unnamed buffer")?;
424
425 let open_preview = !workspace
426 .item_of_type::<StackTraceView>(cx)
427 .map(|viewer| {
428 workspace
429 .active_item(cx)
430 .is_some_and(|item| item.item_id() == viewer.item_id())
431 })
432 .unwrap_or_default();
433
434 anyhow::Ok(workspace.open_path_preview(
435 project_path,
436 None,
437 true,
438 true,
439 open_preview,
440 window,
441 cx,
442 ))
443 })
444 })???
445 .await?;
446
447 this.update(cx, |this, cx| {
448 let thread_id = this.state.read_with(cx, |state, _| {
449 state.thread_id.context("No selected thread ID found")
450 })??;
451
452 this.workspace.update(cx, |workspace, cx| {
453 let breakpoint_store = workspace.project().read(cx).breakpoint_store();
454
455 breakpoint_store.update(cx, |store, cx| {
456 store.set_active_position(
457 ActiveStackFrame {
458 session_id: this.session.read(cx).session_id(),
459 thread_id,
460 stack_frame_id,
461 path: abs_path,
462 position,
463 },
464 cx,
465 );
466 })
467 })
468 })?
469 })
470 }
471
472 pub(crate) fn abs_path_from_stack_frame(stack_frame: &dap::StackFrame) -> Option<Arc<Path>> {
473 stack_frame.source.as_ref().and_then(|s| {
474 s.path
475 .as_deref()
476 .filter(|path| {
477 // Since we do not know if we are debugging on the host or (a remote/WSL) target,
478 // we need to check if either the path is absolute as Posix or Windows.
479 is_absolute(path, PathStyle::Posix) || is_absolute(path, PathStyle::Windows)
480 })
481 .map(|path| Arc::<Path>::from(Path::new(path)))
482 })
483 }
484
485 pub fn restart_stack_frame(&mut self, stack_frame_id: u64, cx: &mut Context<Self>) {
486 self.session.update(cx, |state, cx| {
487 state.restart_stack_frame(stack_frame_id, cx)
488 });
489 }
490
491 fn render_label_entry(
492 &self,
493 stack_frame: &dap::StackFrame,
494 _cx: &mut Context<Self>,
495 ) -> AnyElement {
496 h_flex()
497 .rounded_md()
498 .justify_between()
499 .w_full()
500 .group("")
501 .id(("label-stack-frame", stack_frame.id))
502 .p_1()
503 .on_any_mouse_down(|_, _, cx| {
504 cx.stop_propagation();
505 })
506 .child(
507 v_flex().justify_center().gap_0p5().child(
508 Label::new(stack_frame.name.clone())
509 .size(LabelSize::Small)
510 .weight(FontWeight::BOLD)
511 .truncate()
512 .color(Color::Info),
513 ),
514 )
515 .into_any()
516 }
517
518 fn render_normal_entry(
519 &self,
520 ix: usize,
521 stack_frame: &dap::StackFrame,
522 cx: &mut Context<Self>,
523 ) -> AnyElement {
524 let source = stack_frame.source.clone();
525 let is_selected_frame = Some(ix) == self.selected_ix;
526
527 let path = source.and_then(|s| s.path.or(s.name));
528 let formatted_path = path.map(|path| format!("{}:{}", path, stack_frame.line,));
529 let formatted_path = formatted_path.map(|path| {
530 Label::new(path)
531 .size(LabelSize::XSmall)
532 .line_height_style(LineHeightStyle::UiLabel)
533 .truncate()
534 .color(Color::Muted)
535 });
536
537 let supports_frame_restart = self
538 .session
539 .read(cx)
540 .capabilities()
541 .supports_restart_frame
542 .unwrap_or_default();
543
544 let should_deemphasize = matches!(
545 stack_frame.presentation_hint,
546 Some(
547 dap::StackFramePresentationHint::Subtle
548 | dap::StackFramePresentationHint::Deemphasize
549 )
550 );
551 h_flex()
552 .rounded_md()
553 .justify_between()
554 .w_full()
555 .group("")
556 .id(("stack-frame", stack_frame.id))
557 .p_1()
558 .when(is_selected_frame, |this| {
559 this.bg(cx.theme().colors().element_hover)
560 })
561 .on_any_mouse_down(|_, _, cx| {
562 cx.stop_propagation();
563 })
564 .on_click(cx.listener(move |this, _, window, cx| {
565 this.selected_ix = Some(ix);
566 this.activate_selected_entry(window, cx);
567 }))
568 .hover(|style| style.bg(cx.theme().colors().element_hover).cursor_pointer())
569 .child(
570 v_flex()
571 .gap_0p5()
572 .child(
573 Label::new(stack_frame.name.clone())
574 .size(LabelSize::Small)
575 .truncate()
576 .when(should_deemphasize, |this| this.color(Color::Muted)),
577 )
578 .children(formatted_path),
579 )
580 .when(
581 supports_frame_restart && stack_frame.can_restart.unwrap_or(true),
582 |this| {
583 this.child(
584 h_flex()
585 .id(("restart-stack-frame", stack_frame.id))
586 .visible_on_hover("")
587 .absolute()
588 .right_2()
589 .overflow_hidden()
590 .rounded_md()
591 .border_1()
592 .border_color(cx.theme().colors().element_selected)
593 .bg(cx.theme().colors().element_background)
594 .hover(|style| {
595 style
596 .bg(cx.theme().colors().ghost_element_hover)
597 .cursor_pointer()
598 })
599 .child(
600 IconButton::new(
601 ("restart-stack-frame", stack_frame.id),
602 IconName::RotateCcw,
603 )
604 .icon_size(IconSize::Small)
605 .on_click(cx.listener({
606 let stack_frame_id = stack_frame.id;
607 move |this, _, _window, cx| {
608 this.restart_stack_frame(stack_frame_id, cx);
609 }
610 }))
611 .tooltip(move |window, cx| {
612 Tooltip::text("Restart Stack Frame")(window, cx)
613 }),
614 ),
615 )
616 },
617 )
618 .into_any()
619 }
620
621 pub(crate) fn expand_collapsed_entry(&mut self, ix: usize, cx: &mut Context<Self>) {
622 let Some(StackFrameEntry::Collapsed(stack_frames)) = self.entries.get_mut(ix) else {
623 return;
624 };
625 let entries = std::mem::take(stack_frames)
626 .into_iter()
627 .map(StackFrameEntry::Normal);
628 // HERE
629 let entries_len = entries.len();
630 self.entries.splice(ix..ix + 1, entries);
631 let (Ok(filtered_indices_start) | Err(filtered_indices_start)) =
632 self.filter_entries_indices.binary_search(&ix);
633
634 for idx in &mut self.filter_entries_indices[filtered_indices_start..] {
635 *idx += entries_len - 1;
636 }
637
638 self.selected_ix = Some(ix);
639 self.list_state.reset(self.entries.len());
640 cx.emit(StackFrameListEvent::BuiltEntries);
641 cx.notify();
642 }
643
644 fn render_collapsed_entry(
645 &self,
646 ix: usize,
647 stack_frames: &Vec<dap::StackFrame>,
648 cx: &mut Context<Self>,
649 ) -> AnyElement {
650 let first_stack_frame = &stack_frames[0];
651 let is_selected = Some(ix) == self.selected_ix;
652
653 h_flex()
654 .rounded_md()
655 .justify_between()
656 .w_full()
657 .group("")
658 .id(("stack-frame", first_stack_frame.id))
659 .p_1()
660 .when(is_selected, |this| {
661 this.bg(cx.theme().colors().element_hover)
662 })
663 .on_any_mouse_down(|_, _, cx| {
664 cx.stop_propagation();
665 })
666 .on_click(cx.listener(move |this, _, window, cx| {
667 this.selected_ix = Some(ix);
668 this.activate_selected_entry(window, cx);
669 }))
670 .hover(|style| style.bg(cx.theme().colors().element_hover).cursor_pointer())
671 .child(
672 v_flex()
673 .text_ui_sm(cx)
674 .truncate()
675 .text_color(cx.theme().colors().text_muted)
676 .child(format!(
677 "Show {} more{}",
678 stack_frames.len(),
679 first_stack_frame
680 .source
681 .as_ref()
682 .and_then(|source| source.origin.as_ref())
683 .map_or(String::new(), |origin| format!(": {}", origin))
684 )),
685 )
686 .into_any()
687 }
688
689 fn render_entry(&self, ix: usize, cx: &mut Context<Self>) -> AnyElement {
690 let ix = match self.list_filter {
691 StackFrameFilter::All => ix,
692 StackFrameFilter::OnlyUserFrames => self.filter_entries_indices[ix],
693 };
694
695 match &self.entries[ix] {
696 StackFrameEntry::Label(stack_frame) => self.render_label_entry(stack_frame, cx),
697 StackFrameEntry::Normal(stack_frame) => self.render_normal_entry(ix, stack_frame, cx),
698 StackFrameEntry::Collapsed(stack_frames) => {
699 self.render_collapsed_entry(ix, stack_frames, cx)
700 }
701 }
702 }
703
704 fn select_ix(&mut self, ix: Option<usize>, cx: &mut Context<Self>) {
705 self.selected_ix = ix;
706 cx.notify();
707 }
708
709 fn select_next(&mut self, _: &menu::SelectNext, _window: &mut Window, cx: &mut Context<Self>) {
710 let ix = match self.selected_ix {
711 _ if self.entries.is_empty() => None,
712 None => Some(0),
713 Some(ix) => {
714 if ix == self.entries.len() - 1 {
715 Some(0)
716 } else {
717 Some(ix + 1)
718 }
719 }
720 };
721 self.select_ix(ix, cx);
722 }
723
724 fn select_previous(
725 &mut self,
726 _: &menu::SelectPrevious,
727 _window: &mut Window,
728 cx: &mut Context<Self>,
729 ) {
730 let ix = match self.selected_ix {
731 _ if self.entries.is_empty() => None,
732 None => Some(self.entries.len() - 1),
733 Some(ix) => {
734 if ix == 0 {
735 Some(self.entries.len() - 1)
736 } else {
737 Some(ix - 1)
738 }
739 }
740 };
741 self.select_ix(ix, cx);
742 }
743
744 fn select_first(
745 &mut self,
746 _: &menu::SelectFirst,
747 _window: &mut Window,
748 cx: &mut Context<Self>,
749 ) {
750 let ix = if !self.entries.is_empty() {
751 Some(0)
752 } else {
753 None
754 };
755 self.select_ix(ix, cx);
756 }
757
758 fn select_last(&mut self, _: &menu::SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
759 let ix = if !self.entries.is_empty() {
760 Some(self.entries.len() - 1)
761 } else {
762 None
763 };
764 self.select_ix(ix, cx);
765 }
766
767 fn activate_selected_entry(&mut self, window: &mut Window, cx: &mut Context<Self>) {
768 let Some(ix) = self.selected_ix else {
769 return;
770 };
771 let Some(entry) = self.entries.get_mut(ix) else {
772 return;
773 };
774 match entry {
775 StackFrameEntry::Normal(stack_frame) => {
776 let stack_frame = stack_frame.clone();
777 self.go_to_stack_frame_inner(stack_frame, window, cx)
778 .detach_and_log_err(cx)
779 }
780 StackFrameEntry::Label(_) => {
781 debug_panic!("You should not be able to select a label stack frame")
782 }
783 StackFrameEntry::Collapsed(_) => self.expand_collapsed_entry(ix, cx),
784 }
785 cx.notify();
786 }
787
788 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
789 self.activate_selected_entry(window, cx);
790 }
791
792 pub(crate) fn toggle_frame_filter(
793 &mut self,
794 thread_status: Option<ThreadStatus>,
795 cx: &mut Context<Self>,
796 ) {
797 self.list_filter = match self.list_filter {
798 StackFrameFilter::All => StackFrameFilter::OnlyUserFrames,
799 StackFrameFilter::OnlyUserFrames => StackFrameFilter::All,
800 };
801
802 if let Some(database_id) = self
803 .workspace
804 .read_with(cx, |workspace, _| workspace.database_id())
805 .ok()
806 .flatten()
807 {
808 let database_id: i64 = database_id.into();
809 let save_task = KEY_VALUE_STORE.write_kvp(
810 format!(
811 "stack-frame-list-filter-{}-{}",
812 self.session.read(cx).adapter().0,
813 database_id,
814 ),
815 self.list_filter.into(),
816 );
817 cx.background_spawn(save_task).detach();
818 }
819
820 if let Some(ThreadStatus::Stopped) = thread_status {
821 match self.list_filter {
822 StackFrameFilter::All => {
823 self.list_state.reset(self.entries.len());
824 }
825 StackFrameFilter::OnlyUserFrames => {
826 self.list_state.reset(self.filter_entries_indices.len());
827 if !self
828 .selected_ix
829 .map(|ix| self.filter_entries_indices.contains(&ix))
830 .unwrap_or_default()
831 {
832 self.selected_ix = None;
833 }
834 }
835 }
836
837 if let Some(ix) = self.selected_ix {
838 let scroll_to = match self.list_filter {
839 StackFrameFilter::All => ix,
840 StackFrameFilter::OnlyUserFrames => self
841 .filter_entries_indices
842 .binary_search_by_key(&ix, |ix| *ix)
843 .expect("This index will always exist"),
844 };
845 self.list_state.scroll_to_reveal_item(scroll_to);
846 }
847
848 cx.emit(StackFrameListEvent::BuiltEntries);
849 cx.notify();
850 }
851 }
852
853 fn render_list(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
854 div().p_1().size_full().child(
855 list(
856 self.list_state.clone(),
857 cx.processor(|this, ix, _window, cx| this.render_entry(ix, cx)),
858 )
859 .size_full(),
860 )
861 }
862
863 pub(crate) fn render_control_strip(&self) -> AnyElement {
864 let tooltip_title = match self.list_filter {
865 StackFrameFilter::All => "Show stack frames from your project",
866 StackFrameFilter::OnlyUserFrames => "Show all stack frames",
867 };
868
869 h_flex()
870 .child(
871 IconButton::new(
872 "filter-by-visible-worktree-stack-frame-list",
873 IconName::ListFilter,
874 )
875 .tooltip(move |window, cx| {
876 Tooltip::for_action(tooltip_title, &ToggleUserFrames, window, cx)
877 })
878 .toggle_state(self.list_filter == StackFrameFilter::OnlyUserFrames)
879 .icon_size(IconSize::Small)
880 .on_click(|_, window, cx| {
881 window.dispatch_action(ToggleUserFrames.boxed_clone(), cx)
882 }),
883 )
884 .into_any_element()
885 }
886}
887
888impl Render for StackFrameList {
889 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
890 div()
891 .track_focus(&self.focus_handle)
892 .size_full()
893 .on_action(cx.listener(Self::select_next))
894 .on_action(cx.listener(Self::select_previous))
895 .on_action(cx.listener(Self::select_first))
896 .on_action(cx.listener(Self::select_last))
897 .on_action(cx.listener(Self::confirm))
898 .when_some(self.error.clone(), |el, error| {
899 el.child(
900 h_flex()
901 .bg(cx.theme().status().warning_background)
902 .border_b_1()
903 .border_color(cx.theme().status().warning_border)
904 .pl_1()
905 .child(Icon::new(IconName::Warning).color(Color::Warning))
906 .gap_2()
907 .child(
908 Label::new(error)
909 .size(LabelSize::Small)
910 .color(Color::Warning),
911 ),
912 )
913 })
914 .child(self.render_list(window, cx))
915 .vertical_scrollbar_for(self.list_state.clone(), window, cx)
916 }
917}
918
919impl Focusable for StackFrameList {
920 fn focus_handle(&self, _: &gpui::App) -> gpui::FocusHandle {
921 self.focus_handle.clone()
922 }
923}
924
925impl EventEmitter<StackFrameListEvent> for StackFrameList {}