new_process_modal.rs

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