new_process_modal.rs

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