new_process_modal.rs

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