1use anyhow::{Context as _, bail};
2use collections::{FxHashMap, HashMap};
3use language::LanguageRegistry;
4use std::{
5 borrow::Cow,
6 path::{Path, PathBuf},
7 sync::Arc,
8 usize,
9};
10use tasks_ui::{TaskOverrides, TasksModal};
11
12use dap::{
13 DapRegistry, DebugRequest, TelemetrySpawnLocation, adapters::DebugAdapterName, send_telemetry,
14};
15use editor::{Editor, EditorElement, EditorStyle};
16use fuzzy::{StringMatch, StringMatchCandidate};
17use gpui::{
18 Action, App, AppContext, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable,
19 KeyContext, Render, Subscription, Task, TextStyle, WeakEntity,
20};
21use itertools::Itertools as _;
22use picker::{Picker, PickerDelegate, highlighted_match_with_paths::HighlightedMatch};
23use project::{DebugScenarioContext, TaskContexts, TaskSourceKind, task_store::TaskStore};
24use settings::Settings;
25use task::{DebugScenario, RevealTarget, ZedDebugConfig};
26use theme::ThemeSettings;
27use ui::{
28 ActiveTheme, Button, ButtonCommon, ButtonSize, CheckboxWithLabel, Clickable, Color, Context,
29 ContextMenu, Disableable, DropdownMenu, FluentBuilder, Icon, IconName, IconSize,
30 IconWithIndicator, Indicator, InteractiveElement, IntoElement, KeyBinding, Label,
31 LabelCommon as _, LabelSize, ListItem, ListItemSpacing, ParentElement, RenderOnce,
32 SharedString, Styled, StyledExt, ToggleButton, ToggleState, Toggleable, Tooltip, Window, div,
33 h_flex, relative, rems, v_flex,
34};
35use util::ResultExt;
36use workspace::{ModalView, Workspace, notifications::DetachAndPromptErr, pane};
37
38use crate::{attach_modal::AttachModal, debugger_panel::DebugPanel};
39
40pub(super) struct NewProcessModal {
41 workspace: WeakEntity<Workspace>,
42 debug_panel: WeakEntity<DebugPanel>,
43 mode: NewProcessMode,
44 debug_picker: Entity<Picker<DebugDelegate>>,
45 attach_mode: Entity<AttachMode>,
46 configure_mode: Entity<ConfigureMode>,
47 task_mode: TaskMode,
48 debugger: Option<DebugAdapterName>,
49 _subscriptions: [Subscription; 3],
50}
51
52fn suggested_label(request: &DebugRequest, debugger: &str) -> SharedString {
53 match request {
54 DebugRequest::Launch(config) => {
55 let last_path_component = Path::new(&config.program)
56 .file_name()
57 .map(|name| name.to_string_lossy())
58 .unwrap_or_else(|| Cow::Borrowed(&config.program));
59
60 format!("{} ({debugger})", last_path_component).into()
61 }
62 DebugRequest::Attach(config) => format!(
63 "pid: {} ({debugger})",
64 config.process_id.unwrap_or(u32::MAX)
65 )
66 .into(),
67 }
68}
69
70impl NewProcessModal {
71 pub(super) fn show(
72 workspace: &mut Workspace,
73 window: &mut Window,
74 mode: NewProcessMode,
75 reveal_target: Option<RevealTarget>,
76 cx: &mut Context<Workspace>,
77 ) {
78 let Some(debug_panel) = workspace.panel::<DebugPanel>(cx) else {
79 return;
80 };
81 let task_store = workspace.project().read(cx).task_store().clone();
82 let languages = workspace.app_state().languages.clone();
83
84 cx.spawn_in(window, async move |workspace, cx| {
85 let task_contexts = workspace.update_in(cx, |workspace, window, cx| {
86 // todo(debugger): get the buffer here (if the active item is an editor) and store it so we can pass it to start_session later
87 tasks_ui::task_contexts(workspace, window, cx)
88 })?;
89 workspace.update_in(cx, |workspace, window, cx| {
90 let workspace_handle = workspace.weak_handle();
91 workspace.toggle_modal(window, cx, |window, cx| {
92 let attach_mode = AttachMode::new(None, workspace_handle.clone(), window, cx);
93
94 let debug_picker = cx.new(|cx| {
95 let delegate =
96 DebugDelegate::new(debug_panel.downgrade(), task_store.clone());
97 Picker::uniform_list(delegate, window, cx).modal(false)
98 });
99
100 let configure_mode = ConfigureMode::new(window, cx);
101
102 let task_overrides = Some(TaskOverrides { reveal_target });
103
104 let task_mode = TaskMode {
105 task_modal: cx.new(|cx| {
106 TasksModal::new(
107 task_store.clone(),
108 Arc::new(TaskContexts::default()),
109 task_overrides,
110 false,
111 workspace_handle.clone(),
112 window,
113 cx,
114 )
115 }),
116 };
117
118 let _subscriptions = [
119 cx.subscribe(&debug_picker, |_, _, _, cx| {
120 cx.emit(DismissEvent);
121 }),
122 cx.subscribe(
123 &attach_mode.read(cx).attach_picker.clone(),
124 |_, _, _, cx| {
125 cx.emit(DismissEvent);
126 },
127 ),
128 cx.subscribe(&task_mode.task_modal, |_, _, _: &DismissEvent, cx| {
129 cx.emit(DismissEvent)
130 }),
131 ];
132
133 cx.spawn_in(window, {
134 let debug_picker = debug_picker.downgrade();
135 let configure_mode = configure_mode.downgrade();
136 let task_modal = task_mode.task_modal.downgrade();
137 let workspace = workspace_handle.clone();
138
139 async move |this, cx| {
140 let task_contexts = task_contexts.await;
141 let task_contexts = Arc::new(task_contexts);
142 let lsp_task_sources = task_contexts.lsp_task_sources.clone();
143 let task_position = task_contexts.latest_selection;
144 // Get LSP tasks and filter out based on language vs lsp preference
145 let (lsp_tasks, prefer_lsp) =
146 workspace.update(cx, |workspace, cx| {
147 let lsp_tasks = editor::lsp_tasks(
148 workspace.project().clone(),
149 &lsp_task_sources,
150 task_position,
151 cx,
152 );
153 let prefer_lsp = workspace
154 .active_item(cx)
155 .and_then(|item| item.downcast::<Editor>())
156 .map(|editor| {
157 editor
158 .read(cx)
159 .buffer()
160 .read(cx)
161 .language_settings(cx)
162 .tasks
163 .prefer_lsp
164 })
165 .unwrap_or(false);
166 (lsp_tasks, prefer_lsp)
167 })?;
168
169 let lsp_tasks = lsp_tasks.await;
170 let add_current_language_tasks = !prefer_lsp || lsp_tasks.is_empty();
171
172 let lsp_tasks = lsp_tasks
173 .into_iter()
174 .flat_map(|(kind, tasks_with_locations)| {
175 tasks_with_locations
176 .into_iter()
177 .sorted_by_key(|(location, task)| {
178 (location.is_none(), task.resolved_label.clone())
179 })
180 .map(move |(_, task)| (kind.clone(), task))
181 })
182 .collect::<Vec<_>>();
183
184 let Some(task_inventory) = task_store
185 .update(cx, |task_store, _| task_store.task_inventory().cloned())?
186 else {
187 return Ok(());
188 };
189
190 let (used_tasks, current_resolved_tasks) = task_inventory
191 .update(cx, |task_inventory, cx| {
192 task_inventory
193 .used_and_current_resolved_tasks(task_contexts.clone(), cx)
194 })?
195 .await;
196
197 if let Ok(task) = debug_picker.update(cx, |picker, cx| {
198 picker.delegate.tasks_loaded(
199 task_contexts.clone(),
200 languages,
201 lsp_tasks.clone(),
202 current_resolved_tasks.clone(),
203 add_current_language_tasks,
204 cx,
205 )
206 }) {
207 task.await;
208 debug_picker
209 .update_in(cx, |picker, window, cx| {
210 picker.refresh(window, cx);
211 cx.notify();
212 })
213 .ok();
214 }
215
216 if let Some(active_cwd) = task_contexts
217 .active_context()
218 .and_then(|context| context.cwd.clone())
219 {
220 configure_mode
221 .update_in(cx, |configure_mode, window, cx| {
222 configure_mode.load(active_cwd, window, cx);
223 })
224 .ok();
225 }
226
227 task_modal
228 .update_in(cx, |task_modal, window, cx| {
229 task_modal.tasks_loaded(
230 task_contexts,
231 lsp_tasks,
232 used_tasks,
233 current_resolved_tasks,
234 add_current_language_tasks,
235 window,
236 cx,
237 );
238 })
239 .ok();
240
241 this.update(cx, |_, cx| {
242 cx.notify();
243 })
244 .ok();
245
246 anyhow::Ok(())
247 }
248 })
249 .detach();
250
251 Self {
252 debug_picker,
253 attach_mode,
254 configure_mode,
255 task_mode,
256 debugger: None,
257 mode,
258 debug_panel: debug_panel.downgrade(),
259 workspace: workspace_handle,
260 _subscriptions,
261 }
262 });
263 })?;
264
265 anyhow::Ok(())
266 })
267 .detach();
268 }
269
270 fn render_mode(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl ui::IntoElement {
271 let dap_menu = self.adapter_drop_down_menu(window, cx);
272 match self.mode {
273 NewProcessMode::Task => self
274 .task_mode
275 .task_modal
276 .read(cx)
277 .picker
278 .clone()
279 .into_any_element(),
280 NewProcessMode::Attach => self.attach_mode.update(cx, |this, cx| {
281 this.clone().render(window, cx).into_any_element()
282 }),
283 NewProcessMode::Launch => self.configure_mode.update(cx, |this, cx| {
284 this.clone().render(dap_menu, window, cx).into_any_element()
285 }),
286 NewProcessMode::Debug => v_flex()
287 .w(rems(34.))
288 .child(self.debug_picker.clone())
289 .into_any_element(),
290 }
291 }
292
293 fn mode_focus_handle(&self, cx: &App) -> FocusHandle {
294 match self.mode {
295 NewProcessMode::Task => self.task_mode.task_modal.focus_handle(cx),
296 NewProcessMode::Attach => self.attach_mode.read(cx).attach_picker.focus_handle(cx),
297 NewProcessMode::Launch => self.configure_mode.read(cx).program.focus_handle(cx),
298 NewProcessMode::Debug => self.debug_picker.focus_handle(cx),
299 }
300 }
301
302 fn debug_scenario(&self, debugger: &str, cx: &App) -> Task<Option<DebugScenario>> {
303 let request = match self.mode {
304 NewProcessMode::Launch => {
305 DebugRequest::Launch(self.configure_mode.read(cx).debug_request(cx))
306 }
307 NewProcessMode::Attach => {
308 DebugRequest::Attach(self.attach_mode.read(cx).debug_request())
309 }
310 _ => return Task::ready(None),
311 };
312 let label = suggested_label(&request, debugger);
313
314 let stop_on_entry = if let NewProcessMode::Launch = &self.mode {
315 Some(self.configure_mode.read(cx).stop_on_entry.selected())
316 } else {
317 None
318 };
319
320 let session_scenario = ZedDebugConfig {
321 adapter: debugger.to_owned().into(),
322 label,
323 request,
324 stop_on_entry,
325 };
326
327 let adapter = cx
328 .global::<DapRegistry>()
329 .adapter(&session_scenario.adapter);
330
331 cx.spawn(async move |_| adapter?.config_from_zed_format(session_scenario).await.ok())
332 }
333
334 fn start_new_session(&mut self, window: &mut Window, cx: &mut Context<Self>) {
335 if self.debugger.as_ref().is_none() {
336 return;
337 }
338
339 if let NewProcessMode::Debug = &self.mode {
340 self.debug_picker.update(cx, |picker, cx| {
341 picker.delegate.confirm(false, window, cx);
342 });
343 return;
344 }
345
346 if let NewProcessMode::Launch = &self.mode {
347 if self.configure_mode.read(cx).save_to_debug_json.selected() {
348 self.save_debug_scenario(window, cx);
349 }
350 }
351
352 let Some(debugger) = self.debugger.clone() else {
353 return;
354 };
355
356 let debug_panel = self.debug_panel.clone();
357 let Some(task_contexts) = self.task_contexts(cx) else {
358 return;
359 };
360
361 let task_context = task_contexts.active_context().cloned().unwrap_or_default();
362 let worktree_id = task_contexts.worktree();
363 let mode = self.mode;
364 cx.spawn_in(window, async move |this, cx| {
365 let Some(config) = this
366 .update(cx, |this, cx| this.debug_scenario(&debugger, cx))?
367 .await
368 else {
369 bail!("debug config not found in mode: {mode}");
370 };
371
372 debug_panel.update_in(cx, |debug_panel, window, cx| {
373 send_telemetry(&config, TelemetrySpawnLocation::Custom, cx);
374 debug_panel.start_session(config, task_context, None, worktree_id, window, cx)
375 })?;
376 this.update(cx, |_, cx| {
377 cx.emit(DismissEvent);
378 })
379 .ok();
380 anyhow::Ok(())
381 })
382 .detach_and_log_err(cx);
383 }
384
385 fn update_attach_picker(
386 attach: &Entity<AttachMode>,
387 adapter: &DebugAdapterName,
388 window: &mut Window,
389 cx: &mut App,
390 ) {
391 attach.update(cx, |this, cx| {
392 if adapter.0 != this.definition.adapter {
393 this.definition.adapter = adapter.0.clone();
394
395 this.attach_picker.update(cx, |this, cx| {
396 this.picker.update(cx, |this, cx| {
397 this.delegate.definition.adapter = adapter.0.clone();
398 this.focus(window, cx);
399 })
400 });
401 }
402
403 cx.notify();
404 })
405 }
406
407 fn task_contexts(&self, cx: &App) -> Option<Arc<TaskContexts>> {
408 self.debug_picker.read(cx).delegate.task_contexts.clone()
409 }
410
411 pub fn save_debug_scenario(&mut self, window: &mut Window, cx: &mut Context<Self>) {
412 let task_contexts = self.task_contexts(cx);
413 let Some(adapter) = self.debugger.as_ref() else {
414 return;
415 };
416 let scenario = self.debug_scenario(&adapter, cx);
417 cx.spawn_in(window, async move |this, cx| {
418 let scenario = scenario.await.context("no scenario to save")?;
419 let worktree_id = task_contexts
420 .context("no task contexts")?
421 .worktree()
422 .context("no active worktree")?;
423 this.update_in(cx, |this, window, cx| {
424 this.debug_panel.update(cx, |panel, cx| {
425 panel.save_scenario(scenario, worktree_id, window, cx)
426 })
427 })??
428 .await?;
429 this.update_in(cx, |_, _, cx| {
430 cx.emit(DismissEvent);
431 })
432 })
433 .detach_and_prompt_err("Failed to edit debug.json", window, cx, |_, _, _| None);
434 }
435
436 fn adapter_drop_down_menu(
437 &mut self,
438 window: &mut Window,
439 cx: &mut Context<Self>,
440 ) -> ui::DropdownMenu {
441 let workspace = self.workspace.clone();
442 let weak = cx.weak_entity();
443 let active_buffer = self.task_contexts(cx).and_then(|tc| {
444 tc.active_item_context
445 .as_ref()
446 .and_then(|aic| aic.1.as_ref().map(|l| l.buffer.clone()))
447 });
448
449 let active_buffer_language = active_buffer
450 .and_then(|buffer| buffer.read(cx).language())
451 .cloned();
452
453 let mut available_adapters = workspace
454 .update(cx, |_, cx| DapRegistry::global(cx).enumerate_adapters())
455 .unwrap_or_default();
456 if let Some(language) = active_buffer_language {
457 available_adapters.sort_by_key(|adapter| {
458 language
459 .config()
460 .debuggers
461 .get_index_of(adapter.0.as_ref())
462 .unwrap_or(usize::MAX)
463 });
464 if self.debugger.is_none() {
465 self.debugger = available_adapters.first().cloned();
466 }
467 }
468
469 let label = self
470 .debugger
471 .as_ref()
472 .map(|d| d.0.clone())
473 .unwrap_or_else(|| SELECT_DEBUGGER_LABEL.clone());
474
475 DropdownMenu::new(
476 "dap-adapter-picker",
477 label,
478 ContextMenu::build(window, cx, move |mut menu, _, _| {
479 let setter_for_name = |name: DebugAdapterName| {
480 let weak = weak.clone();
481 move |window: &mut Window, cx: &mut App| {
482 weak.update(cx, |this, cx| {
483 this.debugger = Some(name.clone());
484 cx.notify();
485 if let NewProcessMode::Attach = &this.mode {
486 Self::update_attach_picker(&this.attach_mode, &name, window, cx);
487 }
488 })
489 .ok();
490 }
491 };
492
493 for adapter in available_adapters.into_iter() {
494 menu = menu.entry(adapter.0.clone(), None, setter_for_name(adapter.clone()));
495 }
496
497 menu
498 }),
499 )
500 }
501}
502
503static SELECT_DEBUGGER_LABEL: SharedString = SharedString::new_static("Select Debugger");
504
505#[derive(Clone, Copy)]
506pub(crate) enum NewProcessMode {
507 Task,
508 Launch,
509 Attach,
510 Debug,
511}
512
513impl std::fmt::Display for NewProcessMode {
514 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
515 let mode = match self {
516 NewProcessMode::Task => "Run",
517 NewProcessMode::Debug => "Debug",
518 NewProcessMode::Attach => "Attach",
519 NewProcessMode::Launch => "Launch",
520 };
521
522 write!(f, "{}", mode)
523 }
524}
525
526impl Focusable for NewProcessMode {
527 fn focus_handle(&self, cx: &App) -> FocusHandle {
528 cx.focus_handle()
529 }
530}
531
532fn render_editor(editor: &Entity<Editor>, window: &mut Window, cx: &App) -> impl IntoElement {
533 let settings = ThemeSettings::get_global(cx);
534 let theme = cx.theme();
535
536 let text_style = TextStyle {
537 color: cx.theme().colors().text,
538 font_family: settings.buffer_font.family.clone(),
539 font_features: settings.buffer_font.features.clone(),
540 font_size: settings.buffer_font_size(cx).into(),
541 font_weight: settings.buffer_font.weight,
542 line_height: relative(settings.buffer_line_height.value()),
543 background_color: Some(theme.colors().editor_background),
544 ..Default::default()
545 };
546
547 let element = EditorElement::new(
548 editor,
549 EditorStyle {
550 background: theme.colors().editor_background,
551 local_player: theme.players().local(),
552 text: text_style,
553 ..Default::default()
554 },
555 );
556
557 div()
558 .rounded_md()
559 .p_1()
560 .border_1()
561 .border_color(theme.colors().border_variant)
562 .when(
563 editor.focus_handle(cx).contains_focused(window, cx),
564 |this| this.border_color(theme.colors().border_focused),
565 )
566 .child(element)
567 .bg(theme.colors().editor_background)
568}
569
570impl Render for NewProcessModal {
571 fn render(
572 &mut self,
573 window: &mut ui::Window,
574 cx: &mut ui::Context<Self>,
575 ) -> impl ui::IntoElement {
576 v_flex()
577 .key_context({
578 let mut key_context = KeyContext::new_with_defaults();
579 key_context.add("Pane");
580 key_context.add("RunModal");
581 key_context
582 })
583 .size_full()
584 .w(rems(34.))
585 .elevation_3(cx)
586 .overflow_hidden()
587 .on_action(cx.listener(|_, _: &menu::Cancel, _, cx| {
588 cx.emit(DismissEvent);
589 }))
590 .on_action(cx.listener(|this, _: &pane::ActivateNextItem, window, cx| {
591 this.mode = match this.mode {
592 NewProcessMode::Task => NewProcessMode::Debug,
593 NewProcessMode::Debug => NewProcessMode::Attach,
594 NewProcessMode::Attach => NewProcessMode::Launch,
595 NewProcessMode::Launch => NewProcessMode::Task,
596 };
597
598 this.mode_focus_handle(cx).focus(window);
599 }))
600 .on_action(
601 cx.listener(|this, _: &pane::ActivatePreviousItem, window, cx| {
602 this.mode = match this.mode {
603 NewProcessMode::Task => NewProcessMode::Launch,
604 NewProcessMode::Debug => NewProcessMode::Task,
605 NewProcessMode::Attach => NewProcessMode::Debug,
606 NewProcessMode::Launch => NewProcessMode::Attach,
607 };
608
609 this.mode_focus_handle(cx).focus(window);
610 }),
611 )
612 .child(
613 h_flex()
614 .p_2()
615 .w_full()
616 .border_b_1()
617 .border_color(cx.theme().colors().border_variant)
618 .child(
619 ToggleButton::new(
620 "debugger-session-ui-tasks-button",
621 NewProcessMode::Task.to_string(),
622 )
623 .size(ButtonSize::Default)
624 .toggle_state(matches!(self.mode, NewProcessMode::Task))
625 .style(ui::ButtonStyle::Subtle)
626 .on_click(cx.listener(|this, _, window, cx| {
627 this.mode = NewProcessMode::Task;
628 this.mode_focus_handle(cx).focus(window);
629 cx.notify();
630 }))
631 .tooltip(Tooltip::text("Run predefined task"))
632 .first(),
633 )
634 .child(
635 ToggleButton::new(
636 "debugger-session-ui-launch-button",
637 NewProcessMode::Debug.to_string(),
638 )
639 .size(ButtonSize::Default)
640 .style(ui::ButtonStyle::Subtle)
641 .toggle_state(matches!(self.mode, NewProcessMode::Debug))
642 .on_click(cx.listener(|this, _, window, cx| {
643 this.mode = NewProcessMode::Debug;
644 this.mode_focus_handle(cx).focus(window);
645 cx.notify();
646 }))
647 .tooltip(Tooltip::text("Start a predefined debug scenario"))
648 .middle(),
649 )
650 .child(
651 ToggleButton::new(
652 "debugger-session-ui-attach-button",
653 NewProcessMode::Attach.to_string(),
654 )
655 .size(ButtonSize::Default)
656 .toggle_state(matches!(self.mode, NewProcessMode::Attach))
657 .style(ui::ButtonStyle::Subtle)
658 .on_click(cx.listener(|this, _, window, cx| {
659 this.mode = NewProcessMode::Attach;
660
661 if let Some(debugger) = this.debugger.as_ref() {
662 Self::update_attach_picker(
663 &this.attach_mode,
664 &debugger,
665 window,
666 cx,
667 );
668 }
669 this.mode_focus_handle(cx).focus(window);
670 cx.notify();
671 }))
672 .tooltip(Tooltip::text("Attach the debugger to a running process"))
673 .middle(),
674 )
675 .child(
676 ToggleButton::new(
677 "debugger-session-ui-custom-button",
678 NewProcessMode::Launch.to_string(),
679 )
680 .size(ButtonSize::Default)
681 .toggle_state(matches!(self.mode, NewProcessMode::Launch))
682 .style(ui::ButtonStyle::Subtle)
683 .on_click(cx.listener(|this, _, window, cx| {
684 this.mode = NewProcessMode::Launch;
685 this.mode_focus_handle(cx).focus(window);
686 cx.notify();
687 }))
688 .tooltip(Tooltip::text("Launch a new process with a debugger"))
689 .last(),
690 ),
691 )
692 .child(v_flex().child(self.render_mode(window, cx)))
693 .map(|el| {
694 let container = h_flex()
695 .w_full()
696 .p_1p5()
697 .gap_2()
698 .justify_between()
699 .border_t_1()
700 .border_color(cx.theme().colors().border_variant);
701 match self.mode {
702 NewProcessMode::Launch => el.child(
703 container
704 .child(
705 h_flex().child(
706 Button::new("edit-custom-debug", "Edit in debug.json")
707 .on_click(cx.listener(|this, _, window, cx| {
708 this.save_debug_scenario(window, cx);
709 }))
710 .disabled(
711 self.debugger.is_none()
712 || self
713 .configure_mode
714 .read(cx)
715 .program
716 .read(cx)
717 .is_empty(cx),
718 ),
719 ),
720 )
721 .child(
722 Button::new("debugger-spawn", "Start")
723 .on_click(cx.listener(|this, _, window, cx| {
724 this.start_new_session(window, cx)
725 }))
726 .disabled(
727 self.debugger.is_none()
728 || self
729 .configure_mode
730 .read(cx)
731 .program
732 .read(cx)
733 .is_empty(cx),
734 ),
735 ),
736 ),
737 NewProcessMode::Attach => el.child({
738 let disabled = self.debugger.is_none()
739 || self
740 .attach_mode
741 .read(cx)
742 .attach_picker
743 .read(cx)
744 .picker
745 .read(cx)
746 .delegate
747 .match_count()
748 == 0;
749 let secondary_action = menu::SecondaryConfirm.boxed_clone();
750 container
751 .child(div().children(
752 KeyBinding::for_action(&*secondary_action, window, cx).map(
753 |keybind| {
754 Button::new("edit-attach-task", "Edit in debug.json")
755 .label_size(LabelSize::Small)
756 .key_binding(keybind)
757 .on_click(move |_, window, cx| {
758 window.dispatch_action(
759 secondary_action.boxed_clone(),
760 cx,
761 )
762 })
763 .disabled(disabled)
764 },
765 ),
766 ))
767 .child(
768 h_flex()
769 .child(div().child(self.adapter_drop_down_menu(window, cx))),
770 )
771 }),
772 NewProcessMode::Debug => el,
773 NewProcessMode::Task => el,
774 }
775 })
776 }
777}
778
779impl EventEmitter<DismissEvent> for NewProcessModal {}
780impl Focusable for NewProcessModal {
781 fn focus_handle(&self, cx: &ui::App) -> gpui::FocusHandle {
782 self.mode_focus_handle(cx)
783 }
784}
785
786impl ModalView for NewProcessModal {}
787
788impl RenderOnce for AttachMode {
789 fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
790 v_flex()
791 .w_full()
792 .track_focus(&self.attach_picker.focus_handle(cx))
793 .child(self.attach_picker.clone())
794 }
795}
796
797#[derive(Clone)]
798pub(super) struct ConfigureMode {
799 program: Entity<Editor>,
800 cwd: Entity<Editor>,
801 stop_on_entry: ToggleState,
802 save_to_debug_json: ToggleState,
803}
804
805impl ConfigureMode {
806 pub(super) fn new(window: &mut Window, cx: &mut App) -> Entity<Self> {
807 let program = cx.new(|cx| Editor::single_line(window, cx));
808 program.update(cx, |this, cx| {
809 this.set_placeholder_text("ENV=Zed ~/bin/program --option", cx);
810 });
811
812 let cwd = cx.new(|cx| Editor::single_line(window, cx));
813 cwd.update(cx, |this, cx| {
814 this.set_placeholder_text("Ex: $ZED_WORKTREE_ROOT", cx);
815 });
816
817 cx.new(|_| Self {
818 program,
819 cwd,
820 stop_on_entry: ToggleState::Unselected,
821 save_to_debug_json: ToggleState::Unselected,
822 })
823 }
824
825 fn load(&mut self, cwd: PathBuf, window: &mut Window, cx: &mut App) {
826 self.cwd.update(cx, |editor, cx| {
827 if editor.is_empty(cx) {
828 editor.set_text(cwd.to_string_lossy(), window, cx);
829 }
830 });
831 }
832
833 pub(super) fn debug_request(&self, cx: &App) -> task::LaunchRequest {
834 let cwd_text = self.cwd.read(cx).text(cx);
835 let cwd = if cwd_text.is_empty() {
836 None
837 } else {
838 Some(PathBuf::from(cwd_text))
839 };
840
841 if cfg!(windows) {
842 return task::LaunchRequest {
843 program: self.program.read(cx).text(cx),
844 cwd,
845 args: Default::default(),
846 env: Default::default(),
847 };
848 }
849 let command = self.program.read(cx).text(cx);
850 let mut args = shlex::split(&command).into_iter().flatten().peekable();
851 let mut env = FxHashMap::default();
852 while args.peek().is_some_and(|arg| arg.contains('=')) {
853 let arg = args.next().unwrap();
854 let (lhs, rhs) = arg.split_once('=').unwrap();
855 env.insert(lhs.to_string(), rhs.to_string());
856 }
857
858 let program = if let Some(program) = args.next() {
859 program
860 } else {
861 env = FxHashMap::default();
862 command
863 };
864
865 let args = args.collect::<Vec<_>>();
866
867 task::LaunchRequest {
868 program,
869 cwd,
870 args,
871 env,
872 }
873 }
874
875 fn render(
876 &mut self,
877 adapter_menu: DropdownMenu,
878 window: &mut Window,
879 cx: &mut ui::Context<Self>,
880 ) -> impl IntoElement {
881 v_flex()
882 .p_2()
883 .w_full()
884 .gap_2()
885 .track_focus(&self.program.focus_handle(cx))
886 .child(
887 h_flex()
888 .gap_2()
889 .child(
890 Label::new("Debugger")
891 .size(LabelSize::Small)
892 .color(Color::Muted),
893 )
894 .child(adapter_menu),
895 )
896 .child(
897 v_flex()
898 .gap_0p5()
899 .child(
900 Label::new("Program")
901 .size(LabelSize::Small)
902 .color(Color::Muted),
903 )
904 .child(render_editor(&self.program, window, cx)),
905 )
906 .child(
907 v_flex()
908 .gap_0p5()
909 .child(
910 Label::new("Working Directory")
911 .size(LabelSize::Small)
912 .color(Color::Muted),
913 )
914 .child(render_editor(&self.cwd, window, cx)),
915 )
916 .child(
917 CheckboxWithLabel::new(
918 "debugger-stop-on-entry",
919 Label::new("Stop on Entry")
920 .size(LabelSize::Small)
921 .color(Color::Muted),
922 self.stop_on_entry,
923 {
924 let this = cx.weak_entity();
925 move |state, _, cx| {
926 this.update(cx, |this, _| {
927 this.stop_on_entry = *state;
928 })
929 .ok();
930 }
931 },
932 )
933 .checkbox_position(ui::IconPosition::End),
934 )
935 }
936}
937
938#[derive(Clone)]
939pub(super) struct AttachMode {
940 pub(super) definition: ZedDebugConfig,
941 pub(super) attach_picker: Entity<AttachModal>,
942}
943
944impl AttachMode {
945 pub(super) fn new(
946 debugger: Option<DebugAdapterName>,
947 workspace: WeakEntity<Workspace>,
948 window: &mut Window,
949 cx: &mut Context<NewProcessModal>,
950 ) -> Entity<Self> {
951 let definition = ZedDebugConfig {
952 adapter: debugger.unwrap_or(DebugAdapterName("".into())).0,
953 label: "Attach New Session Setup".into(),
954 request: dap::DebugRequest::Attach(task::AttachRequest { process_id: None }),
955 stop_on_entry: Some(false),
956 };
957 let attach_picker = cx.new(|cx| {
958 let modal = AttachModal::new(definition.clone(), workspace, false, window, cx);
959 window.focus(&modal.focus_handle(cx));
960
961 modal
962 });
963
964 cx.new(|_| Self {
965 definition,
966 attach_picker,
967 })
968 }
969 pub(super) fn debug_request(&self) -> task::AttachRequest {
970 task::AttachRequest { process_id: None }
971 }
972}
973
974#[derive(Clone)]
975pub(super) struct TaskMode {
976 pub(super) task_modal: Entity<TasksModal>,
977}
978
979pub(super) struct DebugDelegate {
980 task_store: Entity<TaskStore>,
981 candidates: Vec<(
982 Option<TaskSourceKind>,
983 DebugScenario,
984 Option<DebugScenarioContext>,
985 )>,
986 selected_index: usize,
987 matches: Vec<StringMatch>,
988 prompt: String,
989 debug_panel: WeakEntity<DebugPanel>,
990 task_contexts: Option<Arc<TaskContexts>>,
991 divider_index: Option<usize>,
992 last_used_candidate_index: Option<usize>,
993}
994
995impl DebugDelegate {
996 pub(super) fn new(debug_panel: WeakEntity<DebugPanel>, task_store: Entity<TaskStore>) -> Self {
997 Self {
998 task_store,
999 candidates: Vec::default(),
1000 selected_index: 0,
1001 matches: Vec::new(),
1002 prompt: String::new(),
1003 debug_panel,
1004 task_contexts: None,
1005 divider_index: None,
1006 last_used_candidate_index: None,
1007 }
1008 }
1009
1010 fn get_scenario_kind(
1011 languages: &Arc<LanguageRegistry>,
1012 dap_registry: &DapRegistry,
1013 scenario: DebugScenario,
1014 ) -> (Option<TaskSourceKind>, DebugScenario) {
1015 let language_names = languages.language_names();
1016 let language = dap_registry
1017 .adapter_language(&scenario.adapter)
1018 .map(|language| TaskSourceKind::Language { name: language.0 });
1019
1020 let language = language.or_else(|| {
1021 scenario.label.split_whitespace().find_map(|word| {
1022 language_names
1023 .iter()
1024 .find(|name| name.as_ref().eq_ignore_ascii_case(word))
1025 .map(|name| TaskSourceKind::Language {
1026 name: name.to_owned().into(),
1027 })
1028 })
1029 });
1030
1031 (language, scenario)
1032 }
1033
1034 pub fn tasks_loaded(
1035 &mut self,
1036 task_contexts: Arc<TaskContexts>,
1037 languages: Arc<LanguageRegistry>,
1038 lsp_tasks: Vec<(TaskSourceKind, task::ResolvedTask)>,
1039 current_resolved_tasks: Vec<(TaskSourceKind, task::ResolvedTask)>,
1040 add_current_language_tasks: bool,
1041 cx: &mut Context<Picker<Self>>,
1042 ) -> Task<()> {
1043 self.task_contexts = Some(task_contexts.clone());
1044 let task = self.task_store.update(cx, |task_store, cx| {
1045 task_store.task_inventory().map(|inventory| {
1046 inventory.update(cx, |inventory, cx| {
1047 inventory.list_debug_scenarios(
1048 &task_contexts,
1049 lsp_tasks,
1050 current_resolved_tasks,
1051 add_current_language_tasks,
1052 cx,
1053 )
1054 })
1055 })
1056 });
1057 cx.spawn(async move |this, cx| {
1058 let (recent, scenarios) = if let Some(task) = task {
1059 task.await
1060 } else {
1061 (Vec::new(), Vec::new())
1062 };
1063
1064 this.update(cx, |this, cx| {
1065 if !recent.is_empty() {
1066 this.delegate.last_used_candidate_index = Some(recent.len() - 1);
1067 }
1068
1069 let dap_registry = cx.global::<DapRegistry>();
1070 let hide_vscode = scenarios.iter().any(|(kind, _)| match kind {
1071 TaskSourceKind::Worktree {
1072 id: _,
1073 directory_in_worktree: dir,
1074 id_base: _,
1075 } => dir.ends_with(".zed"),
1076 _ => false,
1077 });
1078
1079 this.delegate.candidates = recent
1080 .into_iter()
1081 .map(|(scenario, context)| {
1082 let (kind, scenario) =
1083 Self::get_scenario_kind(&languages, &dap_registry, scenario);
1084 (kind, scenario, Some(context))
1085 })
1086 .chain(
1087 scenarios
1088 .into_iter()
1089 .filter(|(kind, _)| match kind {
1090 TaskSourceKind::Worktree {
1091 id: _,
1092 directory_in_worktree: dir,
1093 id_base: _,
1094 } => !(hide_vscode && dir.ends_with(".vscode")),
1095 _ => true,
1096 })
1097 .map(|(kind, scenario)| {
1098 let (language, scenario) =
1099 Self::get_scenario_kind(&languages, &dap_registry, scenario);
1100 (language.or(Some(kind)), scenario, None)
1101 }),
1102 )
1103 .collect();
1104 })
1105 .ok();
1106 })
1107 }
1108}
1109
1110impl PickerDelegate for DebugDelegate {
1111 type ListItem = ui::ListItem;
1112
1113 fn match_count(&self) -> usize {
1114 self.matches.len()
1115 }
1116
1117 fn selected_index(&self) -> usize {
1118 self.selected_index
1119 }
1120
1121 fn set_selected_index(
1122 &mut self,
1123 ix: usize,
1124 _window: &mut Window,
1125 _cx: &mut Context<picker::Picker<Self>>,
1126 ) {
1127 self.selected_index = ix;
1128 }
1129
1130 fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> std::sync::Arc<str> {
1131 "Find a debug task, or debug a command.".into()
1132 }
1133
1134 fn update_matches(
1135 &mut self,
1136 query: String,
1137 window: &mut Window,
1138 cx: &mut Context<picker::Picker<Self>>,
1139 ) -> gpui::Task<()> {
1140 let candidates = self.candidates.clone();
1141
1142 cx.spawn_in(window, async move |picker, cx| {
1143 let candidates: Vec<_> = candidates
1144 .into_iter()
1145 .enumerate()
1146 .map(|(index, (_, candidate, _))| {
1147 StringMatchCandidate::new(index, candidate.label.as_ref())
1148 })
1149 .collect();
1150
1151 let matches = fuzzy::match_strings(
1152 &candidates,
1153 &query,
1154 true,
1155 true,
1156 1000,
1157 &Default::default(),
1158 cx.background_executor().clone(),
1159 )
1160 .await;
1161
1162 picker
1163 .update(cx, |picker, _| {
1164 let delegate = &mut picker.delegate;
1165
1166 delegate.matches = matches;
1167 delegate.prompt = query;
1168
1169 delegate.divider_index = delegate.last_used_candidate_index.and_then(|index| {
1170 let index = delegate
1171 .matches
1172 .partition_point(|matching_task| matching_task.candidate_id <= index);
1173 Some(index).and_then(|index| (index != 0).then(|| index - 1))
1174 });
1175
1176 if delegate.matches.is_empty() {
1177 delegate.selected_index = 0;
1178 } else {
1179 delegate.selected_index =
1180 delegate.selected_index.min(delegate.matches.len() - 1);
1181 }
1182 })
1183 .log_err();
1184 })
1185 }
1186
1187 fn separators_after_indices(&self) -> Vec<usize> {
1188 if let Some(i) = self.divider_index {
1189 vec![i]
1190 } else {
1191 Vec::new()
1192 }
1193 }
1194
1195 fn confirm_input(&mut self, _: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
1196 let text = self.prompt.clone();
1197 let (task_context, worktree_id) = self
1198 .task_contexts
1199 .as_ref()
1200 .and_then(|task_contexts| {
1201 Some((
1202 task_contexts.active_context().cloned()?,
1203 task_contexts.worktree(),
1204 ))
1205 })
1206 .unwrap_or_default();
1207
1208 let mut args = shlex::split(&text).into_iter().flatten().peekable();
1209 let mut env = HashMap::default();
1210 while args.peek().is_some_and(|arg| arg.contains('=')) {
1211 let arg = args.next().unwrap();
1212 let (lhs, rhs) = arg.split_once('=').unwrap();
1213 env.insert(lhs.to_string(), rhs.to_string());
1214 }
1215
1216 let program = if let Some(program) = args.next() {
1217 program
1218 } else {
1219 env = HashMap::default();
1220 text
1221 };
1222
1223 let args = args.collect::<Vec<_>>();
1224 let task = task::TaskTemplate {
1225 label: "one-off".to_owned(), // TODO: rename using command as label
1226 env,
1227 command: program,
1228 args,
1229 ..Default::default()
1230 };
1231
1232 let Some(location) = self
1233 .task_contexts
1234 .as_ref()
1235 .and_then(|cx| cx.location().cloned())
1236 else {
1237 return;
1238 };
1239 let file = location.buffer.read(cx).file();
1240 let language = location.buffer.read(cx).language();
1241 let language_name = language.as_ref().map(|l| l.name());
1242 let Some(adapter): Option<DebugAdapterName> =
1243 language::language_settings::language_settings(language_name, file, cx)
1244 .debuggers
1245 .first()
1246 .map(SharedString::from)
1247 .map(Into::into)
1248 .or_else(|| {
1249 language.and_then(|l| {
1250 l.config()
1251 .debuggers
1252 .first()
1253 .map(SharedString::from)
1254 .map(Into::into)
1255 })
1256 })
1257 else {
1258 return;
1259 };
1260 let locators = cx.global::<DapRegistry>().locators();
1261 cx.spawn_in(window, async move |this, cx| {
1262 let Some(debug_scenario) = cx
1263 .background_spawn(async move {
1264 for locator in locators {
1265 if let Some(scenario) =
1266 // TODO: use a more informative label than "one-off"
1267 locator
1268 .1
1269 .create_scenario(&task, &task.label, &adapter)
1270 .await
1271 {
1272 return Some(scenario);
1273 }
1274 }
1275 None
1276 })
1277 .await
1278 else {
1279 return;
1280 };
1281
1282 this.update_in(cx, |this, window, cx| {
1283 send_telemetry(&debug_scenario, TelemetrySpawnLocation::ScenarioList, cx);
1284 this.delegate
1285 .debug_panel
1286 .update(cx, |panel, cx| {
1287 panel.start_session(
1288 debug_scenario,
1289 task_context,
1290 None,
1291 worktree_id,
1292 window,
1293 cx,
1294 );
1295 })
1296 .ok();
1297 cx.emit(DismissEvent);
1298 })
1299 .ok();
1300 })
1301 .detach();
1302 }
1303
1304 fn confirm(
1305 &mut self,
1306 secondary: bool,
1307 window: &mut Window,
1308 cx: &mut Context<picker::Picker<Self>>,
1309 ) {
1310 let debug_scenario = self
1311 .matches
1312 .get(self.selected_index())
1313 .and_then(|match_candidate| self.candidates.get(match_candidate.candidate_id).cloned());
1314
1315 let Some((kind, debug_scenario, context)) = debug_scenario else {
1316 return;
1317 };
1318
1319 let context = context.unwrap_or_else(|| {
1320 self.task_contexts
1321 .as_ref()
1322 .and_then(|task_contexts| {
1323 Some(DebugScenarioContext {
1324 task_context: task_contexts.active_context().cloned()?,
1325 active_buffer: None,
1326 worktree_id: task_contexts.worktree(),
1327 })
1328 })
1329 .unwrap_or_default()
1330 });
1331 let DebugScenarioContext {
1332 task_context,
1333 active_buffer: _,
1334 worktree_id,
1335 } = context;
1336
1337 if secondary {
1338 let Some(kind) = kind else { return };
1339 let Some(id) = worktree_id else { return };
1340 let debug_panel = self.debug_panel.clone();
1341 cx.spawn_in(window, async move |_, cx| {
1342 debug_panel
1343 .update_in(cx, |debug_panel, window, cx| {
1344 debug_panel.go_to_scenario_definition(kind, debug_scenario, id, window, cx)
1345 })?
1346 .await?;
1347 anyhow::Ok(())
1348 })
1349 .detach();
1350 } else {
1351 send_telemetry(&debug_scenario, TelemetrySpawnLocation::ScenarioList, cx);
1352 self.debug_panel
1353 .update(cx, |panel, cx| {
1354 panel.start_session(
1355 debug_scenario,
1356 task_context,
1357 None,
1358 worktree_id,
1359 window,
1360 cx,
1361 );
1362 })
1363 .ok();
1364 }
1365
1366 cx.emit(DismissEvent);
1367 }
1368
1369 fn dismissed(&mut self, _: &mut Window, cx: &mut Context<picker::Picker<Self>>) {
1370 cx.emit(DismissEvent);
1371 }
1372
1373 fn render_footer(
1374 &self,
1375 window: &mut Window,
1376 cx: &mut Context<Picker<Self>>,
1377 ) -> Option<ui::AnyElement> {
1378 let current_modifiers = window.modifiers();
1379 let footer = h_flex()
1380 .w_full()
1381 .p_1p5()
1382 .justify_between()
1383 .border_t_1()
1384 .border_color(cx.theme().colors().border_variant)
1385 .children({
1386 let action = menu::SecondaryConfirm.boxed_clone();
1387 KeyBinding::for_action(&*action, window, cx).map(|keybind| {
1388 Button::new("edit-debug-task", "Edit in debug.json")
1389 .label_size(LabelSize::Small)
1390 .key_binding(keybind)
1391 .on_click(move |_, window, cx| {
1392 window.dispatch_action(action.boxed_clone(), cx)
1393 })
1394 })
1395 })
1396 .map(|this| {
1397 if (current_modifiers.alt || self.matches.is_empty()) && !self.prompt.is_empty() {
1398 let action = picker::ConfirmInput { secondary: false }.boxed_clone();
1399 this.children(KeyBinding::for_action(&*action, window, cx).map(|keybind| {
1400 Button::new("launch-custom", "Launch Custom")
1401 .key_binding(keybind)
1402 .on_click(move |_, window, cx| {
1403 window.dispatch_action(action.boxed_clone(), cx)
1404 })
1405 }))
1406 } else {
1407 this.children(KeyBinding::for_action(&menu::Confirm, window, cx).map(
1408 |keybind| {
1409 let is_recent_selected =
1410 self.divider_index >= Some(self.selected_index);
1411 let run_entry_label =
1412 if is_recent_selected { "Rerun" } else { "Spawn" };
1413
1414 Button::new("spawn", run_entry_label)
1415 .key_binding(keybind)
1416 .on_click(|_, window, cx| {
1417 window.dispatch_action(menu::Confirm.boxed_clone(), cx);
1418 })
1419 },
1420 ))
1421 }
1422 });
1423 Some(footer.into_any_element())
1424 }
1425
1426 fn render_match(
1427 &self,
1428 ix: usize,
1429 selected: bool,
1430 window: &mut Window,
1431 cx: &mut Context<picker::Picker<Self>>,
1432 ) -> Option<Self::ListItem> {
1433 let hit = &self.matches[ix];
1434
1435 let highlighted_location = HighlightedMatch {
1436 text: hit.string.clone(),
1437 highlight_positions: hit.positions.clone(),
1438 char_count: hit.string.chars().count(),
1439 color: Color::Default,
1440 };
1441 let task_kind = &self.candidates[hit.candidate_id].0;
1442
1443 let icon = match task_kind {
1444 Some(TaskSourceKind::UserInput) => Some(Icon::new(IconName::Terminal)),
1445 Some(TaskSourceKind::AbsPath { .. }) => Some(Icon::new(IconName::Settings)),
1446 Some(TaskSourceKind::Worktree { .. }) => Some(Icon::new(IconName::FileTree)),
1447 Some(TaskSourceKind::Lsp {
1448 language_name: name,
1449 ..
1450 })
1451 | Some(TaskSourceKind::Language { name }) => file_icons::FileIcons::get(cx)
1452 .get_icon_for_type(&name.to_lowercase(), cx)
1453 .map(Icon::from_path),
1454 None => Some(Icon::new(IconName::HistoryRerun)),
1455 }
1456 .map(|icon| icon.color(Color::Muted).size(IconSize::Small));
1457 let indicator = if matches!(task_kind, Some(TaskSourceKind::Lsp { .. })) {
1458 Some(Indicator::icon(
1459 Icon::new(IconName::BoltFilled)
1460 .color(Color::Muted)
1461 .size(IconSize::Small),
1462 ))
1463 } else {
1464 None
1465 };
1466 let icon = icon.map(|icon| {
1467 IconWithIndicator::new(icon, indicator)
1468 .indicator_border_color(Some(cx.theme().colors().border_transparent))
1469 });
1470
1471 Some(
1472 ListItem::new(SharedString::from(format!("debug-scenario-selection-{ix}")))
1473 .inset(true)
1474 .start_slot::<IconWithIndicator>(icon)
1475 .spacing(ListItemSpacing::Sparse)
1476 .toggle_state(selected)
1477 .child(highlighted_location.render(window, cx)),
1478 )
1479 }
1480}
1481
1482pub(crate) fn resolve_path(path: &mut String) {
1483 if path.starts_with('~') {
1484 let home = paths::home_dir().to_string_lossy().to_string();
1485 let trimmed_path = path.trim().to_owned();
1486 *path = trimmed_path.replacen('~', &home, 1);
1487 } else if let Some(strip_path) = path.strip_prefix(&format!(".{}", std::path::MAIN_SEPARATOR)) {
1488 *path = format!(
1489 "$ZED_WORKTREE_ROOT{}{}",
1490 std::path::MAIN_SEPARATOR,
1491 &strip_path
1492 );
1493 };
1494}
1495
1496#[cfg(test)]
1497impl NewProcessModal {
1498 pub(crate) fn set_configure(
1499 &mut self,
1500 program: impl AsRef<str>,
1501 cwd: impl AsRef<str>,
1502 stop_on_entry: bool,
1503 window: &mut Window,
1504 cx: &mut Context<Self>,
1505 ) {
1506 self.mode = NewProcessMode::Launch;
1507 self.debugger = Some(dap::adapters::DebugAdapterName("fake-adapter".into()));
1508
1509 self.configure_mode.update(cx, |configure, cx| {
1510 configure.program.update(cx, |editor, cx| {
1511 editor.clear(window, cx);
1512 editor.set_text(program.as_ref(), window, cx);
1513 });
1514
1515 configure.cwd.update(cx, |editor, cx| {
1516 editor.clear(window, cx);
1517 editor.set_text(cwd.as_ref(), window, cx);
1518 });
1519
1520 configure.stop_on_entry = match stop_on_entry {
1521 true => ToggleState::Selected,
1522 _ => ToggleState::Unselected,
1523 }
1524 })
1525 }
1526}