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 .border_1()
679 .border_r_2()
680 .border_color(border_color)
681 .flex()
682 .w_full()
683 .h_full()
684 .hover(|style| style.bg(bg_hover_color))
685 .on_click(cx.listener({
686 move |this, _, _window, cx| {
687 this.selection = Some(path.clone());
688 cx.notify();
689 }
690 }))
691 .child(
692 ListItem::new(SharedString::from(format!("scope-{}", var_ref)))
693 .selectable(false)
694 .disabled(self.disabled)
695 .indent_level(state.depth + 1)
696 .indent_step_size(px(20.))
697 .always_show_disclosure_icon(true)
698 .toggle(state.is_expanded)
699 .on_toggle({
700 let var_path = entry.path.clone();
701 cx.listener(move |this, _, _, cx| this.toggle_entry(&var_path, cx))
702 })
703 .child(
704 div()
705 .text_ui(cx)
706 .w_full()
707 .when(self.disabled, |this| {
708 this.text_color(Color::Disabled.color(cx))
709 })
710 .child(scope.name.clone()),
711 ),
712 )
713 .into_any()
714 }
715
716 fn render_variable(
717 &self,
718 variable: &ListEntry,
719 state: EntryState,
720 window: &mut Window,
721 cx: &mut Context<Self>,
722 ) -> AnyElement {
723 let dap = match &variable.dap_kind {
724 EntryKind::Variable(dap) => dap,
725 EntryKind::Scope(_) => {
726 debug_panic!("Called render variable on variable list entry kind scope");
727 return div().into_any_element();
728 }
729 };
730
731 let syntax_color_for = |name| cx.theme().syntax().get(name).color;
732 let variable_name_color = if self.disabled {
733 Some(Color::Disabled.color(cx))
734 } else {
735 match &dap
736 .presentation_hint
737 .as_ref()
738 .and_then(|hint| hint.kind.as_ref())
739 .unwrap_or(&VariablePresentationHintKind::Unknown)
740 {
741 VariablePresentationHintKind::Class
742 | VariablePresentationHintKind::BaseClass
743 | VariablePresentationHintKind::InnerClass
744 | VariablePresentationHintKind::MostDerivedClass => syntax_color_for("type"),
745 VariablePresentationHintKind::Data => syntax_color_for("variable"),
746 VariablePresentationHintKind::Unknown | _ => syntax_color_for("variable"),
747 }
748 };
749 let variable_color = self
750 .disabled
751 .then(|| Color::Disabled.color(cx))
752 .or_else(|| syntax_color_for("variable.special"));
753
754 let var_ref = dap.variables_reference;
755 let colors = get_entry_color(cx);
756 let is_selected = self
757 .selection
758 .as_ref()
759 .is_some_and(|selected_path| *selected_path == variable.path);
760
761 let bg_hover_color = if !is_selected {
762 colors.hover
763 } else {
764 colors.default
765 };
766 let border_color = if is_selected && self.focus_handle.contains_focused(window, cx) {
767 colors.marked_active
768 } else {
769 colors.default
770 };
771 let path = variable.path.clone();
772 div()
773 .id(variable.item_id())
774 .group("variable_list_entry")
775 .border_1()
776 .border_r_2()
777 .border_color(border_color)
778 .h_4()
779 .size_full()
780 .hover(|style| style.bg(bg_hover_color))
781 .on_click(cx.listener({
782 move |this, _, _window, cx| {
783 this.selection = Some(path.clone());
784 cx.notify();
785 }
786 }))
787 .child(
788 ListItem::new(SharedString::from(format!(
789 "variable-item-{}-{}",
790 dap.name, state.depth
791 )))
792 .disabled(self.disabled)
793 .selectable(false)
794 .indent_level(state.depth + 1_usize)
795 .indent_step_size(px(20.))
796 .always_show_disclosure_icon(true)
797 .when(var_ref > 0, |list_item| {
798 list_item.toggle(state.is_expanded).on_toggle(cx.listener({
799 let var_path = variable.path.clone();
800 move |this, _, _, cx| {
801 this.session.update(cx, |session, cx| {
802 session.variables(var_ref, cx);
803 });
804
805 this.toggle_entry(&var_path, cx);
806 }
807 }))
808 })
809 .on_secondary_mouse_down(cx.listener({
810 let variable = variable.clone();
811 move |this, event: &MouseDownEvent, window, cx| {
812 this.deploy_variable_context_menu(
813 variable.clone(),
814 event.position,
815 window,
816 cx,
817 )
818 }
819 }))
820 .child(
821 h_flex()
822 .gap_1()
823 .text_ui_sm(cx)
824 .w_full()
825 .child(
826 Label::new(&dap.name).when_some(variable_name_color, |this, color| {
827 this.color(Color::from(color))
828 }),
829 )
830 .when(!dap.value.is_empty(), |this| {
831 this.child(div().w_full().id(variable.item_value_id()).map(|this| {
832 if let Some((_, editor)) = self
833 .edited_path
834 .as_ref()
835 .filter(|(path, _)| path == &variable.path)
836 {
837 this.child(div().size_full().px_2().child(editor.clone()))
838 } else {
839 this.text_color(cx.theme().colors().text_muted)
840 .when(
841 !self.disabled
842 && self
843 .session
844 .read(cx)
845 .capabilities()
846 .supports_set_variable
847 .unwrap_or_default(),
848 |this| {
849 let path = variable.path.clone();
850 let variable_value = dap.value.clone();
851 this.on_click(cx.listener(
852 move |this, click: &ClickEvent, window, cx| {
853 if click.down.click_count < 2 {
854 return;
855 }
856 let editor = Self::create_variable_editor(
857 &variable_value,
858 window,
859 cx,
860 );
861 this.edited_path =
862 Some((path.clone(), editor));
863
864 cx.notify();
865 },
866 ))
867 },
868 )
869 .child(
870 Label::new(format!("= {}", &dap.value))
871 .single_line()
872 .truncate()
873 .size(LabelSize::Small)
874 .color(Color::Muted)
875 .when_some(variable_color, |this, color| {
876 this.color(Color::from(color))
877 }),
878 )
879 }
880 }))
881 }),
882 ),
883 )
884 .into_any()
885 }
886
887 fn render_vertical_scrollbar(&self, cx: &mut Context<Self>) -> Stateful<Div> {
888 div()
889 .occlude()
890 .id("variable-list-vertical-scrollbar")
891 .on_mouse_move(cx.listener(|_, _, _, cx| {
892 cx.notify();
893 cx.stop_propagation()
894 }))
895 .on_hover(|_, _, cx| {
896 cx.stop_propagation();
897 })
898 .on_any_mouse_down(|_, _, cx| {
899 cx.stop_propagation();
900 })
901 .on_mouse_up(
902 MouseButton::Left,
903 cx.listener(|_, _, _, cx| {
904 cx.stop_propagation();
905 }),
906 )
907 .on_scroll_wheel(cx.listener(|_, _, _, cx| {
908 cx.notify();
909 }))
910 .h_full()
911 .absolute()
912 .right_1()
913 .top_1()
914 .bottom_0()
915 .w(px(12.))
916 .cursor_default()
917 .children(Scrollbar::vertical(self.scrollbar_state.clone()))
918 }
919}
920
921impl Focusable for VariableList {
922 fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
923 self.focus_handle.clone()
924 }
925}
926
927impl Render for VariableList {
928 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
929 self.build_entries(cx);
930
931 v_flex()
932 .track_focus(&self.focus_handle)
933 .key_context("VariableList")
934 .id("variable-list")
935 .group("variable-list")
936 .overflow_y_scroll()
937 .size_full()
938 .on_action(cx.listener(Self::select_first))
939 .on_action(cx.listener(Self::select_last))
940 .on_action(cx.listener(Self::select_prev))
941 .on_action(cx.listener(Self::select_next))
942 .on_action(cx.listener(Self::expand_selected_entry))
943 .on_action(cx.listener(Self::collapse_selected_entry))
944 .on_action(cx.listener(Self::cancel_variable_edit))
945 .on_action(cx.listener(Self::confirm_variable_edit))
946 //
947 .child(
948 uniform_list(
949 cx.entity().clone(),
950 "variable-list",
951 self.entries.len(),
952 move |this, range, window, cx| this.render_entries(range, window, cx),
953 )
954 .track_scroll(self.list_handle.clone())
955 .gap_1_5()
956 .size_full()
957 .flex_grow(),
958 )
959 .children(self.open_context_menu.as_ref().map(|(menu, position, _)| {
960 deferred(
961 anchored()
962 .position(*position)
963 .anchor(gpui::Corner::TopLeft)
964 .child(menu.clone()),
965 )
966 .with_priority(1)
967 }))
968 .child(self.render_vertical_scrollbar(cx))
969 }
970}
971
972struct EntryColors {
973 default: Hsla,
974 hover: Hsla,
975 marked_active: Hsla,
976}
977
978fn get_entry_color(cx: &Context<VariableList>) -> EntryColors {
979 let colors = cx.theme().colors();
980
981 EntryColors {
982 default: colors.panel_background,
983 hover: colors.ghost_element_hover,
984 marked_active: colors.ghost_element_selected,
985 }
986}