new_process_modal.rs

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