new_process_modal.rs

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