new_process_modal.rs

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