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 .overflow_x_scroll()
570 .child(
571 v_flex()
572 .gap_0p5()
573 .child(
574 Label::new(stack_frame.name.clone())
575 .size(LabelSize::Small)
576 .truncate()
577 .when(should_deemphasize, |this| this.color(Color::Muted)),
578 )
579 .children(formatted_path),
580 )
581 .when(
582 supports_frame_restart && stack_frame.can_restart.unwrap_or(true),
583 |this| {
584 this.child(
585 h_flex()
586 .id(("restart-stack-frame", stack_frame.id))
587 .visible_on_hover("")
588 .absolute()
589 .right_2()
590 .overflow_hidden()
591 .rounded_md()
592 .border_1()
593 .border_color(cx.theme().colors().element_selected)
594 .bg(cx.theme().colors().element_background)
595 .hover(|style| {
596 style
597 .bg(cx.theme().colors().ghost_element_hover)
598 .cursor_pointer()
599 })
600 .child(
601 IconButton::new(
602 ("restart-stack-frame", stack_frame.id),
603 IconName::RotateCcw,
604 )
605 .icon_size(IconSize::Small)
606 .on_click(cx.listener({
607 let stack_frame_id = stack_frame.id;
608 move |this, _, _window, cx| {
609 this.restart_stack_frame(stack_frame_id, cx);
610 }
611 }))
612 .tooltip(move |window, cx| {
613 Tooltip::text("Restart Stack Frame")(window, cx)
614 }),
615 ),
616 )
617 },
618 )
619 .into_any()
620 }
621
622 pub(crate) fn expand_collapsed_entry(&mut self, ix: usize, cx: &mut Context<Self>) {
623 let Some(StackFrameEntry::Collapsed(stack_frames)) = self.entries.get_mut(ix) else {
624 return;
625 };
626 let entries = std::mem::take(stack_frames)
627 .into_iter()
628 .map(StackFrameEntry::Normal);
629 // HERE
630 let entries_len = entries.len();
631 self.entries.splice(ix..ix + 1, entries);
632 let (Ok(filtered_indices_start) | Err(filtered_indices_start)) =
633 self.filter_entries_indices.binary_search(&ix);
634
635 for idx in &mut self.filter_entries_indices[filtered_indices_start..] {
636 *idx += entries_len - 1;
637 }
638
639 self.selected_ix = Some(ix);
640 self.list_state.reset(self.entries.len());
641 cx.emit(StackFrameListEvent::BuiltEntries);
642 cx.notify();
643 }
644
645 fn render_collapsed_entry(
646 &self,
647 ix: usize,
648 stack_frames: &Vec<dap::StackFrame>,
649 cx: &mut Context<Self>,
650 ) -> AnyElement {
651 let first_stack_frame = &stack_frames[0];
652 let is_selected = Some(ix) == self.selected_ix;
653
654 h_flex()
655 .rounded_md()
656 .justify_between()
657 .w_full()
658 .group("")
659 .id(("stack-frame", first_stack_frame.id))
660 .p_1()
661 .when(is_selected, |this| {
662 this.bg(cx.theme().colors().element_hover)
663 })
664 .on_any_mouse_down(|_, _, cx| {
665 cx.stop_propagation();
666 })
667 .on_click(cx.listener(move |this, _, window, cx| {
668 this.selected_ix = Some(ix);
669 this.activate_selected_entry(window, cx);
670 }))
671 .hover(|style| style.bg(cx.theme().colors().element_hover).cursor_pointer())
672 .child(
673 v_flex()
674 .text_ui_sm(cx)
675 .truncate()
676 .text_color(cx.theme().colors().text_muted)
677 .child(format!(
678 "Show {} more{}",
679 stack_frames.len(),
680 first_stack_frame
681 .source
682 .as_ref()
683 .and_then(|source| source.origin.as_ref())
684 .map_or(String::new(), |origin| format!(": {}", origin))
685 )),
686 )
687 .into_any()
688 }
689
690 fn render_entry(&self, ix: usize, cx: &mut Context<Self>) -> AnyElement {
691 let ix = match self.list_filter {
692 StackFrameFilter::All => ix,
693 StackFrameFilter::OnlyUserFrames => self.filter_entries_indices[ix],
694 };
695
696 match &self.entries[ix] {
697 StackFrameEntry::Label(stack_frame) => self.render_label_entry(stack_frame, cx),
698 StackFrameEntry::Normal(stack_frame) => self.render_normal_entry(ix, stack_frame, cx),
699 StackFrameEntry::Collapsed(stack_frames) => {
700 self.render_collapsed_entry(ix, stack_frames, cx)
701 }
702 }
703 }
704
705 fn select_ix(&mut self, ix: Option<usize>, cx: &mut Context<Self>) {
706 self.selected_ix = ix;
707 cx.notify();
708 }
709
710 fn select_next(&mut self, _: &menu::SelectNext, _window: &mut Window, cx: &mut Context<Self>) {
711 let ix = match self.selected_ix {
712 _ if self.entries.is_empty() => None,
713 None => Some(0),
714 Some(ix) => {
715 if ix == self.entries.len() - 1 {
716 Some(0)
717 } else {
718 Some(ix + 1)
719 }
720 }
721 };
722 self.select_ix(ix, cx);
723 }
724
725 fn select_previous(
726 &mut self,
727 _: &menu::SelectPrevious,
728 _window: &mut Window,
729 cx: &mut Context<Self>,
730 ) {
731 let ix = match self.selected_ix {
732 _ if self.entries.is_empty() => None,
733 None => Some(self.entries.len() - 1),
734 Some(ix) => {
735 if ix == 0 {
736 Some(self.entries.len() - 1)
737 } else {
738 Some(ix - 1)
739 }
740 }
741 };
742 self.select_ix(ix, cx);
743 }
744
745 fn select_first(
746 &mut self,
747 _: &menu::SelectFirst,
748 _window: &mut Window,
749 cx: &mut Context<Self>,
750 ) {
751 let ix = if !self.entries.is_empty() {
752 Some(0)
753 } else {
754 None
755 };
756 self.select_ix(ix, cx);
757 }
758
759 fn select_last(&mut self, _: &menu::SelectLast, _window: &mut Window, cx: &mut Context<Self>) {
760 let ix = if !self.entries.is_empty() {
761 Some(self.entries.len() - 1)
762 } else {
763 None
764 };
765 self.select_ix(ix, cx);
766 }
767
768 fn activate_selected_entry(&mut self, window: &mut Window, cx: &mut Context<Self>) {
769 let Some(ix) = self.selected_ix else {
770 return;
771 };
772 let Some(entry) = self.entries.get_mut(ix) else {
773 return;
774 };
775 match entry {
776 StackFrameEntry::Normal(stack_frame) => {
777 let stack_frame = stack_frame.clone();
778 self.go_to_stack_frame_inner(stack_frame, window, cx)
779 .detach_and_log_err(cx)
780 }
781 StackFrameEntry::Label(_) => {
782 debug_panic!("You should not be able to select a label stack frame")
783 }
784 StackFrameEntry::Collapsed(_) => self.expand_collapsed_entry(ix, cx),
785 }
786 cx.notify();
787 }
788
789 fn confirm(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
790 self.activate_selected_entry(window, cx);
791 }
792
793 pub(crate) fn toggle_frame_filter(
794 &mut self,
795 thread_status: Option<ThreadStatus>,
796 cx: &mut Context<Self>,
797 ) {
798 self.list_filter = match self.list_filter {
799 StackFrameFilter::All => StackFrameFilter::OnlyUserFrames,
800 StackFrameFilter::OnlyUserFrames => StackFrameFilter::All,
801 };
802
803 if let Some(database_id) = self
804 .workspace
805 .read_with(cx, |workspace, _| workspace.database_id())
806 .ok()
807 .flatten()
808 {
809 let database_id: i64 = database_id.into();
810 let save_task = KEY_VALUE_STORE.write_kvp(
811 format!(
812 "stack-frame-list-filter-{}-{}",
813 self.session.read(cx).adapter().0,
814 database_id,
815 ),
816 self.list_filter.into(),
817 );
818 cx.background_spawn(save_task).detach();
819 }
820
821 if let Some(ThreadStatus::Stopped) = thread_status {
822 match self.list_filter {
823 StackFrameFilter::All => {
824 self.list_state.reset(self.entries.len());
825 }
826 StackFrameFilter::OnlyUserFrames => {
827 self.list_state.reset(self.filter_entries_indices.len());
828 if !self
829 .selected_ix
830 .map(|ix| self.filter_entries_indices.contains(&ix))
831 .unwrap_or_default()
832 {
833 self.selected_ix = None;
834 }
835 }
836 }
837
838 if let Some(ix) = self.selected_ix {
839 let scroll_to = match self.list_filter {
840 StackFrameFilter::All => ix,
841 StackFrameFilter::OnlyUserFrames => self
842 .filter_entries_indices
843 .binary_search_by_key(&ix, |ix| *ix)
844 .expect("This index will always exist"),
845 };
846 self.list_state.scroll_to_reveal_item(scroll_to);
847 }
848
849 cx.emit(StackFrameListEvent::BuiltEntries);
850 cx.notify();
851 }
852 }
853
854 fn render_list(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
855 div().p_1().size_full().child(
856 list(
857 self.list_state.clone(),
858 cx.processor(|this, ix, _window, cx| this.render_entry(ix, cx)),
859 )
860 .size_full(),
861 )
862 }
863
864 pub(crate) fn render_control_strip(&self) -> AnyElement {
865 let tooltip_title = match self.list_filter {
866 StackFrameFilter::All => "Show stack frames from your project",
867 StackFrameFilter::OnlyUserFrames => "Show all stack frames",
868 };
869
870 h_flex()
871 .child(
872 IconButton::new(
873 "filter-by-visible-worktree-stack-frame-list",
874 IconName::ListFilter,
875 )
876 .tooltip(move |_window, cx| {
877 Tooltip::for_action(tooltip_title, &ToggleUserFrames, cx)
878 })
879 .toggle_state(self.list_filter == StackFrameFilter::OnlyUserFrames)
880 .icon_size(IconSize::Small)
881 .on_click(|_, window, cx| {
882 window.dispatch_action(ToggleUserFrames.boxed_clone(), cx)
883 }),
884 )
885 .into_any_element()
886 }
887}
888
889impl Render for StackFrameList {
890 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
891 div()
892 .track_focus(&self.focus_handle)
893 .size_full()
894 .on_action(cx.listener(Self::select_next))
895 .on_action(cx.listener(Self::select_previous))
896 .on_action(cx.listener(Self::select_first))
897 .on_action(cx.listener(Self::select_last))
898 .on_action(cx.listener(Self::confirm))
899 .when_some(self.error.clone(), |el, error| {
900 el.child(
901 h_flex()
902 .bg(cx.theme().status().warning_background)
903 .border_b_1()
904 .border_color(cx.theme().status().warning_border)
905 .pl_1()
906 .child(Icon::new(IconName::Warning).color(Color::Warning))
907 .gap_2()
908 .child(
909 Label::new(error)
910 .size(LabelSize::Small)
911 .color(Color::Warning),
912 ),
913 )
914 })
915 .child(self.render_list(window, cx))
916 .vertical_scrollbar_for(self.list_state.clone(), window, cx)
917 }
918}
919
920impl Focusable for StackFrameList {
921 fn focus_handle(&self, _: &gpui::App) -> gpui::FocusHandle {
922 self.focus_handle.clone()
923 }
924}
925
926impl EventEmitter<StackFrameListEvent> for StackFrameList {}