new_process_modal.rs

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