new_process_modal.rs

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