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