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