new_process_modal.rs

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