new_process_modal.rs

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