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