new_process_modal.rs

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