variable_list.rs

  1use super::stack_frame_list::{StackFrameList, StackFrameListEvent};
  2use dap::{ScopePresentationHint, StackFrameId, VariablePresentationHintKind, VariableReference};
  3use editor::Editor;
  4use gpui::{
  5    AnyElement, ClickEvent, ClipboardItem, Context, DismissEvent, Entity, FocusHandle, Focusable,
  6    Hsla, MouseButton, MouseDownEvent, Point, Stateful, Subscription, TextStyleRefinement,
  7    UniformListScrollHandle, actions, anchored, deferred, uniform_list,
  8};
  9use menu::{SelectFirst, SelectLast, SelectNext, SelectPrevious};
 10use project::debugger::session::{Session, SessionEvent};
 11use std::{collections::HashMap, ops::Range, sync::Arc};
 12use ui::{ContextMenu, ListItem, Scrollbar, ScrollbarState, prelude::*};
 13use util::{debug_panic, maybe};
 14
 15actions!(variable_list, [ExpandSelectedEntry, CollapseSelectedEntry]);
 16
 17#[derive(Debug, Copy, Clone, PartialEq, Eq)]
 18pub(crate) struct EntryState {
 19    depth: usize,
 20    is_expanded: bool,
 21    has_children: bool,
 22    parent_reference: VariableReference,
 23}
 24
 25#[derive(Debug, PartialEq, Eq, Hash, Clone)]
 26pub(crate) struct EntryPath {
 27    pub leaf_name: Option<SharedString>,
 28    pub indices: Arc<[SharedString]>,
 29}
 30
 31impl EntryPath {
 32    fn for_scope(scope_name: impl Into<SharedString>) -> Self {
 33        Self {
 34            leaf_name: Some(scope_name.into()),
 35            indices: Arc::new([]),
 36        }
 37    }
 38
 39    fn with_name(&self, name: SharedString) -> Self {
 40        Self {
 41            leaf_name: Some(name),
 42            indices: self.indices.clone(),
 43        }
 44    }
 45
 46    /// Create a new child of this variable path
 47    fn with_child(&self, name: SharedString) -> Self {
 48        Self {
 49            leaf_name: None,
 50            indices: self
 51                .indices
 52                .iter()
 53                .cloned()
 54                .chain(std::iter::once(name))
 55                .collect(),
 56        }
 57    }
 58}
 59
 60#[derive(Debug, Clone, PartialEq)]
 61enum EntryKind {
 62    Variable(dap::Variable),
 63    Scope(dap::Scope),
 64}
 65
 66impl EntryKind {
 67    fn as_variable(&self) -> Option<&dap::Variable> {
 68        match self {
 69            EntryKind::Variable(dap) => Some(dap),
 70            _ => None,
 71        }
 72    }
 73
 74    fn as_scope(&self) -> Option<&dap::Scope> {
 75        match self {
 76            EntryKind::Scope(dap) => Some(dap),
 77            _ => None,
 78        }
 79    }
 80
 81    #[allow(dead_code)]
 82    fn name(&self) -> &str {
 83        match self {
 84            EntryKind::Variable(dap) => &dap.name,
 85            EntryKind::Scope(dap) => &dap.name,
 86        }
 87    }
 88}
 89
 90#[derive(Debug, Clone, PartialEq)]
 91struct ListEntry {
 92    dap_kind: EntryKind,
 93    path: EntryPath,
 94}
 95
 96impl ListEntry {
 97    fn as_variable(&self) -> Option<&dap::Variable> {
 98        self.dap_kind.as_variable()
 99    }
100
101    fn as_scope(&self) -> Option<&dap::Scope> {
102        self.dap_kind.as_scope()
103    }
104
105    fn item_id(&self) -> ElementId {
106        use std::fmt::Write;
107        let mut id = match &self.dap_kind {
108            EntryKind::Variable(dap) => format!("variable-{}", dap.name),
109            EntryKind::Scope(dap) => format!("scope-{}", dap.name),
110        };
111        for name in self.path.indices.iter() {
112            _ = write!(id, "-{}", name);
113        }
114        SharedString::from(id).into()
115    }
116
117    fn item_value_id(&self) -> ElementId {
118        use std::fmt::Write;
119        let mut id = match &self.dap_kind {
120            EntryKind::Variable(dap) => format!("variable-{}", dap.name),
121            EntryKind::Scope(dap) => format!("scope-{}", dap.name),
122        };
123        for name in self.path.indices.iter() {
124            _ = write!(id, "-{}", name);
125        }
126        _ = write!(id, "-value");
127        SharedString::from(id).into()
128    }
129}
130
131pub struct VariableList {
132    entries: Vec<ListEntry>,
133    entry_states: HashMap<EntryPath, EntryState>,
134    selected_stack_frame_id: Option<StackFrameId>,
135    list_handle: UniformListScrollHandle,
136    scrollbar_state: ScrollbarState,
137    session: Entity<Session>,
138    selection: Option<EntryPath>,
139    open_context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,
140    focus_handle: FocusHandle,
141    edited_path: Option<(EntryPath, Entity<Editor>)>,
142    disabled: bool,
143    _subscriptions: Vec<Subscription>,
144}
145
146impl VariableList {
147    pub fn new(
148        session: Entity<Session>,
149        stack_frame_list: Entity<StackFrameList>,
150        window: &mut Window,
151        cx: &mut Context<Self>,
152    ) -> Self {
153        let focus_handle = cx.focus_handle();
154
155        let _subscriptions = vec![
156            cx.subscribe(&stack_frame_list, Self::handle_stack_frame_list_events),
157            cx.subscribe(&session, |this, _, event, _| match event {
158                SessionEvent::Stopped(_) => {
159                    this.selection.take();
160                    this.edited_path.take();
161                    this.selected_stack_frame_id.take();
162                }
163                _ => {}
164            }),
165            cx.on_focus_out(&focus_handle, window, |this, _, _, cx| {
166                this.edited_path.take();
167                cx.notify();
168            }),
169        ];
170
171        let list_state = UniformListScrollHandle::default();
172
173        Self {
174            scrollbar_state: ScrollbarState::new(list_state.clone()),
175            list_handle: list_state,
176            session,
177            focus_handle,
178            _subscriptions,
179            selected_stack_frame_id: None,
180            selection: None,
181            open_context_menu: None,
182            disabled: false,
183            edited_path: None,
184            entries: Default::default(),
185            entry_states: Default::default(),
186        }
187    }
188
189    pub(super) fn disabled(&mut self, disabled: bool, cx: &mut Context<Self>) {
190        let old_disabled = std::mem::take(&mut self.disabled);
191        self.disabled = disabled;
192        if old_disabled != disabled {
193            cx.notify();
194        }
195    }
196
197    pub(super) fn has_open_context_menu(&self) -> bool {
198        self.open_context_menu.is_some()
199    }
200
201    fn build_entries(&mut self, cx: &mut Context<Self>) {
202        let Some(stack_frame_id) = self.selected_stack_frame_id else {
203            return;
204        };
205
206        let mut entries = vec![];
207        let scopes: Vec<_> = self.session.update(cx, |session, cx| {
208            session.scopes(stack_frame_id, cx).iter().cloned().collect()
209        });
210
211        let mut contains_local_scope = false;
212
213        let mut stack = scopes
214            .into_iter()
215            .rev()
216            .filter(|scope| {
217                if scope
218                    .presentation_hint
219                    .as_ref()
220                    .map(|hint| *hint == ScopePresentationHint::Locals)
221                    .unwrap_or(scope.name.to_lowercase().starts_with("local"))
222                {
223                    contains_local_scope = true;
224                }
225
226                self.session.update(cx, |session, cx| {
227                    session.variables(scope.variables_reference, cx).len() > 0
228                })
229            })
230            .map(|scope| {
231                (
232                    scope.variables_reference,
233                    scope.variables_reference,
234                    EntryPath::for_scope(&scope.name),
235                    EntryKind::Scope(scope),
236                )
237            })
238            .collect::<Vec<_>>();
239
240        let scopes_count = stack.len();
241
242        while let Some((container_reference, variables_reference, mut path, dap_kind)) = stack.pop()
243        {
244            match &dap_kind {
245                EntryKind::Variable(dap) => path = path.with_name(dap.name.clone().into()),
246                EntryKind::Scope(dap) => path = path.with_child(dap.name.clone().into()),
247            }
248
249            let var_state = self
250                .entry_states
251                .entry(path.clone())
252                .and_modify(|state| {
253                    state.parent_reference = container_reference;
254                    state.has_children = variables_reference != 0;
255                })
256                .or_insert(EntryState {
257                    depth: path.indices.len(),
258                    is_expanded: dap_kind.as_scope().is_some_and(|scope| {
259                        (scopes_count == 1 && !contains_local_scope)
260                            || scope
261                                .presentation_hint
262                                .as_ref()
263                                .map(|hint| *hint == ScopePresentationHint::Locals)
264                                .unwrap_or(scope.name.to_lowercase().starts_with("local"))
265                    }),
266                    parent_reference: container_reference,
267                    has_children: variables_reference != 0,
268                });
269
270            entries.push(ListEntry {
271                dap_kind,
272                path: path.clone(),
273            });
274
275            if var_state.is_expanded {
276                let children = self
277                    .session
278                    .update(cx, |session, cx| session.variables(variables_reference, cx));
279                stack.extend(children.into_iter().rev().map(|child| {
280                    (
281                        variables_reference,
282                        child.variables_reference,
283                        path.with_child(child.name.clone().into()),
284                        EntryKind::Variable(child),
285                    )
286                }));
287            }
288        }
289
290        self.entries = entries;
291        cx.notify();
292    }
293
294    fn handle_stack_frame_list_events(
295        &mut self,
296        _: Entity<StackFrameList>,
297        event: &StackFrameListEvent,
298        cx: &mut Context<Self>,
299    ) {
300        match event {
301            StackFrameListEvent::SelectedStackFrameChanged(stack_frame_id) => {
302                self.selected_stack_frame_id = Some(*stack_frame_id);
303                cx.notify();
304            }
305        }
306    }
307
308    pub fn completion_variables(&self, _cx: &mut Context<Self>) -> Vec<dap::Variable> {
309        self.entries
310            .iter()
311            .filter_map(|entry| match &entry.dap_kind {
312                EntryKind::Variable(dap) => Some(dap.clone()),
313                EntryKind::Scope(_) => None,
314            })
315            .collect()
316    }
317
318    fn render_entries(
319        &mut self,
320        ix: Range<usize>,
321        window: &mut Window,
322        cx: &mut Context<Self>,
323    ) -> Vec<AnyElement> {
324        ix.into_iter()
325            .filter_map(|ix| {
326                let (entry, state) = self
327                    .entries
328                    .get(ix)
329                    .and_then(|entry| Some(entry).zip(self.entry_states.get(&entry.path)))?;
330
331                match &entry.dap_kind {
332                    EntryKind::Variable(_) => Some(self.render_variable(entry, *state, window, cx)),
333                    EntryKind::Scope(_) => Some(self.render_scope(entry, *state, cx)),
334                }
335            })
336            .collect()
337    }
338
339    pub(crate) fn toggle_entry(&mut self, var_path: &EntryPath, cx: &mut Context<Self>) {
340        let Some(entry) = self.entry_states.get_mut(var_path) else {
341            log::error!("Could not find variable list entry state to toggle");
342            return;
343        };
344
345        entry.is_expanded = !entry.is_expanded;
346        cx.notify();
347    }
348
349    fn select_first(&mut self, _: &SelectFirst, window: &mut Window, cx: &mut Context<Self>) {
350        self.cancel_variable_edit(&Default::default(), window, cx);
351        if let Some(variable) = self.entries.first() {
352            self.selection = Some(variable.path.clone());
353            cx.notify();
354        }
355    }
356
357    fn select_last(&mut self, _: &SelectLast, window: &mut Window, cx: &mut Context<Self>) {
358        self.cancel_variable_edit(&Default::default(), window, cx);
359        if let Some(variable) = self.entries.last() {
360            self.selection = Some(variable.path.clone());
361            cx.notify();
362        }
363    }
364
365    fn select_prev(&mut self, _: &SelectPrevious, window: &mut Window, cx: &mut Context<Self>) {
366        self.cancel_variable_edit(&Default::default(), window, cx);
367        if let Some(selection) = &self.selection {
368            let index = self.entries.iter().enumerate().find_map(|(ix, var)| {
369                if &var.path == selection && ix > 0 {
370                    Some(ix.saturating_sub(1))
371                } else {
372                    None
373                }
374            });
375
376            if let Some(new_selection) =
377                index.and_then(|ix| self.entries.get(ix).map(|var| var.path.clone()))
378            {
379                self.selection = Some(new_selection);
380                cx.notify();
381            } else {
382                self.select_last(&SelectLast, window, cx);
383            }
384        } else {
385            self.select_last(&SelectLast, window, cx);
386        }
387    }
388
389    fn select_next(&mut self, _: &SelectNext, window: &mut Window, cx: &mut Context<Self>) {
390        self.cancel_variable_edit(&Default::default(), window, cx);
391        if let Some(selection) = &self.selection {
392            let index = self.entries.iter().enumerate().find_map(|(ix, var)| {
393                if &var.path == selection {
394                    Some(ix.saturating_add(1))
395                } else {
396                    None
397                }
398            });
399
400            if let Some(new_selection) =
401                index.and_then(|ix| self.entries.get(ix).map(|var| var.path.clone()))
402            {
403                self.selection = Some(new_selection);
404                cx.notify();
405            } else {
406                self.select_first(&SelectFirst, window, cx);
407            }
408        } else {
409            self.select_first(&SelectFirst, window, cx);
410        }
411    }
412
413    fn cancel_variable_edit(
414        &mut self,
415        _: &menu::Cancel,
416        window: &mut Window,
417        cx: &mut Context<Self>,
418    ) {
419        self.edited_path.take();
420        self.focus_handle.focus(window);
421        cx.notify();
422    }
423
424    fn confirm_variable_edit(
425        &mut self,
426        _: &menu::Confirm,
427        _window: &mut Window,
428        cx: &mut Context<Self>,
429    ) {
430        let res = maybe!({
431            let (var_path, editor) = self.edited_path.take()?;
432            let state = self.entry_states.get(&var_path)?;
433            let variables_reference = state.parent_reference;
434            let name = var_path.leaf_name?;
435            let value = editor.read(cx).text(cx);
436
437            self.session.update(cx, |session, cx| {
438                session.set_variable_value(variables_reference, name.into(), value, cx)
439            });
440            Some(())
441        });
442
443        if res.is_none() {
444            log::error!(
445                "Couldn't confirm variable edit because variable doesn't have a leaf name or a parent reference id"
446            );
447        }
448    }
449
450    fn collapse_selected_entry(
451        &mut self,
452        _: &CollapseSelectedEntry,
453        window: &mut Window,
454        cx: &mut Context<Self>,
455    ) {
456        if let Some(ref selected_entry) = self.selection {
457            let Some(entry_state) = self.entry_states.get_mut(selected_entry) else {
458                debug_panic!("Trying to toggle variable in variable list that has an no state");
459                return;
460            };
461
462            if !entry_state.is_expanded || !entry_state.has_children {
463                self.select_prev(&SelectPrevious, window, cx);
464            } else {
465                entry_state.is_expanded = false;
466                cx.notify();
467            }
468        }
469    }
470
471    fn expand_selected_entry(
472        &mut self,
473        _: &ExpandSelectedEntry,
474        window: &mut Window,
475        cx: &mut Context<Self>,
476    ) {
477        if let Some(selected_entry) = &self.selection {
478            let Some(entry_state) = self.entry_states.get_mut(selected_entry) else {
479                debug_panic!("Trying to toggle variable in variable list that has an no state");
480                return;
481            };
482
483            if entry_state.is_expanded || !entry_state.has_children {
484                self.select_next(&SelectNext, window, cx);
485            } else {
486                entry_state.is_expanded = true;
487                cx.notify();
488            }
489        }
490    }
491
492    fn deploy_variable_context_menu(
493        &mut self,
494        variable: ListEntry,
495        position: Point<Pixels>,
496        window: &mut Window,
497        cx: &mut Context<Self>,
498    ) {
499        let Some(dap_var) = variable.as_variable() else {
500            debug_panic!("Trying to open variable context menu on a scope");
501            return;
502        };
503
504        let variable_value = dap_var.value.clone();
505        let variable_name = dap_var.name.clone();
506        let this = cx.entity().clone();
507
508        let context_menu = ContextMenu::build(window, cx, |menu, _, _| {
509            menu.entry("Copy name", None, move |_, cx| {
510                cx.write_to_clipboard(ClipboardItem::new_string(variable_name.clone()))
511            })
512            .entry("Copy value", None, {
513                let variable_value = variable_value.clone();
514                move |_, cx| {
515                    cx.write_to_clipboard(ClipboardItem::new_string(variable_value.clone()))
516                }
517            })
518            .entry("Set value", None, move |window, cx| {
519                this.update(cx, |variable_list, cx| {
520                    let editor = Self::create_variable_editor(&variable_value, window, cx);
521                    variable_list.edited_path = Some((variable.path.clone(), editor));
522
523                    cx.notify();
524                });
525            })
526        });
527
528        cx.focus_view(&context_menu, window);
529        let subscription = cx.subscribe_in(
530            &context_menu,
531            window,
532            |this, _, _: &DismissEvent, window, cx| {
533                if this.open_context_menu.as_ref().is_some_and(|context_menu| {
534                    context_menu.0.focus_handle(cx).contains_focused(window, cx)
535                }) {
536                    cx.focus_self(window);
537                }
538                this.open_context_menu.take();
539                cx.notify();
540            },
541        );
542
543        self.open_context_menu = Some((context_menu, position, subscription));
544    }
545
546    #[track_caller]
547    #[cfg(test)]
548    pub(crate) fn assert_visual_entries(&self, expected: Vec<&str>) {
549        const INDENT: &'static str = "    ";
550
551        let entries = &self.entries;
552        let mut visual_entries = Vec::with_capacity(entries.len());
553        for entry in entries {
554            let state = self
555                .entry_states
556                .get(&entry.path)
557                .expect("If there's a variable entry there has to be a state that goes with it");
558
559            visual_entries.push(format!(
560                "{}{} {}{}",
561                INDENT.repeat(state.depth - 1),
562                if state.is_expanded { "v" } else { ">" },
563                entry.dap_kind.name(),
564                if self.selection.as_ref() == Some(&entry.path) {
565                    " <=== selected"
566                } else {
567                    ""
568                }
569            ));
570        }
571
572        pretty_assertions::assert_eq!(expected, visual_entries);
573    }
574
575    #[track_caller]
576    #[cfg(test)]
577    pub(crate) fn scopes(&self) -> Vec<dap::Scope> {
578        self.entries
579            .iter()
580            .filter_map(|entry| match &entry.dap_kind {
581                EntryKind::Scope(scope) => Some(scope),
582                _ => None,
583            })
584            .cloned()
585            .collect()
586    }
587
588    #[track_caller]
589    #[cfg(test)]
590    pub(crate) fn variables_per_scope(&self) -> Vec<(dap::Scope, Vec<dap::Variable>)> {
591        let mut scopes: Vec<(dap::Scope, Vec<_>)> = Vec::new();
592        let mut idx = 0;
593
594        for entry in self.entries.iter() {
595            match &entry.dap_kind {
596                EntryKind::Variable(dap) => scopes[idx].1.push(dap.clone()),
597                EntryKind::Scope(scope) => {
598                    if scopes.len() > 0 {
599                        idx += 1;
600                    }
601
602                    scopes.push((scope.clone(), Vec::new()));
603                }
604            }
605        }
606
607        scopes
608    }
609
610    #[track_caller]
611    #[cfg(test)]
612    pub(crate) fn variables(&self) -> Vec<dap::Variable> {
613        self.entries
614            .iter()
615            .filter_map(|entry| match &entry.dap_kind {
616                EntryKind::Variable(variable) => Some(variable),
617                _ => None,
618            })
619            .cloned()
620            .collect()
621    }
622
623    fn create_variable_editor(default: &str, window: &mut Window, cx: &mut App) -> Entity<Editor> {
624        let editor = cx.new(|cx| {
625            let mut editor = Editor::single_line(window, cx);
626
627            let refinement = TextStyleRefinement {
628                font_size: Some(
629                    TextSize::XSmall
630                        .rems(cx)
631                        .to_pixels(window.rem_size())
632                        .into(),
633                ),
634                ..Default::default()
635            };
636            editor.set_text_style_refinement(refinement);
637            editor.set_text(default, window, cx);
638            editor.select_all(&editor::actions::SelectAll, window, cx);
639            editor
640        });
641        editor.focus_handle(cx).focus(window);
642        editor
643    }
644
645    fn render_scope(
646        &self,
647        entry: &ListEntry,
648        state: EntryState,
649        cx: &mut Context<Self>,
650    ) -> AnyElement {
651        let Some(scope) = entry.as_scope() else {
652            debug_panic!("Called render scope on non scope variable list entry variant");
653            return div().into_any_element();
654        };
655
656        let var_ref = scope.variables_reference;
657        let is_selected = self
658            .selection
659            .as_ref()
660            .is_some_and(|selection| selection == &entry.path);
661
662        let colors = get_entry_color(cx);
663        let bg_hover_color = if !is_selected {
664            colors.hover
665        } else {
666            colors.default
667        };
668        let border_color = if is_selected {
669            colors.marked_active
670        } else {
671            colors.default
672        };
673        let path = entry.path.clone();
674
675        div()
676            .id(var_ref as usize)
677            .group("variable_list_entry")
678            .pl_2()
679            .border_1()
680            .border_r_2()
681            .border_color(border_color)
682            .flex()
683            .w_full()
684            .h_full()
685            .hover(|style| style.bg(bg_hover_color))
686            .on_click(cx.listener({
687                move |this, _, _window, cx| {
688                    this.selection = Some(path.clone());
689                    cx.notify();
690                }
691            }))
692            .child(
693                ListItem::new(SharedString::from(format!("scope-{}", var_ref)))
694                    .selectable(false)
695                    .disabled(self.disabled)
696                    .indent_level(state.depth)
697                    .indent_step_size(px(10.))
698                    .always_show_disclosure_icon(true)
699                    .toggle(state.is_expanded)
700                    .on_toggle({
701                        let var_path = entry.path.clone();
702                        cx.listener(move |this, _, _, cx| this.toggle_entry(&var_path, cx))
703                    })
704                    .child(
705                        div()
706                            .text_ui(cx)
707                            .w_full()
708                            .when(self.disabled, |this| {
709                                this.text_color(Color::Disabled.color(cx))
710                            })
711                            .child(scope.name.clone()),
712                    ),
713            )
714            .into_any()
715    }
716
717    fn render_variable(
718        &self,
719        variable: &ListEntry,
720        state: EntryState,
721        window: &mut Window,
722        cx: &mut Context<Self>,
723    ) -> AnyElement {
724        let dap = match &variable.dap_kind {
725            EntryKind::Variable(dap) => dap,
726            EntryKind::Scope(_) => {
727                debug_panic!("Called render variable on variable list entry kind scope");
728                return div().into_any_element();
729            }
730        };
731
732        let syntax_color_for = |name| cx.theme().syntax().get(name).color;
733        let variable_name_color = if self.disabled {
734            Some(Color::Disabled.color(cx))
735        } else {
736            match &dap
737                .presentation_hint
738                .as_ref()
739                .and_then(|hint| hint.kind.as_ref())
740                .unwrap_or(&VariablePresentationHintKind::Unknown)
741            {
742                VariablePresentationHintKind::Class
743                | VariablePresentationHintKind::BaseClass
744                | VariablePresentationHintKind::InnerClass
745                | VariablePresentationHintKind::MostDerivedClass => syntax_color_for("type"),
746                VariablePresentationHintKind::Data => syntax_color_for("variable"),
747                VariablePresentationHintKind::Unknown | _ => syntax_color_for("variable"),
748            }
749        };
750        let variable_color = self
751            .disabled
752            .then(|| Color::Disabled.color(cx))
753            .or_else(|| syntax_color_for("variable.special"));
754
755        let var_ref = dap.variables_reference;
756        let colors = get_entry_color(cx);
757        let is_selected = self
758            .selection
759            .as_ref()
760            .is_some_and(|selected_path| *selected_path == variable.path);
761
762        let bg_hover_color = if !is_selected {
763            colors.hover
764        } else {
765            colors.default
766        };
767        let border_color = if is_selected && self.focus_handle.contains_focused(window, cx) {
768            colors.marked_active
769        } else {
770            colors.default
771        };
772        let path = variable.path.clone();
773        div()
774            .id(variable.item_id())
775            .group("variable_list_entry")
776            .pl_2()
777            .border_1()
778            .border_r_2()
779            .border_color(border_color)
780            .h_4()
781            .size_full()
782            .hover(|style| style.bg(bg_hover_color))
783            .on_click(cx.listener({
784                move |this, _, _window, cx| {
785                    this.selection = Some(path.clone());
786                    cx.notify();
787                }
788            }))
789            .child(
790                ListItem::new(SharedString::from(format!(
791                    "variable-item-{}-{}",
792                    dap.name, state.depth
793                )))
794                .disabled(self.disabled)
795                .selectable(false)
796                .indent_level(state.depth)
797                .indent_step_size(px(10.))
798                .always_show_disclosure_icon(true)
799                .when(var_ref > 0, |list_item| {
800                    list_item.toggle(state.is_expanded).on_toggle(cx.listener({
801                        let var_path = variable.path.clone();
802                        move |this, _, _, cx| {
803                            this.session.update(cx, |session, cx| {
804                                session.variables(var_ref, cx);
805                            });
806
807                            this.toggle_entry(&var_path, cx);
808                        }
809                    }))
810                })
811                .on_secondary_mouse_down(cx.listener({
812                    let variable = variable.clone();
813                    move |this, event: &MouseDownEvent, window, cx| {
814                        this.deploy_variable_context_menu(
815                            variable.clone(),
816                            event.position,
817                            window,
818                            cx,
819                        )
820                    }
821                }))
822                .child(
823                    h_flex()
824                        .gap_1()
825                        .text_ui_sm(cx)
826                        .w_full()
827                        .child(
828                            Label::new(&dap.name).when_some(variable_name_color, |this, color| {
829                                this.color(Color::from(color))
830                            }),
831                        )
832                        .when(!dap.value.is_empty(), |this| {
833                            this.child(div().w_full().id(variable.item_value_id()).map(|this| {
834                                if let Some((_, editor)) = self
835                                    .edited_path
836                                    .as_ref()
837                                    .filter(|(path, _)| path == &variable.path)
838                                {
839                                    this.child(div().size_full().px_2().child(editor.clone()))
840                                } else {
841                                    this.text_color(cx.theme().colors().text_muted)
842                                        .when(
843                                            !self.disabled
844                                                && self
845                                                    .session
846                                                    .read(cx)
847                                                    .capabilities()
848                                                    .supports_set_variable
849                                                    .unwrap_or_default(),
850                                            |this| {
851                                                let path = variable.path.clone();
852                                                let variable_value = dap.value.clone();
853                                                this.on_click(cx.listener(
854                                                    move |this, click: &ClickEvent, window, cx| {
855                                                        if click.down.click_count < 2 {
856                                                            return;
857                                                        }
858                                                        let editor = Self::create_variable_editor(
859                                                            &variable_value,
860                                                            window,
861                                                            cx,
862                                                        );
863                                                        this.edited_path =
864                                                            Some((path.clone(), editor));
865
866                                                        cx.notify();
867                                                    },
868                                                ))
869                                            },
870                                        )
871                                        .child(
872                                            Label::new(format!("=  {}", &dap.value))
873                                                .single_line()
874                                                .truncate()
875                                                .size(LabelSize::Small)
876                                                .color(Color::Muted)
877                                                .when_some(variable_color, |this, color| {
878                                                    this.color(Color::from(color))
879                                                }),
880                                        )
881                                }
882                            }))
883                        }),
884                ),
885            )
886            .into_any()
887    }
888
889    fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Stateful<Div> {
890        div()
891            .occlude()
892            .id("variable-list-vertical-scrollbar")
893            .on_mouse_move(cx.listener(|_, _, _, cx| {
894                cx.notify();
895                cx.stop_propagation()
896            }))
897            .on_hover(|_, _, cx| {
898                cx.stop_propagation();
899            })
900            .on_any_mouse_down(|_, _, cx| {
901                cx.stop_propagation();
902            })
903            .on_mouse_up(
904                MouseButton::Left,
905                cx.listener(|_, _, _, cx| {
906                    cx.stop_propagation();
907                }),
908            )
909            .on_scroll_wheel(cx.listener(|_, _, _, cx| {
910                cx.notify();
911            }))
912            .h_full()
913            .absolute()
914            .right_1()
915            .top_1()
916            .bottom_0()
917            .w(px(12.))
918            .cursor_default()
919            .children(Scrollbar::vertical(self.scrollbar_state.clone()))
920    }
921}
922
923impl Focusable for VariableList {
924    fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
925        self.focus_handle.clone()
926    }
927}
928
929impl Render for VariableList {
930    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
931        self.build_entries(cx);
932
933        v_flex()
934            .track_focus(&self.focus_handle)
935            .key_context("VariableList")
936            .id("variable-list")
937            .group("variable-list")
938            .overflow_y_scroll()
939            .size_full()
940            .on_action(cx.listener(Self::select_first))
941            .on_action(cx.listener(Self::select_last))
942            .on_action(cx.listener(Self::select_prev))
943            .on_action(cx.listener(Self::select_next))
944            .on_action(cx.listener(Self::expand_selected_entry))
945            .on_action(cx.listener(Self::collapse_selected_entry))
946            .on_action(cx.listener(Self::cancel_variable_edit))
947            .on_action(cx.listener(Self::confirm_variable_edit))
948            //
949            .child(
950                uniform_list(
951                    cx.entity().clone(),
952                    "variable-list",
953                    self.entries.len(),
954                    move |this, range, window, cx| this.render_entries(range, window, cx),
955                )
956                .track_scroll(self.list_handle.clone())
957                .gap_1_5()
958                .size_full()
959                .flex_grow(),
960            )
961            .children(self.open_context_menu.as_ref().map(|(menu, position, _)| {
962                deferred(
963                    anchored()
964                        .position(*position)
965                        .anchor(gpui::Corner::TopLeft)
966                        .child(menu.clone()),
967                )
968                .with_priority(1)
969            }))
970            .child(self.render_vertical_scrollbar(cx))
971    }
972}
973
974struct EntryColors {
975    default: Hsla,
976    hover: Hsla,
977    marked_active: Hsla,
978}
979
980fn get_entry_color(cx: &Context<VariableList>) -> EntryColors {
981    let colors = cx.theme().colors();
982
983    EntryColors {
984        default: colors.panel_background,
985        hover: colors.ghost_element_hover,
986        marked_active: colors.ghost_element_selected,
987    }
988}