new_process_modal.rs

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