new_session_modal.rs

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