new_process_modal.rs

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