debugger_panel.rs

   1use crate::persistence::DebuggerPaneItem;
   2use crate::session::DebugSession;
   3use crate::session::running::RunningState;
   4use crate::session::running::breakpoint_list::BreakpointList;
   5
   6use crate::{
   7    ClearAllBreakpoints, Continue, CopyDebugAdapterArguments, Detach, FocusBreakpointList,
   8    FocusConsole, FocusFrames, FocusLoadedSources, FocusModules, FocusTerminal, FocusVariables,
   9    NewProcessModal, NewProcessMode, Pause, RerunSession, StepInto, StepOut, StepOver, Stop,
  10    ToggleExpandItem, ToggleSessionPicker, ToggleThreadPicker, persistence, spawn_task_or_modal,
  11};
  12use anyhow::{Context as _, Result, anyhow};
  13use collections::IndexMap;
  14use dap::adapters::DebugAdapterName;
  15use dap::{DapRegistry, StartDebuggingRequestArguments};
  16use dap::{client::SessionId, debugger_settings::DebuggerSettings};
  17use editor::{Editor, MultiBufferOffset, ToPoint};
  18use feature_flags::{FeatureFlag, FeatureFlagAppExt as _};
  19use gpui::{
  20    Action, App, AsyncWindowContext, ClipboardItem, Context, Corner, DismissEvent, Entity,
  21    EntityId, EventEmitter, FocusHandle, Focusable, MouseButton, MouseDownEvent, Point,
  22    Subscription, Task, WeakEntity, anchored, deferred,
  23};
  24
  25use itertools::Itertools as _;
  26use language::Buffer;
  27use project::debugger::session::{Session, SessionQuirks, SessionState, SessionStateEvent};
  28use project::{DebugScenarioContext, Fs, ProjectPath, TaskSourceKind, WorktreeId};
  29use project::{Project, debugger::session::ThreadStatus};
  30use rpc::proto::{self};
  31use settings::Settings;
  32use std::sync::{Arc, LazyLock};
  33use task::{DebugScenario, SharedTaskContext};
  34use tree_sitter::{Query, StreamingIterator as _};
  35use ui::{
  36    ContextMenu, Divider, PopoverMenu, PopoverMenuHandle, SplitButton, Tab, Tooltip, prelude::*,
  37};
  38use util::rel_path::RelPath;
  39use util::{ResultExt, debug_panic, maybe};
  40use workspace::SplitDirection;
  41use workspace::item::SaveOptions;
  42use workspace::{
  43    Item, Pane, Workspace,
  44    dock::{DockPosition, Panel, PanelEvent},
  45};
  46use zed_actions::ToggleFocus;
  47
  48pub struct DebuggerHistoryFeatureFlag;
  49
  50impl FeatureFlag for DebuggerHistoryFeatureFlag {
  51    const NAME: &'static str = "debugger-history";
  52}
  53
  54const DEBUG_PANEL_KEY: &str = "DebugPanel";
  55
  56pub struct DebugPanel {
  57    size: Pixels,
  58    active_session: Option<Entity<DebugSession>>,
  59    project: Entity<Project>,
  60    workspace: WeakEntity<Workspace>,
  61    focus_handle: FocusHandle,
  62    context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,
  63    debug_scenario_scheduled_last: bool,
  64    pub(crate) sessions_with_children:
  65        IndexMap<Entity<DebugSession>, Vec<WeakEntity<DebugSession>>>,
  66    pub(crate) thread_picker_menu_handle: PopoverMenuHandle<ContextMenu>,
  67    pub(crate) session_picker_menu_handle: PopoverMenuHandle<ContextMenu>,
  68    fs: Arc<dyn Fs>,
  69    is_zoomed: bool,
  70    _subscriptions: [Subscription; 1],
  71    breakpoint_list: Entity<BreakpointList>,
  72}
  73
  74impl DebugPanel {
  75    pub fn new(
  76        workspace: &Workspace,
  77        window: &mut Window,
  78        cx: &mut Context<Workspace>,
  79    ) -> Entity<Self> {
  80        cx.new(|cx| {
  81            let project = workspace.project().clone();
  82            let focus_handle = cx.focus_handle();
  83            let thread_picker_menu_handle = PopoverMenuHandle::default();
  84            let session_picker_menu_handle = PopoverMenuHandle::default();
  85
  86            let focus_subscription = cx.on_focus(
  87                &focus_handle,
  88                window,
  89                |this: &mut DebugPanel, window, cx| {
  90                    this.focus_active_item(window, cx);
  91                },
  92            );
  93
  94            Self {
  95                size: px(300.),
  96                sessions_with_children: Default::default(),
  97                active_session: None,
  98                focus_handle,
  99                breakpoint_list: BreakpointList::new(
 100                    None,
 101                    workspace.weak_handle(),
 102                    &project,
 103                    window,
 104                    cx,
 105                ),
 106                project,
 107                workspace: workspace.weak_handle(),
 108                context_menu: None,
 109                fs: workspace.app_state().fs.clone(),
 110                thread_picker_menu_handle,
 111                session_picker_menu_handle,
 112                is_zoomed: false,
 113                _subscriptions: [focus_subscription],
 114                debug_scenario_scheduled_last: true,
 115            }
 116        })
 117    }
 118
 119    pub(crate) fn focus_active_item(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 120        let Some(session) = self.active_session.clone() else {
 121            return;
 122        };
 123        let active_pane = session
 124            .read(cx)
 125            .running_state()
 126            .read(cx)
 127            .active_pane()
 128            .clone();
 129        active_pane.update(cx, |pane, cx| {
 130            pane.focus_active_item(window, cx);
 131        });
 132    }
 133
 134    #[cfg(test)]
 135    pub(crate) fn sessions(&self) -> impl Iterator<Item = Entity<DebugSession>> {
 136        self.sessions_with_children.keys().cloned()
 137    }
 138
 139    pub fn active_session(&self) -> Option<Entity<DebugSession>> {
 140        self.active_session.clone()
 141    }
 142
 143    pub(crate) fn running_state(&self, cx: &mut App) -> Option<Entity<RunningState>> {
 144        self.active_session()
 145            .map(|session| session.read(cx).running_state().clone())
 146    }
 147
 148    pub fn project(&self) -> &Entity<Project> {
 149        &self.project
 150    }
 151
 152    pub fn load(
 153        workspace: WeakEntity<Workspace>,
 154        cx: &mut AsyncWindowContext,
 155    ) -> Task<Result<Entity<Self>>> {
 156        cx.spawn(async move |cx| {
 157            workspace.update_in(cx, |workspace, window, cx| {
 158                let debug_panel = DebugPanel::new(workspace, window, cx);
 159
 160                workspace.register_action(|workspace, _: &ClearAllBreakpoints, _, cx| {
 161                    workspace.project().read(cx).breakpoint_store().update(
 162                        cx,
 163                        |breakpoint_store, cx| {
 164                            breakpoint_store.clear_breakpoints(cx);
 165                        },
 166                    )
 167                });
 168
 169                workspace.set_debugger_provider(DebuggerProvider(debug_panel.clone()));
 170
 171                debug_panel
 172            })
 173        })
 174    }
 175
 176    pub fn start_session(
 177        &mut self,
 178        scenario: DebugScenario,
 179        task_context: SharedTaskContext,
 180        active_buffer: Option<Entity<Buffer>>,
 181        worktree_id: Option<WorktreeId>,
 182        window: &mut Window,
 183        cx: &mut Context<Self>,
 184    ) {
 185        let dap_store = self.project.read(cx).dap_store();
 186        let Some(adapter) = DapRegistry::global(cx).adapter(&scenario.adapter) else {
 187            return;
 188        };
 189        let quirks = SessionQuirks {
 190            compact: adapter.compact_child_session(),
 191            prefer_thread_name: adapter.prefer_thread_name(),
 192        };
 193        let session = dap_store.update(cx, |dap_store, cx| {
 194            dap_store.new_session(
 195                Some(scenario.label.clone()),
 196                DebugAdapterName(scenario.adapter.clone()),
 197                task_context.clone(),
 198                None,
 199                quirks,
 200                cx,
 201            )
 202        });
 203        let worktree = worktree_id.or_else(|| {
 204            active_buffer
 205                .as_ref()
 206                .and_then(|buffer| buffer.read(cx).file())
 207                .map(|f| f.worktree_id(cx))
 208        });
 209
 210        let Some(worktree) = worktree
 211            .and_then(|id| self.project.read(cx).worktree_for_id(id, cx))
 212            .or_else(|| self.project.read(cx).visible_worktrees(cx).next())
 213        else {
 214            log::debug!("Could not find a worktree to spawn the debug session in");
 215            return;
 216        };
 217
 218        self.debug_scenario_scheduled_last = true;
 219        if let Some(inventory) = self
 220            .project
 221            .read(cx)
 222            .task_store()
 223            .read(cx)
 224            .task_inventory()
 225            .cloned()
 226        {
 227            inventory.update(cx, |inventory, _| {
 228                inventory.scenario_scheduled(
 229                    scenario.clone(),
 230                    task_context.clone(),
 231                    worktree_id,
 232                    active_buffer.as_ref().map(|buffer| buffer.downgrade()),
 233                );
 234            })
 235        }
 236        let task = cx.spawn_in(window, {
 237            let session = session.clone();
 238            async move |this, cx| {
 239                let debug_session =
 240                    Self::register_session(this.clone(), session.clone(), true, cx).await?;
 241                let definition = debug_session
 242                    .update_in(cx, |debug_session, window, cx| {
 243                        debug_session.running_state().update(cx, |running, cx| {
 244                            if scenario.build.is_some() {
 245                                running.scenario = Some(scenario.clone());
 246                                running.scenario_context = Some(DebugScenarioContext {
 247                                    active_buffer: active_buffer
 248                                        .as_ref()
 249                                        .map(|entity| entity.downgrade()),
 250                                    task_context: task_context.clone(),
 251                                    worktree_id,
 252                                });
 253                            };
 254                            running.resolve_scenario(
 255                                scenario,
 256                                task_context,
 257                                active_buffer,
 258                                worktree_id,
 259                                window,
 260                                cx,
 261                            )
 262                        })
 263                    })?
 264                    .await?;
 265                dap_store
 266                    .update(cx, |dap_store, cx| {
 267                        dap_store.boot_session(session.clone(), definition, worktree, cx)
 268                    })
 269                    .await
 270            }
 271        });
 272
 273        let boot_task = cx.spawn({
 274            let session = session.clone();
 275
 276            async move |_, cx| {
 277                if let Err(error) = task.await {
 278                    log::error!("{error:#}");
 279                    session
 280                        .update(cx, |session, cx| {
 281                            session
 282                                .console_output(cx)
 283                                .unbounded_send(format!("error: {:#}", error))
 284                                .ok();
 285                            session.shutdown(cx)
 286                        })
 287                        .await;
 288                }
 289                anyhow::Ok(())
 290            }
 291        });
 292
 293        session.update(cx, |session, _| match &mut session.state {
 294            SessionState::Booting(state_task) => {
 295                *state_task = Some(boot_task);
 296            }
 297            SessionState::Running(_) => {
 298                debug_panic!("Session state should be in building because we are just starting it");
 299            }
 300        });
 301    }
 302
 303    pub(crate) fn rerun_last_session(
 304        &mut self,
 305        workspace: &mut Workspace,
 306        window: &mut Window,
 307        cx: &mut Context<Self>,
 308    ) {
 309        let task_store = workspace.project().read(cx).task_store().clone();
 310        let Some(task_inventory) = task_store.read(cx).task_inventory() else {
 311            return;
 312        };
 313        let workspace = self.workspace.clone();
 314        let Some((scenario, context)) = task_inventory.read(cx).last_scheduled_scenario().cloned()
 315        else {
 316            window.defer(cx, move |window, cx| {
 317                workspace
 318                    .update(cx, |workspace, cx| {
 319                        NewProcessModal::show(workspace, window, NewProcessMode::Debug, None, cx);
 320                    })
 321                    .ok();
 322            });
 323            return;
 324        };
 325
 326        let DebugScenarioContext {
 327            task_context,
 328            worktree_id,
 329            active_buffer,
 330        } = context;
 331
 332        let active_buffer = active_buffer.and_then(|buffer| buffer.upgrade());
 333
 334        self.start_session(
 335            scenario,
 336            task_context,
 337            active_buffer,
 338            worktree_id,
 339            window,
 340            cx,
 341        );
 342    }
 343
 344    pub(crate) async fn register_session(
 345        this: WeakEntity<Self>,
 346        session: Entity<Session>,
 347        focus: bool,
 348        cx: &mut AsyncWindowContext,
 349    ) -> Result<Entity<DebugSession>> {
 350        let debug_session = register_session_inner(&this, session, cx).await?;
 351
 352        let workspace = this.update_in(cx, |this, window, cx| {
 353            if focus {
 354                this.activate_session(debug_session.clone(), window, cx);
 355            }
 356
 357            this.workspace.clone()
 358        })?;
 359        workspace.update_in(cx, |workspace, window, cx| {
 360            workspace.focus_panel::<Self>(window, cx);
 361        })?;
 362        Ok(debug_session)
 363    }
 364
 365    pub(crate) fn handle_restart_request(
 366        &mut self,
 367        mut curr_session: Entity<Session>,
 368        window: &mut Window,
 369        cx: &mut Context<Self>,
 370    ) {
 371        while let Some(parent_session) = curr_session.read(cx).parent_session().cloned() {
 372            curr_session = parent_session;
 373        }
 374
 375        let Some(worktree) = curr_session.read(cx).worktree() else {
 376            log::error!("Attempted to restart a non-running session");
 377            return;
 378        };
 379
 380        let dap_store_handle = self.project.read(cx).dap_store();
 381        let label = curr_session.read(cx).label();
 382        let quirks = curr_session.read(cx).quirks();
 383        let adapter = curr_session.read(cx).adapter();
 384        let binary = curr_session.read(cx).binary().cloned().unwrap();
 385        let task_context = curr_session.read(cx).task_context().clone();
 386
 387        let curr_session_id = curr_session.read(cx).session_id();
 388        self.sessions_with_children
 389            .retain(|session, _| session.read(cx).session_id(cx) != curr_session_id);
 390        let task = dap_store_handle.update(cx, |dap_store, cx| {
 391            dap_store.shutdown_session(curr_session_id, cx)
 392        });
 393
 394        cx.spawn_in(window, async move |this, cx| {
 395            task.await.log_err();
 396
 397            let (session, task) = dap_store_handle.update(cx, |dap_store, cx| {
 398                let session = dap_store.new_session(label, adapter, task_context, None, quirks, cx);
 399
 400                let task = session.update(cx, |session, cx| {
 401                    session.boot(binary, worktree, dap_store_handle.downgrade(), cx)
 402                });
 403                (session, task)
 404            });
 405            Self::register_session(this.clone(), session.clone(), true, cx).await?;
 406
 407            if let Err(error) = task.await {
 408                session
 409                    .update(cx, |session, cx| {
 410                        session
 411                            .console_output(cx)
 412                            .unbounded_send(format!(
 413                                "Session failed to restart with error: {}",
 414                                error
 415                            ))
 416                            .ok();
 417                        session.shutdown(cx)
 418                    })
 419                    .await;
 420
 421                return Err(error);
 422            };
 423
 424            Ok(())
 425        })
 426        .detach_and_log_err(cx);
 427    }
 428
 429    pub fn handle_start_debugging_request(
 430        &mut self,
 431        request: &StartDebuggingRequestArguments,
 432        parent_session: Entity<Session>,
 433        window: &mut Window,
 434        cx: &mut Context<Self>,
 435    ) {
 436        let Some(worktree) = parent_session.read(cx).worktree() else {
 437            log::error!("Attempted to start a child-session from a non-running session");
 438            return;
 439        };
 440
 441        let dap_store_handle = self.project.read(cx).dap_store();
 442        let label = self.label_for_child_session(&parent_session, request, cx);
 443        let adapter = parent_session.read(cx).adapter();
 444        let quirks = parent_session.read(cx).quirks();
 445        let Some(mut binary) = parent_session.read(cx).binary().cloned() else {
 446            log::error!("Attempted to start a child-session without a binary");
 447            return;
 448        };
 449        let task_context = parent_session.read(cx).task_context().clone();
 450        binary.request_args = request.clone();
 451        cx.spawn_in(window, async move |this, cx| {
 452            let (session, task) = dap_store_handle.update(cx, |dap_store, cx| {
 453                let session = dap_store.new_session(
 454                    label,
 455                    adapter,
 456                    task_context,
 457                    Some(parent_session.clone()),
 458                    quirks,
 459                    cx,
 460                );
 461
 462                let task = session.update(cx, |session, cx| {
 463                    session.boot(binary, worktree, dap_store_handle.downgrade(), cx)
 464                });
 465                (session, task)
 466            });
 467            // Focus child sessions if the parent has never emitted a stopped event;
 468            // this improves our JavaScript experience, as it always spawns a "main" session that then spawns subsessions.
 469            let parent_ever_stopped = parent_session.update(cx, |this, _| this.has_ever_stopped());
 470            Self::register_session(this, session, !parent_ever_stopped, cx).await?;
 471            task.await
 472        })
 473        .detach_and_log_err(cx);
 474    }
 475
 476    pub(crate) fn close_session(
 477        &mut self,
 478        entity_id: EntityId,
 479        window: &mut Window,
 480        cx: &mut Context<Self>,
 481    ) {
 482        let Some(session) = self
 483            .sessions_with_children
 484            .keys()
 485            .find(|other| entity_id == other.entity_id())
 486            .cloned()
 487        else {
 488            return;
 489        };
 490        session.update(cx, |this, cx| {
 491            this.running_state().update(cx, |this, cx| {
 492                this.serialize_layout(window, cx);
 493            });
 494        });
 495        let session_id = session.update(cx, |this, cx| this.session_id(cx));
 496        let should_prompt = self
 497            .project
 498            .update(cx, |this, cx| {
 499                let session = this.dap_store().read(cx).session_by_id(session_id);
 500                session.map(|session| !session.read(cx).is_terminated())
 501            })
 502            .unwrap_or_default();
 503
 504        cx.spawn_in(window, async move |this, cx| {
 505            if should_prompt {
 506                let response = cx.prompt(
 507                    gpui::PromptLevel::Warning,
 508                    "This Debug Session is still running. Are you sure you want to terminate it?",
 509                    None,
 510                    &["Yes", "No"],
 511                );
 512                if response.await == Ok(1) {
 513                    return;
 514                }
 515            }
 516            session.update(cx, |session, cx| session.shutdown(cx));
 517            this.update(cx, |this, cx| {
 518                this.retain_sessions(|other| entity_id != other.entity_id());
 519                if let Some(active_session_id) = this
 520                    .active_session
 521                    .as_ref()
 522                    .map(|session| session.entity_id())
 523                    && active_session_id == entity_id
 524                {
 525                    this.active_session = this.sessions_with_children.keys().next().cloned();
 526                }
 527                cx.notify()
 528            })
 529            .ok();
 530        })
 531        .detach();
 532    }
 533
 534    pub(crate) fn deploy_context_menu(
 535        &mut self,
 536        position: Point<Pixels>,
 537        window: &mut Window,
 538        cx: &mut Context<Self>,
 539    ) {
 540        if let Some(running_state) = self
 541            .active_session
 542            .as_ref()
 543            .map(|session| session.read(cx).running_state().clone())
 544        {
 545            let pane_items_status = running_state.read(cx).pane_items_status(cx);
 546            let this = cx.weak_entity();
 547
 548            let context_menu = ContextMenu::build(window, cx, |mut menu, _window, _cx| {
 549                for (item_kind, is_visible) in pane_items_status.into_iter() {
 550                    menu = menu.toggleable_entry(item_kind, is_visible, IconPosition::End, None, {
 551                        let this = this.clone();
 552                        move |window, cx| {
 553                            this.update(cx, |this, cx| {
 554                                if let Some(running_state) = this
 555                                    .active_session
 556                                    .as_ref()
 557                                    .map(|session| session.read(cx).running_state().clone())
 558                                {
 559                                    running_state.update(cx, |state, cx| {
 560                                        if is_visible {
 561                                            state.remove_pane_item(item_kind, window, cx);
 562                                        } else {
 563                                            state.add_pane_item(item_kind, position, window, cx);
 564                                        }
 565                                    })
 566                                }
 567                            })
 568                            .ok();
 569                        }
 570                    });
 571                }
 572
 573                menu
 574            });
 575
 576            window.focus(&context_menu.focus_handle(cx), cx);
 577            let subscription = cx.subscribe(&context_menu, |this, _, _: &DismissEvent, cx| {
 578                this.context_menu.take();
 579                cx.notify();
 580            });
 581            self.context_menu = Some((context_menu, position, subscription));
 582        }
 583    }
 584
 585    fn copy_debug_adapter_arguments(
 586        &mut self,
 587        _: &CopyDebugAdapterArguments,
 588        _window: &mut Window,
 589        cx: &mut Context<Self>,
 590    ) {
 591        let content = maybe!({
 592            let mut session = self.active_session()?.read(cx).session(cx);
 593            while let Some(parent) = session.read(cx).parent_session().cloned() {
 594                session = parent;
 595            }
 596            let binary = session.read(cx).binary()?;
 597            let content = serde_json::to_string_pretty(&binary).ok()?;
 598            Some(content)
 599        });
 600        if let Some(content) = content {
 601            cx.write_to_clipboard(ClipboardItem::new_string(content));
 602        }
 603    }
 604
 605    pub(crate) fn top_controls_strip(
 606        &mut self,
 607        window: &mut Window,
 608        cx: &mut Context<Self>,
 609    ) -> Option<Div> {
 610        let active_session = self.active_session.clone();
 611        let focus_handle = self.focus_handle.clone();
 612        let is_side = self.position(window, cx).axis() == gpui::Axis::Horizontal;
 613        let div = if is_side { v_flex() } else { h_flex() };
 614
 615        let new_session_button = || {
 616            IconButton::new("debug-new-session", IconName::Plus)
 617                .icon_size(IconSize::Small)
 618                .on_click({
 619                    move |_, window, cx| window.dispatch_action(crate::Start.boxed_clone(), cx)
 620                })
 621                .tooltip({
 622                    let focus_handle = focus_handle.clone();
 623                    move |_window, cx| {
 624                        Tooltip::for_action_in(
 625                            "Start Debug Session",
 626                            &crate::Start,
 627                            &focus_handle,
 628                            cx,
 629                        )
 630                    }
 631                })
 632        };
 633
 634        let edit_debug_json_button = || {
 635            IconButton::new("debug-edit-debug-json", IconName::Code)
 636                .icon_size(IconSize::Small)
 637                .on_click(|_, window, cx| {
 638                    window.dispatch_action(zed_actions::OpenProjectDebugTasks.boxed_clone(), cx);
 639                })
 640                .tooltip(Tooltip::text("Edit debug.json"))
 641        };
 642
 643        let documentation_button = || {
 644            IconButton::new("debug-open-documentation", IconName::CircleHelp)
 645                .icon_size(IconSize::Small)
 646                .on_click(move |_, _, cx| cx.open_url("https://zed.dev/docs/debugger"))
 647                .tooltip(Tooltip::text("Open Documentation"))
 648        };
 649
 650        let logs_button = || {
 651            IconButton::new("debug-open-logs", IconName::Notepad)
 652                .icon_size(IconSize::Small)
 653                .on_click(move |_, window, cx| {
 654                    window.dispatch_action(debugger_tools::OpenDebugAdapterLogs.boxed_clone(), cx)
 655                })
 656                .tooltip(Tooltip::text("Open Debug Adapter Logs"))
 657        };
 658
 659        let close_bottom_panel_button = {
 660            h_flex().pl_0p5().gap_1().child(Divider::vertical()).child(
 661                IconButton::new("debug-close-panel", IconName::Close)
 662                    .icon_size(IconSize::Small)
 663                    .on_click(move |_, window, cx| {
 664                        window.dispatch_action(workspace::ToggleBottomDock.boxed_clone(), cx)
 665                    })
 666                    .tooltip(Tooltip::text("Close Panel")),
 667            )
 668        };
 669
 670        let thread_status = active_session
 671            .as_ref()
 672            .map(|session| session.read(cx).running_state())
 673            .and_then(|state| state.read(cx).thread_status(cx))
 674            .unwrap_or(project::debugger::session::ThreadStatus::Exited);
 675
 676        Some(
 677            div.w_full()
 678                .py_1()
 679                .px_1p5()
 680                .justify_between()
 681                .border_b_1()
 682                .border_color(cx.theme().colors().border)
 683                .when(is_side, |this| this.gap_1().h(Tab::container_height(cx)))
 684                .child(
 685                    h_flex()
 686                        .justify_between()
 687                        .child(
 688                            h_flex().gap_1().w_full().when_some(
 689                                active_session
 690                                    .as_ref()
 691                                    .map(|session| session.read(cx).running_state()),
 692                                |this, running_state| {
 693                                    let capabilities = running_state.read(cx).capabilities(cx);
 694                                    let supports_detach =
 695                                        running_state.read(cx).session().read(cx).is_attached();
 696
 697                                    this.map(|this| {
 698                                        if thread_status == ThreadStatus::Running {
 699                                            this.child(
 700                                                IconButton::new(
 701                                                    "debug-pause",
 702                                                    IconName::DebugPause,
 703                                                )
 704                                                .icon_size(IconSize::Small)
 705                                                .on_click(window.listener_for(
 706                                                    running_state,
 707                                                    |this, _, _window, cx| {
 708                                                        this.pause_thread(cx);
 709                                                    },
 710                                                ))
 711                                                .tooltip({
 712                                                    let focus_handle = focus_handle.clone();
 713                                                    move |_window, cx| {
 714                                                        Tooltip::for_action_in(
 715                                                            "Pause Program",
 716                                                            &Pause,
 717                                                            &focus_handle,
 718                                                            cx,
 719                                                        )
 720                                                    }
 721                                                }),
 722                                            )
 723                                        } else {
 724                                            this.child(
 725                                                IconButton::new(
 726                                                    "debug-continue",
 727                                                    IconName::DebugContinue,
 728                                                )
 729                                                .icon_size(IconSize::Small)
 730                                                .on_click(window.listener_for(
 731                                                    running_state,
 732                                                    |this, _, _window, cx| this.continue_thread(cx),
 733                                                ))
 734                                                .disabled(thread_status != ThreadStatus::Stopped)
 735                                                .tooltip({
 736                                                    let focus_handle = focus_handle.clone();
 737                                                    move |_window, cx| {
 738                                                        Tooltip::for_action_in(
 739                                                            "Continue Program",
 740                                                            &Continue,
 741                                                            &focus_handle,
 742                                                            cx,
 743                                                        )
 744                                                    }
 745                                                }),
 746                                            )
 747                                        }
 748                                    })
 749                                    .child(
 750                                        IconButton::new("step-over", IconName::DebugStepOver)
 751                                            .icon_size(IconSize::Small)
 752                                            .on_click(window.listener_for(
 753                                                running_state,
 754                                                |this, _, _window, cx| {
 755                                                    this.step_over(cx);
 756                                                },
 757                                            ))
 758                                            .disabled(thread_status != ThreadStatus::Stopped)
 759                                            .tooltip({
 760                                                let focus_handle = focus_handle.clone();
 761                                                move |_window, cx| {
 762                                                    Tooltip::for_action_in(
 763                                                        "Step Over",
 764                                                        &StepOver,
 765                                                        &focus_handle,
 766                                                        cx,
 767                                                    )
 768                                                }
 769                                            }),
 770                                    )
 771                                    .child(
 772                                        IconButton::new("step-into", IconName::DebugStepInto)
 773                                            .icon_size(IconSize::Small)
 774                                            .on_click(window.listener_for(
 775                                                running_state,
 776                                                |this, _, _window, cx| {
 777                                                    this.step_in(cx);
 778                                                },
 779                                            ))
 780                                            .disabled(thread_status != ThreadStatus::Stopped)
 781                                            .tooltip({
 782                                                let focus_handle = focus_handle.clone();
 783                                                move |_window, cx| {
 784                                                    Tooltip::for_action_in(
 785                                                        "Step In",
 786                                                        &StepInto,
 787                                                        &focus_handle,
 788                                                        cx,
 789                                                    )
 790                                                }
 791                                            }),
 792                                    )
 793                                    .child(
 794                                        IconButton::new("step-out", IconName::DebugStepOut)
 795                                            .icon_size(IconSize::Small)
 796                                            .on_click(window.listener_for(
 797                                                running_state,
 798                                                |this, _, _window, cx| {
 799                                                    this.step_out(cx);
 800                                                },
 801                                            ))
 802                                            .disabled(thread_status != ThreadStatus::Stopped)
 803                                            .tooltip({
 804                                                let focus_handle = focus_handle.clone();
 805                                                move |_window, cx| {
 806                                                    Tooltip::for_action_in(
 807                                                        "Step Out",
 808                                                        &StepOut,
 809                                                        &focus_handle,
 810                                                        cx,
 811                                                    )
 812                                                }
 813                                            }),
 814                                    )
 815                                    .child(Divider::vertical())
 816                                    .child(
 817                                        IconButton::new("debug-restart", IconName::RotateCcw)
 818                                            .icon_size(IconSize::Small)
 819                                            .on_click(window.listener_for(
 820                                                running_state,
 821                                                |this, _, window, cx| {
 822                                                    this.rerun_session(window, cx);
 823                                                },
 824                                            ))
 825                                            .tooltip({
 826                                                let focus_handle = focus_handle.clone();
 827                                                move |_window, cx| {
 828                                                    Tooltip::for_action_in(
 829                                                        "Rerun Session",
 830                                                        &RerunSession,
 831                                                        &focus_handle,
 832                                                        cx,
 833                                                    )
 834                                                }
 835                                            }),
 836                                    )
 837                                    .child(
 838                                        IconButton::new("debug-stop", IconName::Power)
 839                                            .icon_size(IconSize::Small)
 840                                            .on_click(window.listener_for(
 841                                                running_state,
 842                                                |this, _, _window, cx| {
 843                                                    if this.session().read(cx).is_building() {
 844                                                        this.session().update(cx, |session, cx| {
 845                                                            session.shutdown(cx).detach()
 846                                                        });
 847                                                    } else {
 848                                                        this.stop_thread(cx);
 849                                                    }
 850                                                },
 851                                            ))
 852                                            .disabled(active_session.as_ref().is_none_or(
 853                                                |session| {
 854                                                    session
 855                                                        .read(cx)
 856                                                        .session(cx)
 857                                                        .read(cx)
 858                                                        .is_terminated()
 859                                                },
 860                                            ))
 861                                            .tooltip({
 862                                                let focus_handle = focus_handle.clone();
 863                                                let label = if capabilities
 864                                                    .supports_terminate_threads_request
 865                                                    .unwrap_or_default()
 866                                                {
 867                                                    "Terminate Thread"
 868                                                } else {
 869                                                    "Terminate All Threads"
 870                                                };
 871                                                move |_window, cx| {
 872                                                    Tooltip::for_action_in(
 873                                                        label,
 874                                                        &Stop,
 875                                                        &focus_handle,
 876                                                        cx,
 877                                                    )
 878                                                }
 879                                            }),
 880                                    )
 881                                    .when(supports_detach, |div| {
 882                                        div.child(
 883                                            IconButton::new(
 884                                                "debug-disconnect",
 885                                                IconName::DebugDetach,
 886                                            )
 887                                            .disabled(
 888                                                thread_status != ThreadStatus::Stopped
 889                                                    && thread_status != ThreadStatus::Running,
 890                                            )
 891                                            .icon_size(IconSize::Small)
 892                                            .on_click(window.listener_for(
 893                                                running_state,
 894                                                |this, _, _, cx| {
 895                                                    this.detach_client(cx);
 896                                                },
 897                                            ))
 898                                            .tooltip({
 899                                                let focus_handle = focus_handle.clone();
 900                                                move |_window, cx| {
 901                                                    Tooltip::for_action_in(
 902                                                        "Detach",
 903                                                        &Detach,
 904                                                        &focus_handle,
 905                                                        cx,
 906                                                    )
 907                                                }
 908                                            }),
 909                                        )
 910                                    })
 911                                    .when(
 912                                        cx.has_flag::<DebuggerHistoryFeatureFlag>(),
 913                                        |this| {
 914                                            this.child(Divider::vertical()).child(
 915                                                SplitButton::new(
 916                                                    self.render_history_button(
 917                                                        &running_state,
 918                                                        thread_status,
 919                                                        window,
 920                                                    ),
 921                                                    self.render_history_toggle_button(
 922                                                        thread_status,
 923                                                        &running_state,
 924                                                    )
 925                                                    .into_any_element(),
 926                                                )
 927                                                .style(ui::SplitButtonStyle::Outlined),
 928                                            )
 929                                        },
 930                                    )
 931                                },
 932                            ),
 933                        )
 934                        .when(is_side, |this| {
 935                            this.child(new_session_button())
 936                                .child(edit_debug_json_button())
 937                                .child(documentation_button())
 938                                .child(logs_button())
 939                        }),
 940                )
 941                .child(
 942                    h_flex()
 943                        .gap_0p5()
 944                        .when(is_side, |this| this.justify_between())
 945                        .child(
 946                            h_flex().when_some(
 947                                active_session
 948                                    .as_ref()
 949                                    .map(|session| session.read(cx).running_state())
 950                                    .cloned(),
 951                                |this, running_state| {
 952                                    this.children({
 953                                        let threads =
 954                                            running_state.update(cx, |running_state, cx| {
 955                                                let session = running_state.session();
 956                                                session.read(cx).is_started().then(|| {
 957                                                    session.update(cx, |session, cx| {
 958                                                        session.threads(cx)
 959                                                    })
 960                                                })
 961                                            });
 962
 963                                        threads.and_then(|threads| {
 964                                            self.render_thread_dropdown(
 965                                                &running_state,
 966                                                threads,
 967                                                window,
 968                                                cx,
 969                                            )
 970                                        })
 971                                    })
 972                                    .when(!is_side, |this| {
 973                                        this.gap_0p5().child(Divider::vertical())
 974                                    })
 975                                },
 976                            ),
 977                        )
 978                        .child(
 979                            h_flex()
 980                                .gap_0p5()
 981                                .children(self.render_session_menu(
 982                                    self.active_session(),
 983                                    self.running_state(cx),
 984                                    window,
 985                                    cx,
 986                                ))
 987                                .when(!is_side, |this| {
 988                                    this.child(new_session_button())
 989                                        .child(edit_debug_json_button())
 990                                        .child(documentation_button())
 991                                        .child(logs_button())
 992                                        .child(close_bottom_panel_button)
 993                                }),
 994                        ),
 995                ),
 996        )
 997    }
 998
 999    pub(crate) fn activate_pane_in_direction(
1000        &mut self,
1001        direction: SplitDirection,
1002        window: &mut Window,
1003        cx: &mut Context<Self>,
1004    ) {
1005        if let Some(session) = self.active_session() {
1006            session.update(cx, |session, cx| {
1007                session.running_state().update(cx, |running, cx| {
1008                    running.activate_pane_in_direction(direction, window, cx);
1009                })
1010            });
1011        }
1012    }
1013
1014    pub(crate) fn activate_item(
1015        &mut self,
1016        item: DebuggerPaneItem,
1017        window: &mut Window,
1018        cx: &mut Context<Self>,
1019    ) {
1020        if let Some(session) = self.active_session() {
1021            session.update(cx, |session, cx| {
1022                session.running_state().update(cx, |running, cx| {
1023                    running.activate_item(item, window, cx);
1024                });
1025            });
1026        }
1027    }
1028
1029    pub(crate) fn activate_session_by_id(
1030        &mut self,
1031        session_id: SessionId,
1032        window: &mut Window,
1033        cx: &mut Context<Self>,
1034    ) {
1035        if let Some(session) = self
1036            .sessions_with_children
1037            .keys()
1038            .find(|session| session.read(cx).session_id(cx) == session_id)
1039        {
1040            self.activate_session(session.clone(), window, cx);
1041        }
1042    }
1043
1044    pub(crate) fn activate_session(
1045        &mut self,
1046        session_item: Entity<DebugSession>,
1047        window: &mut Window,
1048        cx: &mut Context<Self>,
1049    ) {
1050        debug_assert!(self.sessions_with_children.contains_key(&session_item));
1051        session_item.focus_handle(cx).focus(window, cx);
1052        session_item.update(cx, |this, cx| {
1053            this.running_state().update(cx, |this, cx| {
1054                this.go_to_selected_stack_frame(window, cx);
1055            });
1056        });
1057        self.active_session = Some(session_item);
1058        cx.notify();
1059    }
1060
1061    pub(crate) fn go_to_scenario_definition(
1062        &self,
1063        kind: TaskSourceKind,
1064        scenario: DebugScenario,
1065        worktree_id: WorktreeId,
1066        window: &mut Window,
1067        cx: &mut Context<Self>,
1068    ) -> Task<Result<()>> {
1069        let Some(workspace) = self.workspace.upgrade() else {
1070            return Task::ready(Ok(()));
1071        };
1072        let project_path = match kind {
1073            TaskSourceKind::AbsPath { abs_path, .. } => {
1074                let Some(project_path) = workspace
1075                    .read(cx)
1076                    .project()
1077                    .read(cx)
1078                    .project_path_for_absolute_path(&abs_path, cx)
1079                else {
1080                    return Task::ready(Err(anyhow!("no abs path")));
1081                };
1082
1083                project_path
1084            }
1085            TaskSourceKind::Worktree {
1086                id,
1087                directory_in_worktree: dir,
1088                ..
1089            } => {
1090                let relative_path = if dir.ends_with(RelPath::unix(".vscode").unwrap()) {
1091                    dir.join(RelPath::unix("launch.json").unwrap())
1092                } else {
1093                    dir.join(RelPath::unix("debug.json").unwrap())
1094                };
1095                ProjectPath {
1096                    worktree_id: id,
1097                    path: relative_path,
1098                }
1099            }
1100            _ => return self.save_scenario(scenario, worktree_id, window, cx),
1101        };
1102
1103        let editor = workspace.update(cx, |workspace, cx| {
1104            workspace.open_path(project_path, None, true, window, cx)
1105        });
1106        cx.spawn_in(window, async move |_, cx| {
1107            let editor = editor.await?;
1108            let editor = cx
1109                .update(|_, cx| editor.act_as::<Editor>(cx))?
1110                .context("expected editor")?;
1111
1112            // unfortunately debug tasks don't have an easy way to globally
1113            // identify them. to jump to the one that you just created or an
1114            // old one that you're choosing to edit we use a heuristic of searching for a line with `label:  <your label>` from the end rather than the start so we bias towards more renctly
1115            editor.update_in(cx, |editor, window, cx| {
1116                let row = editor.text(cx).lines().enumerate().find_map(|(row, text)| {
1117                    if text.contains(scenario.label.as_ref()) && text.contains("\"label\": ") {
1118                        Some(row)
1119                    } else {
1120                        None
1121                    }
1122                });
1123                if let Some(row) = row {
1124                    editor.go_to_singleton_buffer_point(
1125                        text::Point::new(row as u32, 4),
1126                        window,
1127                        cx,
1128                    );
1129                }
1130            })?;
1131
1132            Ok(())
1133        })
1134    }
1135
1136    pub(crate) fn save_scenario(
1137        &self,
1138        scenario: DebugScenario,
1139        worktree_id: WorktreeId,
1140        window: &mut Window,
1141        cx: &mut Context<Self>,
1142    ) -> Task<Result<()>> {
1143        let this = cx.weak_entity();
1144        let project = self.project.clone();
1145        self.workspace
1146            .update(cx, |workspace, cx| {
1147                let Some(mut path) = workspace.absolute_path_of_worktree(worktree_id, cx) else {
1148                    return Task::ready(Err(anyhow!("Couldn't get worktree path")));
1149                };
1150
1151                let serialized_scenario = serde_json::to_value(scenario);
1152
1153                cx.spawn_in(window, async move |workspace, cx| {
1154                    let serialized_scenario = serialized_scenario?;
1155                    let fs =
1156                        workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
1157
1158                    path.push(paths::local_settings_folder_name());
1159                    if !fs.is_dir(path.as_path()).await {
1160                        fs.create_dir(path.as_path()).await?;
1161                    }
1162                    path.pop();
1163
1164                    path.push(paths::local_debug_file_relative_path().as_std_path());
1165                    let path = path.as_path();
1166
1167                    if !fs.is_file(path).await {
1168                        fs.create_file(path, Default::default()).await?;
1169                        fs.write(
1170                            path,
1171                            settings::initial_local_debug_tasks_content()
1172                                .to_string()
1173                                .as_bytes(),
1174                        )
1175                        .await?;
1176                    }
1177                    let project_path = workspace.update(cx, |workspace, cx| {
1178                        workspace
1179                            .project()
1180                            .read(cx)
1181                            .project_path_for_absolute_path(path, cx)
1182                            .context(
1183                                "Couldn't get project path for .zed/debug.json in active worktree",
1184                            )
1185                    })??;
1186
1187                    let editor = this
1188                        .update_in(cx, |this, window, cx| {
1189                            this.workspace.update(cx, |workspace, cx| {
1190                                workspace.open_path(project_path, None, true, window, cx)
1191                            })
1192                        })??
1193                        .await?;
1194                    let editor = cx
1195                        .update(|_, cx| editor.act_as::<Editor>(cx))?
1196                        .context("expected editor")?;
1197
1198                    let new_scenario = serde_json_lenient::to_string_pretty(&serialized_scenario)?
1199                        .lines()
1200                        .map(|l| format!("  {l}"))
1201                        .join("\n");
1202
1203                    editor
1204                        .update_in(cx, |editor, window, cx| {
1205                            Self::insert_task_into_editor(editor, new_scenario, project, window, cx)
1206                        })??
1207                        .await
1208                })
1209            })
1210            .unwrap_or_else(|err| Task::ready(Err(err)))
1211    }
1212
1213    pub fn insert_task_into_editor(
1214        editor: &mut Editor,
1215        new_scenario: String,
1216        project: Entity<Project>,
1217        window: &mut Window,
1218        cx: &mut Context<Editor>,
1219    ) -> Result<Task<Result<()>>> {
1220        static LAST_ITEM_QUERY: LazyLock<Query> = LazyLock::new(|| {
1221            Query::new(
1222                &tree_sitter_json::LANGUAGE.into(),
1223                "(document (array (object) @object))", // TODO: use "." anchor to only match last object
1224            )
1225            .expect("Failed to create LAST_ITEM_QUERY")
1226        });
1227        static EMPTY_ARRAY_QUERY: LazyLock<Query> = LazyLock::new(|| {
1228            Query::new(
1229                &tree_sitter_json::LANGUAGE.into(),
1230                "(document (array) @array)",
1231            )
1232            .expect("Failed to create EMPTY_ARRAY_QUERY")
1233        });
1234
1235        let content = editor.text(cx);
1236        let mut parser = tree_sitter::Parser::new();
1237        parser.set_language(&tree_sitter_json::LANGUAGE.into())?;
1238        let mut cursor = tree_sitter::QueryCursor::new();
1239        let syntax_tree = parser
1240            .parse(&content, None)
1241            .context("could not parse debug.json")?;
1242        let mut matches = cursor.matches(
1243            &LAST_ITEM_QUERY,
1244            syntax_tree.root_node(),
1245            content.as_bytes(),
1246        );
1247
1248        let mut last_offset = None;
1249        while let Some(mat) = matches.next() {
1250            if let Some(pos) = mat.captures.first().map(|m| m.node.byte_range().end) {
1251                last_offset = Some(MultiBufferOffset(pos))
1252            }
1253        }
1254        let mut edits = Vec::new();
1255        let mut cursor_position = MultiBufferOffset(0);
1256
1257        if let Some(pos) = last_offset {
1258            edits.push((pos..pos, format!(",\n{new_scenario}")));
1259            cursor_position = pos + ",\n  ".len();
1260        } else {
1261            let mut matches = cursor.matches(
1262                &EMPTY_ARRAY_QUERY,
1263                syntax_tree.root_node(),
1264                content.as_bytes(),
1265            );
1266
1267            if let Some(mat) = matches.next() {
1268                if let Some(pos) = mat.captures.first().map(|m| m.node.byte_range().end - 1) {
1269                    edits.push((
1270                        MultiBufferOffset(pos)..MultiBufferOffset(pos),
1271                        format!("\n{new_scenario}\n"),
1272                    ));
1273                    cursor_position = MultiBufferOffset(pos) + "\n  ".len();
1274                }
1275            } else {
1276                edits.push((
1277                    MultiBufferOffset(0)..MultiBufferOffset(0),
1278                    format!("[\n{}\n]", new_scenario),
1279                ));
1280                cursor_position = MultiBufferOffset("[\n  ".len());
1281            }
1282        }
1283        editor.transact(window, cx, |editor, window, cx| {
1284            editor.edit(edits, cx);
1285            let snapshot = editor.buffer().read(cx).read(cx);
1286            let point = cursor_position.to_point(&snapshot);
1287            drop(snapshot);
1288            editor.go_to_singleton_buffer_point(point, window, cx);
1289        });
1290        Ok(editor.save(SaveOptions::default(), project, window, cx))
1291    }
1292
1293    pub(crate) fn toggle_thread_picker(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1294        self.thread_picker_menu_handle.toggle(window, cx);
1295    }
1296
1297    pub(crate) fn toggle_session_picker(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1298        self.session_picker_menu_handle.toggle(window, cx);
1299    }
1300
1301    fn toggle_zoom(
1302        &mut self,
1303        _: &workspace::ToggleZoom,
1304        window: &mut Window,
1305        cx: &mut Context<Self>,
1306    ) {
1307        if self.is_zoomed {
1308            cx.emit(PanelEvent::ZoomOut);
1309        } else {
1310            if !self.focus_handle(cx).contains_focused(window, cx) {
1311                cx.focus_self(window);
1312            }
1313            cx.emit(PanelEvent::ZoomIn);
1314        }
1315    }
1316
1317    fn label_for_child_session(
1318        &self,
1319        parent_session: &Entity<Session>,
1320        request: &StartDebuggingRequestArguments,
1321        cx: &mut Context<'_, Self>,
1322    ) -> Option<SharedString> {
1323        let adapter = parent_session.read(cx).adapter();
1324        if let Some(adapter) = DapRegistry::global(cx).adapter(&adapter)
1325            && let Some(label) = adapter.label_for_child_session(request)
1326        {
1327            return Some(label.into());
1328        }
1329        None
1330    }
1331
1332    fn retain_sessions(&mut self, keep: impl Fn(&Entity<DebugSession>) -> bool) {
1333        self.sessions_with_children
1334            .retain(|session, _| keep(session));
1335        for children in self.sessions_with_children.values_mut() {
1336            children.retain(|child| {
1337                let Some(child) = child.upgrade() else {
1338                    return false;
1339                };
1340                keep(&child)
1341            });
1342        }
1343    }
1344
1345    fn render_history_button(
1346        &self,
1347        running_state: &Entity<RunningState>,
1348        thread_status: ThreadStatus,
1349        window: &mut Window,
1350    ) -> IconButton {
1351        IconButton::new("debug-back-in-history", IconName::HistoryRerun)
1352            .icon_size(IconSize::Small)
1353            .on_click(window.listener_for(running_state, |this, _, _window, cx| {
1354                this.session().update(cx, |session, cx| {
1355                    let ix = session
1356                        .active_snapshot_index()
1357                        .unwrap_or_else(|| session.historic_snapshots().len());
1358
1359                    session.select_historic_snapshot(Some(ix.saturating_sub(1)), cx);
1360                })
1361            }))
1362            .disabled(
1363                thread_status == ThreadStatus::Running || thread_status == ThreadStatus::Stepping,
1364            )
1365    }
1366
1367    fn render_history_toggle_button(
1368        &self,
1369        thread_status: ThreadStatus,
1370        running_state: &Entity<RunningState>,
1371    ) -> impl IntoElement {
1372        PopoverMenu::new("debug-back-in-history-menu")
1373            .trigger(
1374                ui::ButtonLike::new_rounded_right("debug-back-in-history-menu-trigger")
1375                    .layer(ui::ElevationIndex::ModalSurface)
1376                    .size(ui::ButtonSize::None)
1377                    .child(
1378                        div()
1379                            .px_1()
1380                            .child(Icon::new(IconName::ChevronDown).size(IconSize::XSmall)),
1381                    )
1382                    .disabled(
1383                        thread_status == ThreadStatus::Running
1384                            || thread_status == ThreadStatus::Stepping,
1385                    ),
1386            )
1387            .menu({
1388                let running_state = running_state.clone();
1389                move |window, cx| {
1390                    let handler =
1391                        |ix: Option<usize>, running_state: Entity<RunningState>, cx: &mut App| {
1392                            running_state.update(cx, |state, cx| {
1393                                state.session().update(cx, |session, cx| {
1394                                    session.select_historic_snapshot(ix, cx);
1395                                })
1396                            })
1397                        };
1398
1399                    let running_state = running_state.clone();
1400                    Some(ContextMenu::build(
1401                        window,
1402                        cx,
1403                        move |mut context_menu, _window, cx| {
1404                            let history = running_state
1405                                .read(cx)
1406                                .session()
1407                                .read(cx)
1408                                .historic_snapshots();
1409
1410                            context_menu = context_menu.entry("Current State", None, {
1411                                let running_state = running_state.clone();
1412                                move |_window, cx| {
1413                                    handler(None, running_state.clone(), cx);
1414                                }
1415                            });
1416                            context_menu = context_menu.separator();
1417
1418                            for (ix, _) in history.iter().enumerate().rev() {
1419                                context_menu =
1420                                    context_menu.entry(format!("history-{}", ix + 1), None, {
1421                                        let running_state = running_state.clone();
1422                                        move |_window, cx| {
1423                                            handler(Some(ix), running_state.clone(), cx);
1424                                        }
1425                                    });
1426                            }
1427
1428                            context_menu
1429                        },
1430                    ))
1431                }
1432            })
1433            .anchor(Corner::TopRight)
1434    }
1435}
1436
1437async fn register_session_inner(
1438    this: &WeakEntity<DebugPanel>,
1439    session: Entity<Session>,
1440    cx: &mut AsyncWindowContext,
1441) -> Result<Entity<DebugSession>> {
1442    let adapter_name = session.read_with(cx, |session, _| session.adapter());
1443    this.update_in(cx, |_, window, cx| {
1444        cx.subscribe_in(
1445            &session,
1446            window,
1447            move |this, session, event: &SessionStateEvent, window, cx| match event {
1448                SessionStateEvent::Restart => {
1449                    this.handle_restart_request(session.clone(), window, cx);
1450                }
1451                SessionStateEvent::SpawnChildSession { request } => {
1452                    this.handle_start_debugging_request(request, session.clone(), window, cx);
1453                }
1454                _ => {}
1455            },
1456        )
1457        .detach();
1458    })
1459    .ok();
1460    let serialized_layout = persistence::get_serialized_layout(adapter_name).await;
1461    let debug_session = this.update_in(cx, |this, window, cx| {
1462        let parent_session = this
1463            .sessions_with_children
1464            .keys()
1465            .find(|p| Some(p.read(cx).session_id(cx)) == session.read(cx).parent_id(cx))
1466            .cloned();
1467        this.retain_sessions(|session| {
1468            !session
1469                .read(cx)
1470                .running_state()
1471                .read(cx)
1472                .session()
1473                .read(cx)
1474                .is_terminated()
1475        });
1476
1477        let debug_session = DebugSession::running(
1478            this.project.clone(),
1479            this.workspace.clone(),
1480            parent_session
1481                .as_ref()
1482                .map(|p| p.read(cx).running_state().read(cx).debug_terminal.clone()),
1483            session,
1484            serialized_layout,
1485            this.position(window, cx).axis(),
1486            window,
1487            cx,
1488        );
1489
1490        // We might want to make this an event subscription and only notify when a new thread is selected
1491        // This is used to filter the command menu correctly
1492        cx.observe(
1493            &debug_session.read(cx).running_state().clone(),
1494            |_, _, cx| cx.notify(),
1495        )
1496        .detach();
1497        let insert_position = this
1498            .sessions_with_children
1499            .keys()
1500            .position(|session| Some(session) == parent_session.as_ref())
1501            .map(|position| position + 1)
1502            .unwrap_or(this.sessions_with_children.len());
1503        // Maintain topological sort order of sessions
1504        let (_, old) = this.sessions_with_children.insert_before(
1505            insert_position,
1506            debug_session.clone(),
1507            Default::default(),
1508        );
1509        debug_assert!(old.is_none());
1510        if let Some(parent_session) = parent_session {
1511            this.sessions_with_children
1512                .entry(parent_session)
1513                .and_modify(|children| children.push(debug_session.downgrade()));
1514        }
1515
1516        debug_session
1517    })?;
1518    Ok(debug_session)
1519}
1520
1521impl EventEmitter<PanelEvent> for DebugPanel {}
1522
1523impl Focusable for DebugPanel {
1524    fn focus_handle(&self, _: &App) -> FocusHandle {
1525        self.focus_handle.clone()
1526    }
1527}
1528
1529impl Panel for DebugPanel {
1530    fn persistent_name() -> &'static str {
1531        "DebugPanel"
1532    }
1533
1534    fn panel_key() -> &'static str {
1535        DEBUG_PANEL_KEY
1536    }
1537
1538    fn position(&self, _window: &Window, cx: &App) -> DockPosition {
1539        DebuggerSettings::get_global(cx).dock.into()
1540    }
1541
1542    fn position_is_valid(&self, _: DockPosition) -> bool {
1543        true
1544    }
1545
1546    fn set_position(
1547        &mut self,
1548        position: DockPosition,
1549        window: &mut Window,
1550        cx: &mut Context<Self>,
1551    ) {
1552        if position.axis() != self.position(window, cx).axis() {
1553            self.sessions_with_children.keys().for_each(|session_item| {
1554                session_item.update(cx, |item, cx| {
1555                    item.running_state()
1556                        .update(cx, |state, cx| state.invert_axies(cx))
1557                })
1558            });
1559        }
1560
1561        settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
1562            settings.debugger.get_or_insert_default().dock = Some(position.into());
1563        });
1564    }
1565
1566    fn size(&self, _window: &Window, _: &App) -> Pixels {
1567        self.size
1568    }
1569
1570    fn set_size(&mut self, size: Option<Pixels>, _window: &mut Window, _cx: &mut Context<Self>) {
1571        self.size = size.unwrap_or(px(300.));
1572    }
1573
1574    fn remote_id() -> Option<proto::PanelId> {
1575        Some(proto::PanelId::DebugPanel)
1576    }
1577
1578    fn icon(&self, _window: &Window, cx: &App) -> Option<IconName> {
1579        DebuggerSettings::get_global(cx)
1580            .button
1581            .then_some(IconName::Debug)
1582    }
1583
1584    fn icon_tooltip(&self, _window: &Window, cx: &App) -> Option<&'static str> {
1585        if DebuggerSettings::get_global(cx).button {
1586            Some("Debug Panel")
1587        } else {
1588            None
1589        }
1590    }
1591
1592    fn toggle_action(&self) -> Box<dyn Action> {
1593        Box::new(ToggleFocus)
1594    }
1595
1596    fn pane(&self) -> Option<Entity<Pane>> {
1597        None
1598    }
1599
1600    fn activation_priority(&self) -> u32 {
1601        9
1602    }
1603
1604    fn set_active(&mut self, _: bool, _: &mut Window, _: &mut Context<Self>) {}
1605
1606    fn is_zoomed(&self, _window: &Window, _cx: &App) -> bool {
1607        self.is_zoomed
1608    }
1609
1610    fn set_zoomed(&mut self, zoomed: bool, _window: &mut Window, cx: &mut Context<Self>) {
1611        self.is_zoomed = zoomed;
1612        cx.notify();
1613    }
1614}
1615
1616impl Render for DebugPanel {
1617    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1618        let this = cx.weak_entity();
1619
1620        if self
1621            .active_session
1622            .as_ref()
1623            .map(|session| session.read(cx).running_state())
1624            .map(|state| state.read(cx).has_open_context_menu(cx))
1625            .unwrap_or(false)
1626        {
1627            self.context_menu.take();
1628        }
1629
1630        v_flex()
1631            .when(!self.is_zoomed, |this| {
1632                this.when_else(
1633                    self.position(window, cx) == DockPosition::Bottom,
1634                    |this| this.max_h(self.size),
1635                    |this| this.max_w(self.size),
1636                )
1637            })
1638            .size_full()
1639            .key_context("DebugPanel")
1640            .child(h_flex().children(self.top_controls_strip(window, cx)))
1641            .track_focus(&self.focus_handle(cx))
1642            .on_action({
1643                let this = this.clone();
1644                move |_: &workspace::ActivatePaneLeft, window, cx| {
1645                    this.update(cx, |this, cx| {
1646                        this.activate_pane_in_direction(SplitDirection::Left, window, cx);
1647                    })
1648                    .ok();
1649                }
1650            })
1651            .on_action({
1652                let this = this.clone();
1653                move |_: &workspace::ActivatePaneRight, window, cx| {
1654                    this.update(cx, |this, cx| {
1655                        this.activate_pane_in_direction(SplitDirection::Right, window, cx);
1656                    })
1657                    .ok();
1658                }
1659            })
1660            .on_action({
1661                let this = this.clone();
1662                move |_: &workspace::ActivatePaneUp, window, cx| {
1663                    this.update(cx, |this, cx| {
1664                        this.activate_pane_in_direction(SplitDirection::Up, window, cx);
1665                    })
1666                    .ok();
1667                }
1668            })
1669            .on_action({
1670                let this = this.clone();
1671                move |_: &workspace::ActivatePaneDown, window, cx| {
1672                    this.update(cx, |this, cx| {
1673                        this.activate_pane_in_direction(SplitDirection::Down, window, cx);
1674                    })
1675                    .ok();
1676                }
1677            })
1678            .on_action({
1679                let this = this.clone();
1680                move |_: &FocusConsole, window, cx| {
1681                    this.update(cx, |this, cx| {
1682                        this.activate_item(DebuggerPaneItem::Console, window, cx);
1683                    })
1684                    .ok();
1685                }
1686            })
1687            .on_action({
1688                let this = this.clone();
1689                move |_: &FocusVariables, window, cx| {
1690                    this.update(cx, |this, cx| {
1691                        this.activate_item(DebuggerPaneItem::Variables, window, cx);
1692                    })
1693                    .ok();
1694                }
1695            })
1696            .on_action({
1697                let this = this.clone();
1698                move |_: &FocusBreakpointList, window, cx| {
1699                    this.update(cx, |this, cx| {
1700                        this.activate_item(DebuggerPaneItem::BreakpointList, window, cx);
1701                    })
1702                    .ok();
1703                }
1704            })
1705            .on_action({
1706                let this = this.clone();
1707                move |_: &FocusFrames, window, cx| {
1708                    this.update(cx, |this, cx| {
1709                        this.activate_item(DebuggerPaneItem::Frames, window, cx);
1710                    })
1711                    .ok();
1712                }
1713            })
1714            .on_action({
1715                let this = this.clone();
1716                move |_: &FocusModules, window, cx| {
1717                    this.update(cx, |this, cx| {
1718                        this.activate_item(DebuggerPaneItem::Modules, window, cx);
1719                    })
1720                    .ok();
1721                }
1722            })
1723            .on_action({
1724                let this = this.clone();
1725                move |_: &FocusLoadedSources, window, cx| {
1726                    this.update(cx, |this, cx| {
1727                        this.activate_item(DebuggerPaneItem::LoadedSources, window, cx);
1728                    })
1729                    .ok();
1730                }
1731            })
1732            .on_action({
1733                let this = this.clone();
1734                move |_: &FocusTerminal, window, cx| {
1735                    this.update(cx, |this, cx| {
1736                        this.activate_item(DebuggerPaneItem::Terminal, window, cx);
1737                    })
1738                    .ok();
1739                }
1740            })
1741            .on_action({
1742                let this = this.clone();
1743                move |_: &ToggleThreadPicker, window, cx| {
1744                    this.update(cx, |this, cx| {
1745                        this.toggle_thread_picker(window, cx);
1746                    })
1747                    .ok();
1748                }
1749            })
1750            .on_action({
1751                move |_: &ToggleSessionPicker, window, cx| {
1752                    this.update(cx, |this, cx| {
1753                        this.toggle_session_picker(window, cx);
1754                    })
1755                    .ok();
1756                }
1757            })
1758            .on_action(cx.listener(Self::toggle_zoom))
1759            .on_action(cx.listener(|panel, _: &ToggleExpandItem, _, cx| {
1760                let Some(session) = panel.active_session() else {
1761                    return;
1762                };
1763                let active_pane = session
1764                    .read(cx)
1765                    .running_state()
1766                    .read(cx)
1767                    .active_pane()
1768                    .clone();
1769                active_pane.update(cx, |pane, cx| {
1770                    let is_zoomed = pane.is_zoomed();
1771                    pane.set_zoomed(!is_zoomed, cx);
1772                });
1773                cx.notify();
1774            }))
1775            .on_action(cx.listener(Self::copy_debug_adapter_arguments))
1776            .when(self.active_session.is_some(), |this| {
1777                this.on_mouse_down(
1778                    MouseButton::Right,
1779                    cx.listener(|this, event: &MouseDownEvent, window, cx| {
1780                        if this
1781                            .active_session
1782                            .as_ref()
1783                            .map(|session| {
1784                                let state = session.read(cx).running_state();
1785                                state.read(cx).has_pane_at_position(event.position)
1786                            })
1787                            .unwrap_or(false)
1788                        {
1789                            this.deploy_context_menu(event.position, window, cx);
1790                        }
1791                    }),
1792                )
1793                .children(self.context_menu.as_ref().map(|(menu, position, _)| {
1794                    deferred(
1795                        anchored()
1796                            .position(*position)
1797                            .anchor(gpui::Corner::TopLeft)
1798                            .child(menu.clone()),
1799                    )
1800                    .with_priority(1)
1801                }))
1802            })
1803            .map(|this| {
1804                if let Some(active_session) = self.active_session.clone() {
1805                    this.child(active_session)
1806                } else {
1807                    let docked_to_bottom = self.position(window, cx) == DockPosition::Bottom;
1808
1809                    let welcome_experience = v_flex()
1810                        .when_else(
1811                            docked_to_bottom,
1812                            |this| this.w_2_3().h_full().pr_8(),
1813                            |this| this.w_full().h_1_3(),
1814                        )
1815                        .items_center()
1816                        .justify_center()
1817                        .gap_2()
1818                        .child(
1819                            Button::new("spawn-new-session-empty-state", "New Session")
1820                                .icon(IconName::Plus)
1821                                .icon_size(IconSize::Small)
1822                                .icon_color(Color::Muted)
1823                                .icon_position(IconPosition::Start)
1824                                .on_click(|_, window, cx| {
1825                                    window.dispatch_action(crate::Start.boxed_clone(), cx);
1826                                }),
1827                        )
1828                        .child(
1829                            Button::new("edit-debug-settings", "Edit debug.json")
1830                                .icon(IconName::Code)
1831                                .icon_size(IconSize::Small)
1832                                .icon_color(Color::Muted)
1833                                .icon_position(IconPosition::Start)
1834                                .on_click(|_, window, cx| {
1835                                    window.dispatch_action(
1836                                        zed_actions::OpenProjectDebugTasks.boxed_clone(),
1837                                        cx,
1838                                    );
1839                                }),
1840                        )
1841                        .child(
1842                            Button::new("open-debugger-docs", "Debugger Docs")
1843                                .icon(IconName::Book)
1844                                .icon_size(IconSize::Small)
1845                                .icon_color(Color::Muted)
1846                                .icon_position(IconPosition::Start)
1847                                .on_click(|_, _, cx| cx.open_url("https://zed.dev/docs/debugger")),
1848                        )
1849                        .child(
1850                            Button::new(
1851                                "spawn-new-session-install-extensions",
1852                                "Debugger Extensions",
1853                            )
1854                            .icon(IconName::Blocks)
1855                            .icon_size(IconSize::Small)
1856                            .icon_color(Color::Muted)
1857                            .icon_position(IconPosition::Start)
1858                            .on_click(|_, window, cx| {
1859                                window.dispatch_action(
1860                                    zed_actions::Extensions {
1861                                        category_filter: Some(
1862                                            zed_actions::ExtensionCategoryFilter::DebugAdapters,
1863                                        ),
1864                                        id: None,
1865                                    }
1866                                    .boxed_clone(),
1867                                    cx,
1868                                );
1869                            }),
1870                        );
1871
1872                    let has_breakpoints = self
1873                        .project
1874                        .read(cx)
1875                        .breakpoint_store()
1876                        .read(cx)
1877                        .all_source_breakpoints(cx)
1878                        .values()
1879                        .any(|breakpoints| !breakpoints.is_empty());
1880
1881                    let breakpoint_list = v_flex()
1882                        .group("base-breakpoint-list")
1883                        .when_else(
1884                            docked_to_bottom,
1885                            |this| this.min_w_1_3().h_full(),
1886                            |this| this.size_full().h_2_3(),
1887                        )
1888                        .child(
1889                            h_flex()
1890                                .track_focus(&self.breakpoint_list.focus_handle(cx))
1891                                .h(Tab::container_height(cx))
1892                                .p_1p5()
1893                                .w_full()
1894                                .justify_between()
1895                                .border_b_1()
1896                                .border_color(cx.theme().colors().border_variant)
1897                                .child(Label::new("Breakpoints").size(LabelSize::Small))
1898                                .child(
1899                                    h_flex().visible_on_hover("base-breakpoint-list").child(
1900                                        self.breakpoint_list.read(cx).render_control_strip(),
1901                                    ),
1902                                ),
1903                        )
1904                        .when(has_breakpoints, |this| {
1905                            this.child(self.breakpoint_list.clone())
1906                        })
1907                        .when(!has_breakpoints, |this| {
1908                            this.child(
1909                                v_flex().size_full().items_center().justify_center().child(
1910                                    Label::new("No Breakpoints Set")
1911                                        .size(LabelSize::Small)
1912                                        .color(Color::Muted),
1913                                ),
1914                            )
1915                        });
1916
1917                    this.child(
1918                        v_flex()
1919                            .size_full()
1920                            .overflow_hidden()
1921                            .gap_1()
1922                            .items_center()
1923                            .justify_center()
1924                            .map(|this| {
1925                                if docked_to_bottom {
1926                                    this.child(
1927                                        h_flex()
1928                                            .size_full()
1929                                            .child(breakpoint_list)
1930                                            .child(Divider::vertical())
1931                                            .child(welcome_experience)
1932                                            .child(Divider::vertical()),
1933                                    )
1934                                } else {
1935                                    this.child(
1936                                        v_flex()
1937                                            .size_full()
1938                                            .child(welcome_experience)
1939                                            .child(Divider::horizontal())
1940                                            .child(breakpoint_list),
1941                                    )
1942                                }
1943                            }),
1944                    )
1945                }
1946            })
1947            .into_any()
1948    }
1949}
1950
1951struct DebuggerProvider(Entity<DebugPanel>);
1952
1953impl workspace::DebuggerProvider for DebuggerProvider {
1954    fn start_session(
1955        &self,
1956        definition: DebugScenario,
1957        context: SharedTaskContext,
1958        buffer: Option<Entity<Buffer>>,
1959        worktree_id: Option<WorktreeId>,
1960        window: &mut Window,
1961        cx: &mut App,
1962    ) {
1963        self.0.update(cx, |_, cx| {
1964            cx.defer_in(window, move |this, window, cx| {
1965                this.start_session(definition, context, buffer, worktree_id, window, cx);
1966            })
1967        })
1968    }
1969
1970    fn spawn_task_or_modal(
1971        &self,
1972        workspace: &mut Workspace,
1973        action: &tasks_ui::Spawn,
1974        window: &mut Window,
1975        cx: &mut Context<Workspace>,
1976    ) {
1977        spawn_task_or_modal(workspace, action, window, cx);
1978    }
1979
1980    fn debug_scenario_scheduled(&self, cx: &mut App) {
1981        self.0.update(cx, |this, _| {
1982            this.debug_scenario_scheduled_last = true;
1983        });
1984    }
1985
1986    fn task_scheduled(&self, cx: &mut App) {
1987        self.0.update(cx, |this, _| {
1988            this.debug_scenario_scheduled_last = false;
1989        })
1990    }
1991
1992    fn debug_scenario_scheduled_last(&self, cx: &App) -> bool {
1993        self.0.read(cx).debug_scenario_scheduled_last
1994    }
1995
1996    fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus> {
1997        let session = self.0.read(cx).active_session()?;
1998        let thread = session.read(cx).running_state().read(cx).thread_id()?;
1999        session.read(cx).session(cx).read(cx).thread_state(thread)
2000    }
2001}