Skip to repository content

tenant.openagents/omega

No repository description is available.

OpenAgents Git authority 2026-07-28T03:32:41.016Z Public web read
NIP-34 coordinate30617:7649603503856e5148d571eac2766b288a8ff1e9e35d380337a1d2b0015b4f92:omega
MaintainersHidden in public view
References2 branches · 1 tag
Read-only clonegit clone https://openagents.com/git/tenant.openagents/omega.git
Browse files

new_process_modal.rs

1670 lines · 63.5 KB · rust
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, TaskExt, 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, SharedTaskContext, 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::{ResultExt, debug_panic, rel_path::RelPath, shell::ShellKind};
32use workspace::{ModalView, Workspace, notifications::DetachAndPromptErr, pane};
33
34use crate::{
35    attach_modal::{AttachModal, ModalIntent},
36    debugger_panel::DebugPanel,
37};
38
39actions!(
40    new_process_modal,
41    [
42        ActivateTaskTab,
43        ActivateDebugTab,
44        ActivateAttachTab,
45        ActivateLaunchTab
46    ]
47);
48
49pub(super) struct NewProcessModal {
50    workspace: WeakEntity<Workspace>,
51    debug_panel: WeakEntity<DebugPanel>,
52    mode: NewProcessMode,
53    debug_picker: Entity<Picker<DebugDelegate>>,
54    attach_mode: Entity<AttachMode>,
55    configure_mode: Entity<ConfigureMode>,
56    task_mode: TaskMode,
57    debugger: Option<DebugAdapterName>,
58    _subscriptions: [Subscription; 3],
59}
60
61fn suggested_label(request: &DebugRequest, debugger: &str) -> SharedString {
62    match request {
63        DebugRequest::Launch(config) => {
64            let last_path_component = Path::new(&config.program)
65                .file_name()
66                .map(|name| name.to_string_lossy())
67                .unwrap_or_else(|| Cow::Borrowed(&config.program));
68
69            format!("{} ({debugger})", last_path_component).into()
70        }
71        DebugRequest::Attach(config) => format!(
72            "pid: {} ({debugger})",
73            config.process_id.unwrap_or(u32::MAX)
74        )
75        .into(),
76    }
77}
78
79impl NewProcessModal {
80    pub(super) fn show(
81        workspace: &mut Workspace,
82        window: &mut Window,
83        mode: NewProcessMode,
84        reveal_target: Option<RevealTarget>,
85        cx: &mut Context<Workspace>,
86    ) {
87        let Some(debug_panel) = workspace.panel::<DebugPanel>(cx) else {
88            return;
89        };
90        let task_store = workspace.project().read(cx).task_store().clone();
91        let languages = workspace.app_state().languages.clone();
92
93        cx.spawn_in(window, async move |workspace, cx| {
94            let task_contexts = workspace.update_in(cx, |workspace, window, cx| {
95                // 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
96                tasks_ui::task_contexts(workspace, window, cx)
97            })?;
98            workspace.update_in(cx, |workspace, window, cx| {
99                let workspace_handle = workspace.weak_handle();
100                let project = workspace.project().clone();
101                workspace.toggle_modal(window, cx, |window, cx| {
102                    let attach_mode =
103                        AttachMode::new(None, workspace_handle.clone(), project, window, cx);
104
105                    let debug_picker = cx.new(|cx| {
106                        let delegate =
107                            DebugDelegate::new(debug_panel.downgrade(), task_store.clone());
108                        Picker::list(delegate, window, cx)
109                            .embedded()
110                            .list_measure_all()
111                    });
112
113                    let configure_mode = ConfigureMode::new(window, cx);
114
115                    let task_overrides = Some(TaskOverrides { reveal_target });
116
117                    let task_mode = TaskMode {
118                        task_modal: cx.new(|cx| {
119                            TasksModal::new(
120                                task_store.clone(),
121                                Arc::new(TaskContexts::default()),
122                                task_overrides,
123                                false,
124                                workspace_handle.clone(),
125                                window,
126                                cx,
127                            )
128                        }),
129                    };
130
131                    let _subscriptions = [
132                        cx.subscribe(&debug_picker, |_, _, _, cx| {
133                            cx.emit(DismissEvent);
134                        }),
135                        cx.subscribe(
136                            &attach_mode.read(cx).attach_picker.clone(),
137                            |_, _, _, cx| {
138                                cx.emit(DismissEvent);
139                            },
140                        ),
141                        cx.subscribe(&task_mode.task_modal, |_, _, _: &DismissEvent, cx| {
142                            cx.emit(DismissEvent)
143                        }),
144                    ];
145
146                    cx.spawn_in(window, {
147                        let debug_picker = debug_picker.downgrade();
148                        let configure_mode = configure_mode.downgrade();
149                        let task_modal = task_mode.task_modal.downgrade();
150                        let workspace = workspace_handle.clone();
151
152                        async move |this, cx| {
153                            let task_contexts = task_contexts.await;
154                            let task_contexts = Arc::new(task_contexts);
155                            let lsp_task_sources = task_contexts.lsp_task_sources.clone();
156                            let task_position = task_contexts.latest_selection;
157                            // Get LSP tasks and filter out based on language vs lsp preference
158                            let (lsp_tasks, prefer_lsp) =
159                                workspace.update(cx, |workspace, cx| {
160                                    let lsp_tasks = editor::lsp_tasks(
161                                        workspace.project().clone(),
162                                        &lsp_task_sources,
163                                        task_position,
164                                        cx,
165                                    );
166                                    let prefer_lsp = workspace
167                                        .active_item(cx)
168                                        .and_then(|item| item.downcast::<Editor>())
169                                        .map(|editor| {
170                                            editor
171                                                .read(cx)
172                                                .buffer()
173                                                .read(cx)
174                                                .language_settings(cx)
175                                                .tasks
176                                                .prefer_lsp
177                                        })
178                                        .unwrap_or(false);
179                                    (lsp_tasks, prefer_lsp)
180                                })?;
181
182                            let lsp_tasks = lsp_tasks.await;
183                            let add_current_language_tasks = !prefer_lsp || lsp_tasks.is_empty();
184
185                            let lsp_tasks = lsp_tasks
186                                .into_iter()
187                                .flat_map(|(kind, tasks_with_locations)| {
188                                    tasks_with_locations
189                                        .into_iter()
190                                        .sorted_by_key(|(location, task)| {
191                                            (location.is_none(), task.resolved_label.clone())
192                                        })
193                                        .map(move |(_, task)| (kind.clone(), task))
194                                })
195                                .collect::<Vec<_>>();
196
197                            let Some(task_inventory) = task_store
198                                .update(cx, |task_store, _| task_store.task_inventory().cloned())
199                            else {
200                                return Ok(());
201                            };
202
203                            let (used_tasks, current_resolved_tasks) = task_inventory
204                                .update(cx, |task_inventory, cx| {
205                                    task_inventory
206                                        .used_and_current_resolved_tasks(task_contexts.clone(), cx)
207                                })
208                                .await;
209
210                            if let Ok(task) = debug_picker.update(cx, |picker, cx| {
211                                picker.delegate.tasks_loaded(
212                                    task_contexts.clone(),
213                                    languages,
214                                    lsp_tasks.clone(),
215                                    current_resolved_tasks.clone(),
216                                    add_current_language_tasks,
217                                    cx,
218                                )
219                            }) {
220                                task.await;
221                                debug_picker
222                                    .update_in(cx, |picker, window, cx| {
223                                        picker.refresh(window, cx);
224                                        cx.notify();
225                                    })
226                                    .ok();
227                            }
228
229                            if let Some(active_cwd) = task_contexts
230                                .active_context()
231                                .and_then(|context| context.cwd.clone())
232                            {
233                                configure_mode
234                                    .update_in(cx, |configure_mode, window, cx| {
235                                        configure_mode.load(active_cwd, window, cx);
236                                    })
237                                    .ok();
238                            }
239
240                            task_modal
241                                .update_in(cx, |task_modal, window, cx| {
242                                    task_modal.tasks_loaded(
243                                        task_contexts,
244                                        lsp_tasks,
245                                        used_tasks,
246                                        current_resolved_tasks,
247                                        add_current_language_tasks,
248                                        window,
249                                        cx,
250                                    );
251                                })
252                                .ok();
253
254                            this.update(cx, |_, cx| {
255                                cx.notify();
256                            })
257                            .ok();
258
259                            anyhow::Ok(())
260                        }
261                    })
262                    .detach();
263
264                    Self {
265                        debug_picker,
266                        attach_mode,
267                        configure_mode,
268                        task_mode,
269                        debugger: None,
270                        mode,
271                        debug_panel: debug_panel.downgrade(),
272                        workspace: workspace_handle,
273                        _subscriptions,
274                    }
275                });
276            })?;
277
278            anyhow::Ok(())
279        })
280        .detach();
281    }
282
283    fn render_mode(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl ui::IntoElement {
284        let dap_menu = self.adapter_drop_down_menu(window, cx);
285        match self.mode {
286            NewProcessMode::Task => self
287                .task_mode
288                .task_modal
289                .read(cx)
290                .picker
291                .clone()
292                .into_any_element(),
293            NewProcessMode::Attach => self.attach_mode.update(cx, |this, cx| {
294                this.clone().render(window, cx).into_any_element()
295            }),
296            NewProcessMode::Launch => self.configure_mode.update(cx, |this, cx| {
297                this.clone().render(dap_menu, window, cx).into_any_element()
298            }),
299            NewProcessMode::Debug => v_flex()
300                .w(rems(34.))
301                .child(self.debug_picker.clone())
302                .into_any_element(),
303        }
304    }
305
306    fn mode_focus_handle(&self, cx: &App) -> FocusHandle {
307        match self.mode {
308            NewProcessMode::Task => self.task_mode.task_modal.focus_handle(cx),
309            NewProcessMode::Attach => self.attach_mode.read(cx).attach_picker.focus_handle(cx),
310            NewProcessMode::Launch => self.configure_mode.read(cx).program.focus_handle(cx),
311            NewProcessMode::Debug => self.debug_picker.focus_handle(cx),
312        }
313    }
314
315    fn debug_scenario(&self, debugger: &str, cx: &App) -> Task<Option<DebugScenario>> {
316        let request = match self.mode {
317            NewProcessMode::Launch => {
318                DebugRequest::Launch(self.configure_mode.read(cx).debug_request(cx))
319            }
320            NewProcessMode::Attach => {
321                DebugRequest::Attach(self.attach_mode.read(cx).debug_request())
322            }
323            _ => return Task::ready(None),
324        };
325        let label = suggested_label(&request, debugger);
326
327        let stop_on_entry = if let NewProcessMode::Launch = &self.mode {
328            Some(self.configure_mode.read(cx).stop_on_entry.selected())
329        } else {
330            None
331        };
332
333        let session_scenario = ZedDebugConfig {
334            adapter: debugger.to_owned().into(),
335            label,
336            request,
337            stop_on_entry,
338        };
339
340        let adapter = cx
341            .global::<DapRegistry>()
342            .adapter(&session_scenario.adapter);
343
344        cx.spawn(async move |_| adapter?.config_from_zed_format(session_scenario).await.ok())
345    }
346
347    fn start_new_session(&mut self, window: &mut Window, cx: &mut Context<Self>) {
348        if self.debugger.as_ref().is_none() {
349            return;
350        }
351
352        if let NewProcessMode::Debug = &self.mode {
353            self.debug_picker.update(cx, |picker, cx| {
354                picker.delegate.confirm(false, window, cx);
355            });
356            return;
357        }
358
359        if let NewProcessMode::Launch = &self.mode
360            && self.configure_mode.read(cx).save_to_debug_json.selected()
361        {
362            self.save_debug_scenario(window, cx);
363        }
364
365        let Some(debugger) = self.debugger.clone() else {
366            return;
367        };
368
369        let debug_panel = self.debug_panel.clone();
370        let Some(task_contexts) = self.task_contexts(cx) else {
371            return;
372        };
373
374        let task_context = task_contexts
375            .active_context()
376            .cloned()
377            .unwrap_or_default()
378            .into();
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::Anchor::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        let mut args = ShellKind::Posix
878            .split(&command)
879            .into_iter()
880            .flatten()
881            .peekable();
882        let mut env = FxHashMap::default();
883        while args.peek().is_some_and(|arg| arg.contains('=')) {
884            let arg = args.next().unwrap();
885            let (lhs, rhs) = arg.split_once('=').unwrap();
886            env.insert(lhs.to_string(), rhs.to_string());
887        }
888
889        let program = if let Some(program) = args.next() {
890            program
891        } else {
892            env = FxHashMap::default();
893            command
894        };
895
896        let args = args.collect::<Vec<_>>();
897
898        task::LaunchRequest {
899            program,
900            cwd,
901            args,
902            env,
903        }
904    }
905
906    fn on_tab(&mut self, _: &menu::SelectNext, window: &mut Window, cx: &mut Context<Self>) {
907        window.focus_next(cx);
908    }
909
910    fn on_tab_prev(
911        &mut self,
912        _: &menu::SelectPrevious,
913        window: &mut Window,
914        cx: &mut Context<Self>,
915    ) {
916        window.focus_prev(cx);
917    }
918
919    fn render(
920        &mut self,
921        adapter_menu: DropdownMenu,
922        _: &mut Window,
923        cx: &mut ui::Context<Self>,
924    ) -> impl IntoElement {
925        v_flex()
926            .tab_group()
927            .track_focus(&self.program.focus_handle(cx))
928            .on_action(cx.listener(Self::on_tab))
929            .on_action(cx.listener(Self::on_tab_prev))
930            .p_2()
931            .w_full()
932            .gap_3()
933            .child(
934                h_flex()
935                    .gap_1()
936                    .child(Label::new("Debugger:").color(Color::Muted))
937                    .child(adapter_menu),
938            )
939            .child(self.program.clone())
940            .child(self.cwd.clone())
941            .child(
942                Switch::new("debugger-stop-on-entry", self.stop_on_entry)
943                    .tab_index(3_isize)
944                    .label("Stop on Entry")
945                    .label_position(SwitchLabelPosition::Start)
946                    .label_size(LabelSize::Default)
947                    .on_click({
948                        let this = cx.weak_entity();
949                        move |state, _, cx| {
950                            this.update(cx, |this, _| {
951                                this.stop_on_entry = *state;
952                            })
953                            .ok();
954                        }
955                    }),
956            )
957    }
958}
959
960#[derive(Clone)]
961pub(super) struct AttachMode {
962    pub(super) definition: ZedDebugConfig,
963    pub(super) attach_picker: Entity<AttachModal>,
964}
965
966impl AttachMode {
967    pub(super) fn new(
968        debugger: Option<DebugAdapterName>,
969        workspace: WeakEntity<Workspace>,
970        project: Entity<Project>,
971        window: &mut Window,
972        cx: &mut Context<NewProcessModal>,
973    ) -> Entity<Self> {
974        let definition = ZedDebugConfig {
975            adapter: debugger.unwrap_or(DebugAdapterName("".into())).0,
976            label: "Attach New Session Setup".into(),
977            request: dap::DebugRequest::Attach(task::AttachRequest { process_id: None }),
978            stop_on_entry: Some(false),
979        };
980        let attach_picker = cx.new(|cx| {
981            let modal = AttachModal::new(
982                ModalIntent::AttachToProcess(definition.clone()),
983                workspace,
984                project,
985                false,
986                window,
987                cx,
988            );
989            window.focus(&modal.focus_handle(cx), cx);
990
991            modal
992        });
993
994        cx.new(|_| Self {
995            definition,
996            attach_picker,
997        })
998    }
999    pub(super) fn debug_request(&self) -> task::AttachRequest {
1000        task::AttachRequest { process_id: None }
1001    }
1002}
1003
1004#[derive(Clone)]
1005pub(super) struct TaskMode {
1006    pub(super) task_modal: Entity<TasksModal>,
1007}
1008
1009pub(super) struct DebugDelegate {
1010    task_store: Entity<TaskStore>,
1011    candidates: Vec<(
1012        Option<TaskSourceKind>,
1013        Option<LanguageName>,
1014        DebugScenario,
1015        Option<DebugScenarioContext>,
1016    )>,
1017    selected_index: usize,
1018    matches: Vec<StringMatch>,
1019    prompt: String,
1020    debug_panel: WeakEntity<DebugPanel>,
1021    task_contexts: Option<Arc<TaskContexts>>,
1022    divider_index: Option<usize>,
1023    last_used_candidate_index: Option<usize>,
1024}
1025
1026impl DebugDelegate {
1027    pub(super) fn new(debug_panel: WeakEntity<DebugPanel>, task_store: Entity<TaskStore>) -> Self {
1028        Self {
1029            task_store,
1030            candidates: Vec::default(),
1031            selected_index: 0,
1032            matches: Vec::new(),
1033            prompt: String::new(),
1034            debug_panel,
1035            task_contexts: None,
1036            divider_index: None,
1037            last_used_candidate_index: None,
1038        }
1039    }
1040
1041    fn get_task_subtitle(
1042        &self,
1043        task_kind: &Option<TaskSourceKind>,
1044        context: &Option<DebugScenarioContext>,
1045        cx: &mut App,
1046    ) -> Option<String> {
1047        match task_kind {
1048            Some(TaskSourceKind::Worktree {
1049                id: worktree_id,
1050                directory_in_worktree,
1051                ..
1052            }) => self
1053                .debug_panel
1054                .update(cx, |debug_panel, cx| {
1055                    let project = debug_panel.project().read(cx);
1056                    let worktrees: Vec<_> = project.visible_worktrees(cx).collect();
1057
1058                    let mut path = if worktrees.len() > 1
1059                        && let Some(worktree) = project.worktree_for_id(*worktree_id, cx)
1060                    {
1061                        worktree
1062                            .read(cx)
1063                            .root_name()
1064                            .join(directory_in_worktree)
1065                            .to_rel_path_buf()
1066                    } else {
1067                        directory_in_worktree.to_rel_path_buf()
1068                    };
1069
1070                    match path.components().next_back() {
1071                        Some(".zed") => {
1072                            path.push(RelPath::from_unix_str("debug.json").unwrap());
1073                        }
1074                        Some(".vscode") => {
1075                            path.push(RelPath::from_unix_str("launch.json").unwrap());
1076                        }
1077                        _ => {}
1078                    }
1079                    path.display(project.path_style(cx)).to_string()
1080                })
1081                .ok(),
1082            Some(TaskSourceKind::AbsPath { abs_path, .. }) => {
1083                Some(abs_path.to_string_lossy().into_owned())
1084            }
1085            Some(TaskSourceKind::Lsp { language_name, .. }) => {
1086                Some(format!("LSP: {language_name}"))
1087            }
1088            Some(TaskSourceKind::Language { name }) => Some(format!("Language: {name}")),
1089            _ => context.clone().and_then(|ctx| {
1090                ctx.task_context
1091                    .task_variables
1092                    .get(&VariableName::RelativeFile)
1093                    .map(|f| format!("in {f}"))
1094                    .or_else(|| {
1095                        ctx.task_context
1096                            .task_variables
1097                            .get(&VariableName::Dirname)
1098                            .map(|d| format!("in {d}/"))
1099                    })
1100            }),
1101        }
1102    }
1103
1104    fn get_scenario_language(
1105        languages: &Arc<LanguageRegistry>,
1106        dap_registry: &DapRegistry,
1107        scenario: DebugScenario,
1108    ) -> (Option<LanguageName>, DebugScenario) {
1109        let language_names = languages.language_names();
1110        let language_name = dap_registry.adapter_language(&scenario.adapter);
1111
1112        let language_name = language_name.or_else(|| {
1113            scenario.label.split_whitespace().find_map(|word| {
1114                language_names
1115                    .iter()
1116                    .find(|name| name.as_ref().eq_ignore_ascii_case(word))
1117                    .cloned()
1118            })
1119        });
1120
1121        (language_name, scenario)
1122    }
1123
1124    pub fn tasks_loaded(
1125        &mut self,
1126        task_contexts: Arc<TaskContexts>,
1127        languages: Arc<LanguageRegistry>,
1128        lsp_tasks: Vec<(TaskSourceKind, task::ResolvedTask)>,
1129        current_resolved_tasks: Vec<(TaskSourceKind, task::ResolvedTask)>,
1130        add_current_language_tasks: bool,
1131        cx: &mut Context<Picker<Self>>,
1132    ) -> Task<()> {
1133        self.task_contexts = Some(task_contexts.clone());
1134        let task = self.task_store.update(cx, |task_store, cx| {
1135            task_store.task_inventory().map(|inventory| {
1136                inventory.update(cx, |inventory, cx| {
1137                    inventory.list_debug_scenarios(
1138                        &task_contexts,
1139                        lsp_tasks,
1140                        current_resolved_tasks,
1141                        add_current_language_tasks,
1142                        cx,
1143                    )
1144                })
1145            })
1146        });
1147
1148        let valid_adapters: HashSet<_> = cx.global::<DapRegistry>().enumerate_adapters();
1149
1150        cx.spawn(async move |this, cx| {
1151            let (recent, scenarios) = if let Some(task) = task {
1152                task.await
1153            } else {
1154                (Vec::new(), Vec::new())
1155            };
1156
1157            this.update(cx, |this, cx| {
1158                if !recent.is_empty() {
1159                    this.delegate.last_used_candidate_index = Some(recent.len() - 1);
1160                }
1161
1162                let dap_registry = cx.global::<DapRegistry>();
1163                let hide_vscode = scenarios.iter().any(|(kind, _)| match kind {
1164                    TaskSourceKind::Worktree {
1165                        id: _,
1166                        directory_in_worktree: dir,
1167                        id_base: _,
1168                    } => dir.ends_with(RelPath::from_unix_str(".zed").unwrap()),
1169                    _ => false,
1170                });
1171
1172                this.delegate.candidates = recent
1173                    .into_iter()
1174                    .map(|(scenario, context)| {
1175                        let (language_name, scenario) =
1176                            Self::get_scenario_language(&languages, dap_registry, scenario);
1177                        (None, language_name, scenario, Some(context))
1178                    })
1179                    .chain(
1180                        scenarios
1181                            .into_iter()
1182                            .filter(|(kind, _)| match kind {
1183                                TaskSourceKind::Worktree {
1184                                    id: _,
1185                                    directory_in_worktree: dir,
1186                                    id_base: _,
1187                                } => {
1188                                    !(hide_vscode
1189                                        && dir
1190                                            .ends_with(RelPath::from_unix_str(".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 name() -> &'static str {
1212        "debug scenario picker"
1213    }
1214
1215    fn match_count(&self) -> usize {
1216        self.matches.len()
1217    }
1218
1219    fn selected_index(&self) -> usize {
1220        self.selected_index
1221    }
1222
1223    fn set_selected_index(
1224        &mut self,
1225        ix: usize,
1226        _window: &mut Window,
1227        _cx: &mut Context<picker::Picker<Self>>,
1228    ) {
1229        self.selected_index = ix;
1230    }
1231
1232    fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> std::sync::Arc<str> {
1233        "Find a debug task, or debug a command".into()
1234    }
1235
1236    fn update_matches(
1237        &mut self,
1238        query: String,
1239        window: &mut Window,
1240        cx: &mut Context<picker::Picker<Self>>,
1241    ) -> gpui::Task<()> {
1242        let candidates = self.candidates.clone();
1243
1244        cx.spawn_in(window, async move |picker, cx| {
1245            let candidates: Vec<_> = candidates
1246                .into_iter()
1247                .enumerate()
1248                .map(|(index, (_, _, candidate, _))| {
1249                    StringMatchCandidate::new(index, candidate.label.as_ref())
1250                })
1251                .collect();
1252
1253            let matches = fuzzy::match_strings(
1254                &candidates,
1255                &query,
1256                true,
1257                true,
1258                1000,
1259                &Default::default(),
1260                cx.background_executor().clone(),
1261            )
1262            .await;
1263
1264            picker
1265                .update(cx, |picker, _| {
1266                    let delegate = &mut picker.delegate;
1267
1268                    delegate.matches = matches;
1269                    delegate.prompt = query;
1270
1271                    delegate.divider_index = delegate.last_used_candidate_index.and_then(|index| {
1272                        let index = delegate
1273                            .matches
1274                            .partition_point(|matching_task| matching_task.candidate_id <= index);
1275                        Some(index).and_then(|index| (index != 0).then(|| index - 1))
1276                    });
1277
1278                    if delegate.matches.is_empty() {
1279                        delegate.selected_index = 0;
1280                    } else {
1281                        delegate.selected_index =
1282                            delegate.selected_index.min(delegate.matches.len() - 1);
1283                    }
1284                })
1285                .log_err();
1286        })
1287    }
1288
1289    fn separators_after_indices(&self) -> Vec<usize> {
1290        if let Some(i) = self.divider_index {
1291            vec![i]
1292        } else {
1293            Vec::new()
1294        }
1295    }
1296
1297    fn confirm_input(&mut self, _: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
1298        let text = self.prompt.clone();
1299        let (task_context, worktree_id) = self
1300            .task_contexts
1301            .as_ref()
1302            .and_then(|task_contexts| {
1303                Some((
1304                    SharedTaskContext::from(task_contexts.active_context().cloned()?),
1305                    task_contexts.worktree(),
1306                ))
1307            })
1308            .unwrap_or_default();
1309
1310        let mut args = ShellKind::Posix
1311            .split(&text)
1312            .into_iter()
1313            .flatten()
1314            .peekable();
1315        let mut env = HashMap::default();
1316        while args.peek().is_some_and(|arg| arg.contains('=')) {
1317            let arg = args.next().unwrap();
1318            let (lhs, rhs) = arg.split_once('=').unwrap();
1319            env.insert(lhs.to_string(), rhs.to_string());
1320        }
1321
1322        let program = if let Some(program) = args.next() {
1323            program
1324        } else {
1325            env = HashMap::default();
1326            text
1327        };
1328
1329        let args = args.collect::<Vec<_>>();
1330        let task = task::TaskTemplate {
1331            label: "one-off".to_owned(), // TODO: rename using command as label
1332            env,
1333            command: program,
1334            args,
1335            ..Default::default()
1336        };
1337
1338        let Some(location) = self
1339            .task_contexts
1340            .as_ref()
1341            .and_then(|cx| cx.location().cloned())
1342        else {
1343            return;
1344        };
1345        let buffer = location.buffer.read(cx);
1346        let language = buffer.language();
1347        let Some(adapter): Option<DebugAdapterName> =
1348            language::language_settings::LanguageSettings::for_buffer(buffer, cx)
1349                .debuggers
1350                .first()
1351                .map(SharedString::from)
1352                .map(Into::into)
1353                .or_else(|| {
1354                    language.and_then(|l| {
1355                        l.config()
1356                            .debuggers
1357                            .first()
1358                            .map(SharedString::from)
1359                            .map(Into::into)
1360                    })
1361                })
1362        else {
1363            return;
1364        };
1365        let locators = cx.global::<DapRegistry>().locators();
1366        cx.spawn_in(window, async move |this, cx| {
1367            let Some(debug_scenario) = cx
1368                .background_spawn(async move {
1369                    for locator in locators {
1370                        if let Some(scenario) =
1371                            // TODO: use a more informative label than "one-off"
1372                            locator
1373                                .1
1374                                .create_scenario(&task, &task.label, &adapter)
1375                                .await
1376                        {
1377                            return Some(scenario);
1378                        }
1379                    }
1380                    None
1381                })
1382                .await
1383            else {
1384                return;
1385            };
1386
1387            this.update_in(cx, |this, window, cx| {
1388                send_telemetry(&debug_scenario, TelemetrySpawnLocation::ScenarioList, cx);
1389                this.delegate
1390                    .debug_panel
1391                    .update(cx, |panel, cx| {
1392                        panel.start_session(
1393                            debug_scenario,
1394                            task_context,
1395                            None,
1396                            worktree_id,
1397                            window,
1398                            cx,
1399                        );
1400                    })
1401                    .ok();
1402                cx.emit(DismissEvent);
1403            })
1404            .ok();
1405        })
1406        .detach();
1407    }
1408
1409    fn confirm(
1410        &mut self,
1411        secondary: bool,
1412        window: &mut Window,
1413        cx: &mut Context<picker::Picker<Self>>,
1414    ) {
1415        let debug_scenario = self
1416            .matches
1417            .get(self.selected_index())
1418            .and_then(|match_candidate| self.candidates.get(match_candidate.candidate_id).cloned());
1419
1420        let Some((kind, _, debug_scenario, context)) = debug_scenario else {
1421            return;
1422        };
1423
1424        let context = context.unwrap_or_else(|| {
1425            self.task_contexts
1426                .as_ref()
1427                .and_then(|task_contexts| {
1428                    Some(DebugScenarioContext {
1429                        task_context: task_contexts.active_context().cloned()?.into(),
1430                        active_buffer: None,
1431                        worktree_id: task_contexts.worktree(),
1432                    })
1433                })
1434                .unwrap_or_default()
1435        });
1436        let DebugScenarioContext {
1437            task_context,
1438            active_buffer: _,
1439            worktree_id,
1440        } = context;
1441
1442        if secondary {
1443            let Some(kind) = kind else { return };
1444            let Some(id) = worktree_id else { return };
1445            let debug_panel = self.debug_panel.clone();
1446            cx.spawn_in(window, async move |_, cx| {
1447                debug_panel
1448                    .update_in(cx, |debug_panel, window, cx| {
1449                        debug_panel.go_to_scenario_definition(kind, debug_scenario, id, window, cx)
1450                    })?
1451                    .await?;
1452                anyhow::Ok(())
1453            })
1454            .detach();
1455        } else {
1456            send_telemetry(&debug_scenario, TelemetrySpawnLocation::ScenarioList, cx);
1457            self.debug_panel
1458                .update(cx, |panel, cx| {
1459                    panel.start_session(
1460                        debug_scenario,
1461                        task_context,
1462                        None,
1463                        worktree_id,
1464                        window,
1465                        cx,
1466                    );
1467                })
1468                .ok();
1469        }
1470
1471        cx.emit(DismissEvent);
1472    }
1473
1474    fn dismissed(&mut self, _: &mut Window, cx: &mut Context<picker::Picker<Self>>) {
1475        cx.emit(DismissEvent);
1476    }
1477
1478    fn render_footer(
1479        &self,
1480        window: &mut Window,
1481        cx: &mut Context<Picker<Self>>,
1482    ) -> Option<ui::AnyElement> {
1483        let current_modifiers = window.modifiers();
1484        let footer = h_flex()
1485            .w_full()
1486            .p_1p5()
1487            .justify_between()
1488            .border_t_1()
1489            .border_color(cx.theme().colors().border_variant)
1490            .child({
1491                let action = menu::SecondaryConfirm.boxed_clone();
1492                if self.matches.is_empty() {
1493                    Button::new("edit-debug-json", "Edit debug.json").on_click(cx.listener(
1494                        |_picker, _, window, cx| {
1495                            window.dispatch_action(
1496                                zed_actions::OpenProjectDebugTasks.boxed_clone(),
1497                                cx,
1498                            );
1499                            cx.emit(DismissEvent);
1500                        },
1501                    ))
1502                } else {
1503                    Button::new("edit-debug-task", "Edit in debug.json")
1504                        .key_binding(KeyBinding::for_action(&*action, cx))
1505                        .on_click(move |_, window, cx| {
1506                            window.dispatch_action(action.boxed_clone(), cx)
1507                        })
1508                }
1509            })
1510            .map(|this| {
1511                if (current_modifiers.alt || self.matches.is_empty()) && !self.prompt.is_empty() {
1512                    let action = picker::ConfirmInput { secondary: false }.boxed_clone();
1513                    this.child({
1514                        Button::new("launch-custom", "Launch Custom")
1515                            .key_binding(KeyBinding::for_action(&*action, cx))
1516                            .on_click(move |_, window, cx| {
1517                                window.dispatch_action(action.boxed_clone(), cx)
1518                            })
1519                    })
1520                } else {
1521                    this.child({
1522                        let is_recent_selected = self.divider_index >= Some(self.selected_index);
1523                        let run_entry_label = if is_recent_selected { "Rerun" } else { "Spawn" };
1524
1525                        Button::new("spawn", run_entry_label)
1526                            .key_binding(KeyBinding::for_action(&menu::Confirm, cx))
1527                            .on_click(|_, window, cx| {
1528                                window.dispatch_action(menu::Confirm.boxed_clone(), cx);
1529                            })
1530                    })
1531                }
1532            });
1533        Some(footer.into_any_element())
1534    }
1535
1536    fn render_match(
1537        &self,
1538        ix: usize,
1539        selected: bool,
1540        window: &mut Window,
1541        cx: &mut Context<picker::Picker<Self>>,
1542    ) -> Option<Self::ListItem> {
1543        let hit = &self.matches.get(ix)?;
1544        let (task_kind, language_name, _scenario, context) = &self.candidates[hit.candidate_id];
1545
1546        let highlighted_location = HighlightedMatch {
1547            text: hit.string.clone(),
1548            highlight_positions: hit.positions.clone(),
1549            color: Color::Default,
1550        };
1551
1552        let subtitle = self.get_task_subtitle(task_kind, context, cx);
1553
1554        let language_icon = language_name.as_ref().and_then(|lang| {
1555            file_icons::FileIcons::get(cx)
1556                .get_icon_for_type(&lang.0.to_lowercase(), cx)
1557                .map(Icon::from_path)
1558        });
1559
1560        let (icon, indicator) = match task_kind {
1561            Some(TaskSourceKind::UserInput) => (Some(Icon::new(IconName::Terminal)), None),
1562            Some(TaskSourceKind::AbsPath { .. }) => (Some(Icon::new(IconName::Settings)), None),
1563            Some(TaskSourceKind::Worktree { .. }) => (Some(Icon::new(IconName::FileTree)), None),
1564            Some(TaskSourceKind::Lsp { language_name, .. }) => (
1565                file_icons::FileIcons::get(cx)
1566                    .get_icon_for_type(&language_name.to_lowercase(), cx)
1567                    .map(Icon::from_path),
1568                Some(Indicator::icon(
1569                    Icon::new(IconName::BoltFilled)
1570                        .color(Color::Muted)
1571                        .size(IconSize::Small),
1572                )),
1573            ),
1574            Some(TaskSourceKind::Language { name }) => (
1575                file_icons::FileIcons::get(cx)
1576                    .get_icon_for_type(&name.to_lowercase(), cx)
1577                    .map(Icon::from_path),
1578                None,
1579            ),
1580            None => (Some(Icon::new(IconName::HistoryRerun)), None),
1581        };
1582
1583        let icon = language_icon.or(icon).map(|icon| {
1584            IconWithIndicator::new(icon.color(Color::Muted).size(IconSize::Small), indicator)
1585                .indicator_border_color(Some(cx.theme().colors().border_transparent))
1586        });
1587
1588        Some(
1589            ListItem::new(format!("debug-scenario-selection-{ix}"))
1590                .inset(true)
1591                .start_slot::<IconWithIndicator>(icon)
1592                .spacing(ListItemSpacing::Sparse)
1593                .toggle_state(selected)
1594                .child(
1595                    v_flex()
1596                        .w_full()
1597                        .min_w_0()
1598                        .items_start()
1599                        .child(highlighted_location.render(window, cx))
1600                        .when_some(subtitle, |this, subtitle_text| {
1601                            this.child(
1602                                Label::new(subtitle_text)
1603                                    .size(LabelSize::Small)
1604                                    .color(Color::Muted),
1605                            )
1606                        }),
1607                ),
1608        )
1609    }
1610}
1611
1612pub(crate) fn resolve_path(path: &mut String) {
1613    if path.starts_with('~') {
1614        let home = paths::home_dir().to_string_lossy().into_owned();
1615        let trimmed_path = path.trim().to_owned();
1616        *path = trimmed_path.replacen('~', &home, 1);
1617    } else if let Some(strip_path) = path.strip_prefix(&format!(".{}", std::path::MAIN_SEPARATOR)) {
1618        *path = format!(
1619            "$ZED_WORKTREE_ROOT{}{}",
1620            std::path::MAIN_SEPARATOR,
1621            &strip_path
1622        );
1623    };
1624}
1625
1626#[cfg(test)]
1627impl NewProcessModal {
1628    pub(crate) fn set_configure(
1629        &mut self,
1630        program: impl AsRef<str>,
1631        cwd: impl AsRef<str>,
1632        stop_on_entry: bool,
1633        window: &mut Window,
1634        cx: &mut Context<Self>,
1635    ) {
1636        self.mode = NewProcessMode::Launch;
1637        self.debugger = Some(dap::adapters::DebugAdapterName("fake-adapter".into()));
1638
1639        self.configure_mode.update(cx, |configure, cx| {
1640            configure.program.update(cx, |editor, cx| {
1641                editor.clear(window, cx);
1642                editor.set_text(program.as_ref(), window, cx);
1643            });
1644
1645            configure.cwd.update(cx, |editor, cx| {
1646                editor.clear(window, cx);
1647                editor.set_text(cwd.as_ref(), window, cx);
1648            });
1649
1650            configure.stop_on_entry = match stop_on_entry {
1651                true => ToggleState::Selected,
1652                _ => ToggleState::Unselected,
1653            }
1654        })
1655    }
1656
1657    pub(crate) fn debug_picker_candidate_subtitles(&self, cx: &mut App) -> Vec<String> {
1658        self.debug_picker.update(cx, |picker, cx| {
1659            picker
1660                .delegate
1661                .candidates
1662                .iter()
1663                .filter_map(|(task_kind, _, _, context)| {
1664                    picker.delegate.get_task_subtitle(task_kind, context, cx)
1665                })
1666                .collect()
1667        })
1668    }
1669}
1670
Served at tenant.openagents/omega Member data and write actions are omitted.