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