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