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::debug_panel::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<DebugSession>| {
 519                    entity_id != other.entity_id()
 520                });
 521                if let Some(active_session_id) = this
 522                    .active_session
 523                    .as_ref()
 524                    .map(|session| session.entity_id())
 525                    && active_session_id == entity_id
 526                {
 527                    this.active_session = this.sessions_with_children.keys().next().cloned();
 528                }
 529                cx.notify()
 530            })
 531            .ok();
 532        })
 533        .detach();
 534    }
 535
 536    pub(crate) fn deploy_context_menu(
 537        &mut self,
 538        position: Point<Pixels>,
 539        window: &mut Window,
 540        cx: &mut Context<Self>,
 541    ) {
 542        if let Some(running_state) = self
 543            .active_session
 544            .as_ref()
 545            .map(|session| session.read(cx).running_state().clone())
 546        {
 547            let pane_items_status = running_state.read(cx).pane_items_status(cx);
 548            let this = cx.weak_entity();
 549
 550            let context_menu = ContextMenu::build(window, cx, |mut menu, _window, _cx| {
 551                for (item_kind, is_visible) in pane_items_status.into_iter() {
 552                    menu = menu.toggleable_entry(item_kind, is_visible, IconPosition::End, None, {
 553                        let this = this.clone();
 554                        move |window, cx| {
 555                            this.update(cx, |this, cx| {
 556                                if let Some(running_state) = this
 557                                    .active_session
 558                                    .as_ref()
 559                                    .map(|session| session.read(cx).running_state().clone())
 560                                {
 561                                    running_state.update(cx, |state, cx| {
 562                                        if is_visible {
 563                                            state.remove_pane_item(item_kind, window, cx);
 564                                        } else {
 565                                            state.add_pane_item(item_kind, position, window, cx);
 566                                        }
 567                                    })
 568                                }
 569                            })
 570                            .ok();
 571                        }
 572                    });
 573                }
 574
 575                menu
 576            });
 577
 578            window.focus(&context_menu.focus_handle(cx), cx);
 579            let subscription = cx.subscribe(&context_menu, |this, _, _: &DismissEvent, cx| {
 580                this.context_menu.take();
 581                cx.notify();
 582            });
 583            self.context_menu = Some((context_menu, position, subscription));
 584        }
 585    }
 586
 587    fn copy_debug_adapter_arguments(
 588        &mut self,
 589        _: &CopyDebugAdapterArguments,
 590        _window: &mut Window,
 591        cx: &mut Context<Self>,
 592    ) {
 593        let content = maybe!({
 594            let mut session = self.active_session()?.read(cx).session(cx);
 595            while let Some(parent) = session.read(cx).parent_session().cloned() {
 596                session = parent;
 597            }
 598            let binary = session.read(cx).binary()?;
 599            let content = serde_json::to_string_pretty(&binary).ok()?;
 600            Some(content)
 601        });
 602        if let Some(content) = content {
 603            cx.write_to_clipboard(ClipboardItem::new_string(content));
 604        }
 605    }
 606
 607    pub(crate) fn top_controls_strip(
 608        &mut self,
 609        window: &mut Window,
 610        cx: &mut Context<Self>,
 611    ) -> Option<Div> {
 612        let active_session = self.active_session.clone();
 613        let focus_handle = self.focus_handle.clone();
 614        let is_side = self.position(window, cx).axis() == gpui::Axis::Horizontal;
 615        let div = if is_side { v_flex() } else { h_flex() };
 616
 617        let new_session_button = || {
 618            IconButton::new("debug-new-session", IconName::Plus)
 619                .icon_size(IconSize::Small)
 620                .on_click({
 621                    move |_, window, cx| window.dispatch_action(crate::Start.boxed_clone(), cx)
 622                })
 623                .tooltip({
 624                    let focus_handle = focus_handle.clone();
 625                    move |_window, cx| {
 626                        Tooltip::for_action_in(
 627                            "Start Debug Session",
 628                            &crate::Start,
 629                            &focus_handle,
 630                            cx,
 631                        )
 632                    }
 633                })
 634        };
 635
 636        let edit_debug_json_button = || {
 637            IconButton::new("debug-edit-debug-json", IconName::Code)
 638                .icon_size(IconSize::Small)
 639                .on_click(|_, window, cx| {
 640                    window.dispatch_action(zed_actions::OpenProjectDebugTasks.boxed_clone(), cx);
 641                })
 642                .tooltip(Tooltip::text("Edit debug.json"))
 643        };
 644
 645        let documentation_button = || {
 646            IconButton::new("debug-open-documentation", IconName::CircleHelp)
 647                .icon_size(IconSize::Small)
 648                .on_click(move |_, _, cx| cx.open_url("https://zed.dev/docs/debugger"))
 649                .tooltip(Tooltip::text("Open Documentation"))
 650        };
 651
 652        let logs_button = || {
 653            IconButton::new("debug-open-logs", IconName::Notepad)
 654                .icon_size(IconSize::Small)
 655                .on_click(move |_, window, cx| {
 656                    window.dispatch_action(debugger_tools::OpenDebugAdapterLogs.boxed_clone(), cx)
 657                })
 658                .tooltip(Tooltip::text("Open Debug Adapter Logs"))
 659        };
 660
 661        let close_bottom_panel_button = {
 662            h_flex().pl_0p5().gap_1().child(Divider::vertical()).child(
 663                IconButton::new("debug-close-panel", IconName::Close)
 664                    .icon_size(IconSize::Small)
 665                    .on_click(move |_, window, cx| {
 666                        window.dispatch_action(workspace::ToggleBottomDock.boxed_clone(), cx)
 667                    })
 668                    .tooltip(Tooltip::text("Close Panel")),
 669            )
 670        };
 671
 672        let thread_status = active_session
 673            .as_ref()
 674            .map(|session| session.read(cx).running_state())
 675            .and_then(|state| state.read(cx).thread_status(cx))
 676            .unwrap_or(project::debugger::session::ThreadStatus::Exited);
 677
 678        Some(
 679            div.w_full()
 680                .py_1()
 681                .px_1p5()
 682                .justify_between()
 683                .border_b_1()
 684                .border_color(cx.theme().colors().border)
 685                .when(is_side, |this| this.gap_1().h(Tab::container_height(cx)))
 686                .child(
 687                    h_flex()
 688                        .justify_between()
 689                        .child(
 690                            h_flex().gap_1().w_full().when_some(
 691                                active_session
 692                                    .as_ref()
 693                                    .map(|session| session.read(cx).running_state()),
 694                                |this, running_state| {
 695                                    let capabilities = running_state.read(cx).capabilities(cx);
 696                                    let supports_detach =
 697                                        running_state.read(cx).session().read(cx).is_attached();
 698
 699                                    this.map(|this| {
 700                                        if thread_status == ThreadStatus::Running {
 701                                            this.child(
 702                                                IconButton::new(
 703                                                    "debug-pause",
 704                                                    IconName::DebugPause,
 705                                                )
 706                                                .icon_size(IconSize::Small)
 707                                                .on_click(window.listener_for(
 708                                                    running_state,
 709                                                    |this, _, _window, cx| {
 710                                                        this.pause_thread(cx);
 711                                                    },
 712                                                ))
 713                                                .tooltip({
 714                                                    let focus_handle = focus_handle.clone();
 715                                                    move |_window, cx| {
 716                                                        Tooltip::for_action_in(
 717                                                            "Pause Program",
 718                                                            &Pause,
 719                                                            &focus_handle,
 720                                                            cx,
 721                                                        )
 722                                                    }
 723                                                }),
 724                                            )
 725                                        } else {
 726                                            this.child(
 727                                                IconButton::new(
 728                                                    "debug-continue",
 729                                                    IconName::DebugContinue,
 730                                                )
 731                                                .icon_size(IconSize::Small)
 732                                                .on_click(window.listener_for(
 733                                                    running_state,
 734                                                    |this, _, _window, cx| this.continue_thread(cx),
 735                                                ))
 736                                                .disabled(thread_status != ThreadStatus::Stopped)
 737                                                .tooltip({
 738                                                    let focus_handle = focus_handle.clone();
 739                                                    move |_window, cx| {
 740                                                        Tooltip::for_action_in(
 741                                                            "Continue Program",
 742                                                            &Continue,
 743                                                            &focus_handle,
 744                                                            cx,
 745                                                        )
 746                                                    }
 747                                                }),
 748                                            )
 749                                        }
 750                                    })
 751                                    .child(
 752                                        IconButton::new("step-over", IconName::DebugStepOver)
 753                                            .icon_size(IconSize::Small)
 754                                            .on_click(window.listener_for(
 755                                                running_state,
 756                                                |this, _, _window, cx| {
 757                                                    this.step_over(cx);
 758                                                },
 759                                            ))
 760                                            .disabled(thread_status != ThreadStatus::Stopped)
 761                                            .tooltip({
 762                                                let focus_handle = focus_handle.clone();
 763                                                move |_window, cx| {
 764                                                    Tooltip::for_action_in(
 765                                                        "Step Over",
 766                                                        &StepOver,
 767                                                        &focus_handle,
 768                                                        cx,
 769                                                    )
 770                                                }
 771                                            }),
 772                                    )
 773                                    .child(
 774                                        IconButton::new("step-into", IconName::DebugStepInto)
 775                                            .icon_size(IconSize::Small)
 776                                            .on_click(window.listener_for(
 777                                                running_state,
 778                                                |this, _, _window, cx| {
 779                                                    this.step_in(cx);
 780                                                },
 781                                            ))
 782                                            .disabled(thread_status != ThreadStatus::Stopped)
 783                                            .tooltip({
 784                                                let focus_handle = focus_handle.clone();
 785                                                move |_window, cx| {
 786                                                    Tooltip::for_action_in(
 787                                                        "Step In",
 788                                                        &StepInto,
 789                                                        &focus_handle,
 790                                                        cx,
 791                                                    )
 792                                                }
 793                                            }),
 794                                    )
 795                                    .child(
 796                                        IconButton::new("step-out", IconName::DebugStepOut)
 797                                            .icon_size(IconSize::Small)
 798                                            .on_click(window.listener_for(
 799                                                running_state,
 800                                                |this, _, _window, cx| {
 801                                                    this.step_out(cx);
 802                                                },
 803                                            ))
 804                                            .disabled(thread_status != ThreadStatus::Stopped)
 805                                            .tooltip({
 806                                                let focus_handle = focus_handle.clone();
 807                                                move |_window, cx| {
 808                                                    Tooltip::for_action_in(
 809                                                        "Step Out",
 810                                                        &StepOut,
 811                                                        &focus_handle,
 812                                                        cx,
 813                                                    )
 814                                                }
 815                                            }),
 816                                    )
 817                                    .child(Divider::vertical())
 818                                    .child(
 819                                        IconButton::new("debug-restart", IconName::RotateCcw)
 820                                            .icon_size(IconSize::Small)
 821                                            .on_click(window.listener_for(
 822                                                running_state,
 823                                                |this, _, window, cx| {
 824                                                    this.rerun_session(window, cx);
 825                                                },
 826                                            ))
 827                                            .tooltip({
 828                                                let focus_handle = focus_handle.clone();
 829                                                move |_window, cx| {
 830                                                    Tooltip::for_action_in(
 831                                                        "Rerun Session",
 832                                                        &RerunSession,
 833                                                        &focus_handle,
 834                                                        cx,
 835                                                    )
 836                                                }
 837                                            }),
 838                                    )
 839                                    .child(
 840                                        IconButton::new("debug-stop", IconName::Power)
 841                                            .icon_size(IconSize::Small)
 842                                            .on_click(window.listener_for(
 843                                                running_state,
 844                                                |this, _, _window, cx| {
 845                                                    if this.session().read(cx).is_building() {
 846                                                        this.session().update(cx, |session, cx| {
 847                                                            session.shutdown(cx).detach()
 848                                                        });
 849                                                    } else {
 850                                                        this.stop_thread(cx);
 851                                                    }
 852                                                },
 853                                            ))
 854                                            .disabled(active_session.as_ref().is_none_or(
 855                                                |session| {
 856                                                    session
 857                                                        .read(cx)
 858                                                        .session(cx)
 859                                                        .read(cx)
 860                                                        .is_terminated()
 861                                                },
 862                                            ))
 863                                            .tooltip({
 864                                                let focus_handle = focus_handle.clone();
 865                                                let label = if capabilities
 866                                                    .supports_terminate_threads_request
 867                                                    .unwrap_or_default()
 868                                                {
 869                                                    "Terminate Thread"
 870                                                } else {
 871                                                    "Terminate All Threads"
 872                                                };
 873                                                move |_window, cx| {
 874                                                    Tooltip::for_action_in(
 875                                                        label,
 876                                                        &Stop,
 877                                                        &focus_handle,
 878                                                        cx,
 879                                                    )
 880                                                }
 881                                            }),
 882                                    )
 883                                    .when(supports_detach, |div| {
 884                                        div.child(
 885                                            IconButton::new(
 886                                                "debug-disconnect",
 887                                                IconName::DebugDetach,
 888                                            )
 889                                            .disabled(
 890                                                thread_status != ThreadStatus::Stopped
 891                                                    && thread_status != ThreadStatus::Running,
 892                                            )
 893                                            .icon_size(IconSize::Small)
 894                                            .on_click(window.listener_for(
 895                                                running_state,
 896                                                |this, _, _, cx| {
 897                                                    this.detach_client(cx);
 898                                                },
 899                                            ))
 900                                            .tooltip({
 901                                                let focus_handle = focus_handle.clone();
 902                                                move |_window, cx| {
 903                                                    Tooltip::for_action_in(
 904                                                        "Detach",
 905                                                        &Detach,
 906                                                        &focus_handle,
 907                                                        cx,
 908                                                    )
 909                                                }
 910                                            }),
 911                                        )
 912                                    })
 913                                    .when(
 914                                        cx.has_flag::<DebuggerHistoryFeatureFlag>(),
 915                                        |this| {
 916                                            this.child(Divider::vertical()).child(
 917                                                SplitButton::new(
 918                                                    self.render_history_button(
 919                                                        &running_state,
 920                                                        thread_status,
 921                                                        window,
 922                                                    ),
 923                                                    self.render_history_toggle_button(
 924                                                        thread_status,
 925                                                        &running_state,
 926                                                    )
 927                                                    .into_any_element(),
 928                                                )
 929                                                .style(ui::SplitButtonStyle::Outlined),
 930                                            )
 931                                        },
 932                                    )
 933                                },
 934                            ),
 935                        )
 936                        .when(is_side, |this| {
 937                            this.child(new_session_button())
 938                                .child(edit_debug_json_button())
 939                                .child(documentation_button())
 940                                .child(logs_button())
 941                        }),
 942                )
 943                .child(
 944                    h_flex()
 945                        .gap_0p5()
 946                        .when(is_side, |this| this.justify_between())
 947                        .child(
 948                            h_flex().when_some(
 949                                active_session
 950                                    .as_ref()
 951                                    .map(|session| session.read(cx).running_state())
 952                                    .cloned(),
 953                                |this, running_state| {
 954                                    this.children({
 955                                        let threads =
 956                                            running_state.update(cx, |running_state, cx| {
 957                                                let session = running_state.session();
 958                                                session.read(cx).is_started().then(|| {
 959                                                    session.update(cx, |session, cx| {
 960                                                        session.threads(cx)
 961                                                    })
 962                                                })
 963                                            });
 964
 965                                        threads.and_then(|threads| {
 966                                            self.render_thread_dropdown(
 967                                                &running_state,
 968                                                threads,
 969                                                window,
 970                                                cx,
 971                                            )
 972                                        })
 973                                    })
 974                                    .when(!is_side, |this| {
 975                                        this.gap_0p5().child(Divider::vertical())
 976                                    })
 977                                },
 978                            ),
 979                        )
 980                        .child(
 981                            h_flex()
 982                                .gap_0p5()
 983                                .children(self.render_session_menu(
 984                                    self.active_session(),
 985                                    self.running_state(cx),
 986                                    window,
 987                                    cx,
 988                                ))
 989                                .when(!is_side, |this| {
 990                                    this.child(new_session_button())
 991                                        .child(edit_debug_json_button())
 992                                        .child(documentation_button())
 993                                        .child(logs_button())
 994                                        .child(close_bottom_panel_button)
 995                                }),
 996                        ),
 997                ),
 998        )
 999    }
1000
1001    pub(crate) fn activate_pane_in_direction(
1002        &mut self,
1003        direction: SplitDirection,
1004        window: &mut Window,
1005        cx: &mut Context<Self>,
1006    ) {
1007        if let Some(session) = self.active_session() {
1008            session.update(cx, |session, cx| {
1009                session.running_state().update(cx, |running, cx| {
1010                    running.activate_pane_in_direction(direction, window, cx);
1011                })
1012            });
1013        }
1014    }
1015
1016    pub(crate) fn activate_item(
1017        &mut self,
1018        item: DebuggerPaneItem,
1019        window: &mut Window,
1020        cx: &mut Context<Self>,
1021    ) {
1022        if let Some(session) = self.active_session() {
1023            session.update(cx, |session, cx| {
1024                session.running_state().update(cx, |running, cx| {
1025                    running.activate_item(item, window, cx);
1026                });
1027            });
1028        }
1029    }
1030
1031    pub(crate) fn activate_session_by_id(
1032        &mut self,
1033        session_id: SessionId,
1034        window: &mut Window,
1035        cx: &mut Context<Self>,
1036    ) {
1037        if let Some(session) = self
1038            .sessions_with_children
1039            .keys()
1040            .find(|session| session.read(cx).session_id(cx) == session_id)
1041        {
1042            self.activate_session(session.clone(), window, cx);
1043        }
1044    }
1045
1046    pub(crate) fn activate_session(
1047        &mut self,
1048        session_item: Entity<DebugSession>,
1049        window: &mut Window,
1050        cx: &mut Context<Self>,
1051    ) {
1052        debug_assert!(self.sessions_with_children.contains_key(&session_item));
1053        session_item.focus_handle(cx).focus(window, cx);
1054        session_item.update(cx, |this, cx| {
1055            this.running_state().update(cx, |this, cx| {
1056                this.go_to_selected_stack_frame(window, cx);
1057            });
1058        });
1059        self.active_session = Some(session_item);
1060        cx.notify();
1061    }
1062
1063    pub(crate) fn go_to_scenario_definition(
1064        &self,
1065        kind: TaskSourceKind,
1066        scenario: DebugScenario,
1067        worktree_id: WorktreeId,
1068        window: &mut Window,
1069        cx: &mut Context<Self>,
1070    ) -> Task<Result<()>> {
1071        let Some(workspace) = self.workspace.upgrade() else {
1072            return Task::ready(Ok(()));
1073        };
1074        let project_path = match kind {
1075            TaskSourceKind::AbsPath { abs_path, .. } => {
1076                let Some(project_path) = workspace
1077                    .read(cx)
1078                    .project()
1079                    .read(cx)
1080                    .project_path_for_absolute_path(&abs_path, cx)
1081                else {
1082                    return Task::ready(Err(anyhow!("no abs path")));
1083                };
1084
1085                project_path
1086            }
1087            TaskSourceKind::Worktree {
1088                id,
1089                directory_in_worktree: dir,
1090                ..
1091            } => {
1092                let relative_path = if dir.ends_with(RelPath::unix(".vscode").unwrap()) {
1093                    dir.join(RelPath::unix("launch.json").unwrap())
1094                } else {
1095                    dir.join(RelPath::unix("debug.json").unwrap())
1096                };
1097                ProjectPath {
1098                    worktree_id: id,
1099                    path: relative_path,
1100                }
1101            }
1102            _ => return self.save_scenario(scenario, worktree_id, window, cx),
1103        };
1104
1105        let editor = workspace.update(cx, |workspace, cx| {
1106            workspace.open_path(project_path, None, true, window, cx)
1107        });
1108        cx.spawn_in(window, async move |_, cx| {
1109            let editor = editor.await?;
1110            let editor = cx
1111                .update(|_, cx| editor.act_as::<Editor>(cx))?
1112                .context("expected editor")?;
1113
1114            // unfortunately debug tasks don't have an easy way to globally
1115            // identify them. to jump to the one that you just created or an
1116            // 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
1117            editor.update_in(cx, |editor, window, cx| {
1118                let row = editor.text(cx).lines().enumerate().find_map(|(row, text)| {
1119                    if text.contains(scenario.label.as_ref()) && text.contains("\"label\": ") {
1120                        Some(row)
1121                    } else {
1122                        None
1123                    }
1124                });
1125                if let Some(row) = row {
1126                    editor.go_to_singleton_buffer_point(
1127                        text::Point::new(row as u32, 4),
1128                        window,
1129                        cx,
1130                    );
1131                }
1132            })?;
1133
1134            Ok(())
1135        })
1136    }
1137
1138    pub(crate) fn save_scenario(
1139        &self,
1140        scenario: DebugScenario,
1141        worktree_id: WorktreeId,
1142        window: &mut Window,
1143        cx: &mut Context<Self>,
1144    ) -> Task<Result<()>> {
1145        let this = cx.weak_entity();
1146        let project = self.project.clone();
1147        self.workspace
1148            .update(cx, |workspace, cx| {
1149                let Some(mut path) = workspace.absolute_path_of_worktree(worktree_id, cx) else {
1150                    return Task::ready(Err(anyhow!("Couldn't get worktree path")));
1151                };
1152
1153                let serialized_scenario = serde_json::to_value(scenario);
1154
1155                cx.spawn_in(window, async move |workspace, cx| {
1156                    let serialized_scenario = serialized_scenario?;
1157                    let fs =
1158                        workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
1159
1160                    path.push(paths::local_settings_folder_name());
1161                    if !fs.is_dir(path.as_path()).await {
1162                        fs.create_dir(path.as_path()).await?;
1163                    }
1164                    path.pop();
1165
1166                    path.push(paths::local_debug_file_relative_path().as_std_path());
1167                    let path = path.as_path();
1168
1169                    if !fs.is_file(path).await {
1170                        fs.create_file(path, Default::default()).await?;
1171                        fs.write(
1172                            path,
1173                            settings::initial_local_debug_tasks_content()
1174                                .to_string()
1175                                .as_bytes(),
1176                        )
1177                        .await?;
1178                    }
1179                    let project_path = workspace.update(cx, |workspace, cx| {
1180                        workspace
1181                            .project()
1182                            .read(cx)
1183                            .project_path_for_absolute_path(path, cx)
1184                            .context(
1185                                "Couldn't get project path for .zed/debug.json in active worktree",
1186                            )
1187                    })??;
1188
1189                    let editor = this
1190                        .update_in(cx, |this, window, cx| {
1191                            this.workspace.update(cx, |workspace, cx| {
1192                                workspace.open_path(project_path, None, true, window, cx)
1193                            })
1194                        })??
1195                        .await?;
1196                    let editor = cx
1197                        .update(|_, cx| editor.act_as::<Editor>(cx))?
1198                        .context("expected editor")?;
1199
1200                    let new_scenario = serde_json_lenient::to_string_pretty(&serialized_scenario)?
1201                        .lines()
1202                        .map(|l| format!("  {l}"))
1203                        .join("\n");
1204
1205                    editor
1206                        .update_in(cx, |editor, window, cx| {
1207                            Self::insert_task_into_editor(editor, new_scenario, project, window, cx)
1208                        })??
1209                        .await
1210                })
1211            })
1212            .unwrap_or_else(|err| Task::ready(Err(err)))
1213    }
1214
1215    pub fn insert_task_into_editor(
1216        editor: &mut Editor,
1217        new_scenario: String,
1218        project: Entity<Project>,
1219        window: &mut Window,
1220        cx: &mut Context<Editor>,
1221    ) -> Result<Task<Result<()>>> {
1222        static LAST_ITEM_QUERY: LazyLock<Query> = LazyLock::new(|| {
1223            Query::new(
1224                &tree_sitter_json::LANGUAGE.into(),
1225                "(document (array (object) @object))", // TODO: use "." anchor to only match last object
1226            )
1227            .expect("Failed to create LAST_ITEM_QUERY")
1228        });
1229        static EMPTY_ARRAY_QUERY: LazyLock<Query> = LazyLock::new(|| {
1230            Query::new(
1231                &tree_sitter_json::LANGUAGE.into(),
1232                "(document (array) @array)",
1233            )
1234            .expect("Failed to create EMPTY_ARRAY_QUERY")
1235        });
1236
1237        let content = editor.text(cx);
1238        let mut parser = tree_sitter::Parser::new();
1239        parser.set_language(&tree_sitter_json::LANGUAGE.into())?;
1240        let mut cursor = tree_sitter::QueryCursor::new();
1241        let syntax_tree = parser
1242            .parse(&content, None)
1243            .context("could not parse debug.json")?;
1244        let mut matches = cursor.matches(
1245            &LAST_ITEM_QUERY,
1246            syntax_tree.root_node(),
1247            content.as_bytes(),
1248        );
1249
1250        let mut last_offset = None;
1251        while let Some(mat) = matches.next() {
1252            if let Some(pos) = mat.captures.first().map(|m| m.node.byte_range().end) {
1253                last_offset = Some(MultiBufferOffset(pos))
1254            }
1255        }
1256        let mut edits = Vec::new();
1257        let mut cursor_position = MultiBufferOffset(0);
1258
1259        if let Some(pos) = last_offset {
1260            edits.push((pos..pos, format!(",\n{new_scenario}")));
1261            cursor_position = pos + ",\n  ".len();
1262        } else {
1263            let mut matches = cursor.matches(
1264                &EMPTY_ARRAY_QUERY,
1265                syntax_tree.root_node(),
1266                content.as_bytes(),
1267            );
1268
1269            if let Some(mat) = matches.next() {
1270                if let Some(pos) = mat.captures.first().map(|m| m.node.byte_range().end - 1) {
1271                    edits.push((
1272                        MultiBufferOffset(pos)..MultiBufferOffset(pos),
1273                        format!("\n{new_scenario}\n"),
1274                    ));
1275                    cursor_position = MultiBufferOffset(pos) + "\n  ".len();
1276                }
1277            } else {
1278                edits.push((
1279                    MultiBufferOffset(0)..MultiBufferOffset(0),
1280                    format!("[\n{}\n]", new_scenario),
1281                ));
1282                cursor_position = MultiBufferOffset("[\n  ".len());
1283            }
1284        }
1285        editor.transact(window, cx, |editor, window, cx| {
1286            editor.edit(edits, cx);
1287            let snapshot = editor.buffer().read(cx).read(cx);
1288            let point = cursor_position.to_point(&snapshot);
1289            drop(snapshot);
1290            editor.go_to_singleton_buffer_point(point, window, cx);
1291        });
1292        Ok(editor.save(SaveOptions::default(), project, window, cx))
1293    }
1294
1295    pub(crate) fn toggle_thread_picker(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1296        self.thread_picker_menu_handle.toggle(window, cx);
1297    }
1298
1299    pub(crate) fn toggle_session_picker(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1300        self.session_picker_menu_handle.toggle(window, cx);
1301    }
1302
1303    fn toggle_zoom(
1304        &mut self,
1305        _: &workspace::ToggleZoom,
1306        window: &mut Window,
1307        cx: &mut Context<Self>,
1308    ) {
1309        if self.is_zoomed {
1310            cx.emit(PanelEvent::ZoomOut);
1311        } else {
1312            if !self.focus_handle(cx).contains_focused(window, cx) {
1313                cx.focus_self(window);
1314            }
1315            cx.emit(PanelEvent::ZoomIn);
1316        }
1317    }
1318
1319    fn label_for_child_session(
1320        &self,
1321        parent_session: &Entity<Session>,
1322        request: &StartDebuggingRequestArguments,
1323        cx: &mut Context<'_, Self>,
1324    ) -> Option<SharedString> {
1325        let adapter = parent_session.read(cx).adapter();
1326        if let Some(adapter) = DapRegistry::global(cx).adapter(&adapter)
1327            && let Some(label) = adapter.label_for_child_session(request)
1328        {
1329            return Some(label.into());
1330        }
1331        None
1332    }
1333
1334    fn retain_sessions(&mut self, keep: &dyn Fn(&Entity<DebugSession>) -> bool) {
1335        self.sessions_with_children
1336            .retain(|session, _| keep(session));
1337        for children in self.sessions_with_children.values_mut() {
1338            children.retain(|child| {
1339                let Some(child) = child.upgrade() else {
1340                    return false;
1341                };
1342                keep(&child)
1343            });
1344        }
1345    }
1346
1347    fn render_history_button(
1348        &self,
1349        running_state: &Entity<RunningState>,
1350        thread_status: ThreadStatus,
1351        window: &mut Window,
1352    ) -> IconButton {
1353        IconButton::new("debug-back-in-history", IconName::HistoryRerun)
1354            .icon_size(IconSize::Small)
1355            .on_click(window.listener_for(running_state, |this, _, _window, cx| {
1356                this.session().update(cx, |session, cx| {
1357                    let ix = session
1358                        .active_snapshot_index()
1359                        .unwrap_or_else(|| session.historic_snapshots().len());
1360
1361                    session.select_historic_snapshot(Some(ix.saturating_sub(1)), cx);
1362                })
1363            }))
1364            .disabled(
1365                thread_status == ThreadStatus::Running || thread_status == ThreadStatus::Stepping,
1366            )
1367    }
1368
1369    fn render_history_toggle_button(
1370        &self,
1371        thread_status: ThreadStatus,
1372        running_state: &Entity<RunningState>,
1373    ) -> impl IntoElement {
1374        PopoverMenu::new("debug-back-in-history-menu")
1375            .trigger(
1376                ui::ButtonLike::new_rounded_right("debug-back-in-history-menu-trigger")
1377                    .layer(ui::ElevationIndex::ModalSurface)
1378                    .size(ui::ButtonSize::None)
1379                    .child(
1380                        div()
1381                            .px_1()
1382                            .child(Icon::new(IconName::ChevronDown).size(IconSize::XSmall)),
1383                    )
1384                    .disabled(
1385                        thread_status == ThreadStatus::Running
1386                            || thread_status == ThreadStatus::Stepping,
1387                    ),
1388            )
1389            .menu({
1390                let running_state = running_state.clone();
1391                move |window, cx| {
1392                    let handler =
1393                        |ix: Option<usize>, running_state: Entity<RunningState>, cx: &mut App| {
1394                            running_state.update(cx, |state, cx| {
1395                                state.session().update(cx, |session, cx| {
1396                                    session.select_historic_snapshot(ix, cx);
1397                                })
1398                            })
1399                        };
1400
1401                    let running_state = running_state.clone();
1402                    Some(ContextMenu::build(
1403                        window,
1404                        cx,
1405                        move |mut context_menu, _window, cx| {
1406                            let history = running_state
1407                                .read(cx)
1408                                .session()
1409                                .read(cx)
1410                                .historic_snapshots();
1411
1412                            context_menu = context_menu.entry("Current State", None, {
1413                                let running_state = running_state.clone();
1414                                move |_window, cx| {
1415                                    handler(None, running_state.clone(), cx);
1416                                }
1417                            });
1418                            context_menu = context_menu.separator();
1419
1420                            for (ix, _) in history.iter().enumerate().rev() {
1421                                context_menu =
1422                                    context_menu.entry(format!("history-{}", ix + 1), None, {
1423                                        let running_state = running_state.clone();
1424                                        move |_window, cx| {
1425                                            handler(Some(ix), running_state.clone(), cx);
1426                                        }
1427                                    });
1428                            }
1429
1430                            context_menu
1431                        },
1432                    ))
1433                }
1434            })
1435            .anchor(Corner::TopRight)
1436    }
1437}
1438
1439async fn register_session_inner(
1440    this: &WeakEntity<DebugPanel>,
1441    session: Entity<Session>,
1442    cx: &mut AsyncWindowContext,
1443) -> Result<Entity<DebugSession>> {
1444    let adapter_name = session.read_with(cx, |session, _| session.adapter());
1445    this.update_in(cx, |_, window, cx| {
1446        cx.subscribe_in(
1447            &session,
1448            window,
1449            move |this, session, event: &SessionStateEvent, window, cx| match event {
1450                SessionStateEvent::Restart => {
1451                    this.handle_restart_request(session.clone(), window, cx);
1452                }
1453                SessionStateEvent::SpawnChildSession { request } => {
1454                    this.handle_start_debugging_request(request, session.clone(), window, cx);
1455                }
1456                _ => {}
1457            },
1458        )
1459        .detach();
1460    })
1461    .ok();
1462    let serialized_layout = persistence::get_serialized_layout(adapter_name).await;
1463    let debug_session = this.update_in(cx, |this, window, cx| {
1464        let parent_session = this
1465            .sessions_with_children
1466            .keys()
1467            .find(|p| Some(p.read(cx).session_id(cx)) == session.read(cx).parent_id(cx))
1468            .cloned();
1469        this.retain_sessions(&|session: &Entity<DebugSession>| {
1470            !session
1471                .read(cx)
1472                .running_state()
1473                .read(cx)
1474                .session()
1475                .read(cx)
1476                .is_terminated()
1477        });
1478
1479        let debug_session = DebugSession::running(
1480            this.project.clone(),
1481            this.workspace.clone(),
1482            parent_session
1483                .as_ref()
1484                .map(|p| p.read(cx).running_state().read(cx).debug_terminal.clone()),
1485            session,
1486            serialized_layout,
1487            this.position(window, cx).axis(),
1488            window,
1489            cx,
1490        );
1491
1492        // We might want to make this an event subscription and only notify when a new thread is selected
1493        // This is used to filter the command menu correctly
1494        cx.observe(
1495            &debug_session.read(cx).running_state().clone(),
1496            |_, _, cx| cx.notify(),
1497        )
1498        .detach();
1499        let insert_position = this
1500            .sessions_with_children
1501            .keys()
1502            .position(|session| Some(session) == parent_session.as_ref())
1503            .map(|position| position + 1)
1504            .unwrap_or(this.sessions_with_children.len());
1505        // Maintain topological sort order of sessions
1506        let (_, old) = this.sessions_with_children.insert_before(
1507            insert_position,
1508            debug_session.clone(),
1509            Default::default(),
1510        );
1511        debug_assert!(old.is_none());
1512        if let Some(parent_session) = parent_session {
1513            this.sessions_with_children
1514                .entry(parent_session)
1515                .and_modify(|children| children.push(debug_session.downgrade()));
1516        }
1517
1518        debug_session
1519    })?;
1520    Ok(debug_session)
1521}
1522
1523impl EventEmitter<PanelEvent> for DebugPanel {}
1524
1525impl Focusable for DebugPanel {
1526    fn focus_handle(&self, _: &App) -> FocusHandle {
1527        self.focus_handle.clone()
1528    }
1529}
1530
1531impl Panel for DebugPanel {
1532    fn persistent_name() -> &'static str {
1533        "DebugPanel"
1534    }
1535
1536    fn panel_key() -> &'static str {
1537        DEBUG_PANEL_KEY
1538    }
1539
1540    fn position(&self, _window: &Window, cx: &App) -> DockPosition {
1541        DebuggerSettings::get_global(cx).dock.into()
1542    }
1543
1544    fn position_is_valid(&self, _: DockPosition) -> bool {
1545        true
1546    }
1547
1548    fn set_position(
1549        &mut self,
1550        position: DockPosition,
1551        window: &mut Window,
1552        cx: &mut Context<Self>,
1553    ) {
1554        if position.axis() != self.position(window, cx).axis() {
1555            self.sessions_with_children.keys().for_each(|session_item| {
1556                session_item.update(cx, |item, cx| {
1557                    item.running_state()
1558                        .update(cx, |state, cx| state.invert_axies(cx))
1559                })
1560            });
1561        }
1562
1563        settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
1564            settings.debugger.get_or_insert_default().dock = Some(position.into());
1565        });
1566    }
1567
1568    fn size(&self, _window: &Window, _: &App) -> Pixels {
1569        self.size
1570    }
1571
1572    fn set_size(&mut self, size: Option<Pixels>, _window: &mut Window, _cx: &mut Context<Self>) {
1573        self.size = size.unwrap_or(px(300.));
1574    }
1575
1576    fn remote_id() -> Option<proto::PanelId> {
1577        Some(proto::PanelId::DebugPanel)
1578    }
1579
1580    fn icon(&self, _window: &Window, cx: &App) -> Option<IconName> {
1581        DebuggerSettings::get_global(cx)
1582            .button
1583            .then_some(IconName::Debug)
1584    }
1585
1586    fn icon_tooltip(&self, _window: &Window, cx: &App) -> Option<&'static str> {
1587        if DebuggerSettings::get_global(cx).button {
1588            Some("Debug Panel")
1589        } else {
1590            None
1591        }
1592    }
1593
1594    fn toggle_action(&self) -> Box<dyn Action> {
1595        Box::new(ToggleFocus)
1596    }
1597
1598    fn pane(&self) -> Option<Entity<Pane>> {
1599        None
1600    }
1601
1602    fn activation_priority(&self) -> u32 {
1603        9
1604    }
1605
1606    fn set_active(&mut self, _: bool, _: &mut Window, _: &mut Context<Self>) {}
1607
1608    fn is_zoomed(&self, _window: &Window, _cx: &App) -> bool {
1609        self.is_zoomed
1610    }
1611
1612    fn set_zoomed(&mut self, zoomed: bool, _window: &mut Window, cx: &mut Context<Self>) {
1613        self.is_zoomed = zoomed;
1614        cx.notify();
1615    }
1616}
1617
1618impl Render for DebugPanel {
1619    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1620        let this = cx.weak_entity();
1621
1622        if self
1623            .active_session
1624            .as_ref()
1625            .map(|session| session.read(cx).running_state())
1626            .map(|state| state.read(cx).has_open_context_menu(cx))
1627            .unwrap_or(false)
1628        {
1629            self.context_menu.take();
1630        }
1631
1632        v_flex()
1633            .when(!self.is_zoomed, |this| {
1634                this.when_else(
1635                    self.position(window, cx) == DockPosition::Bottom,
1636                    |this| this.max_h(self.size),
1637                    |this| this.max_w(self.size),
1638                )
1639            })
1640            .size_full()
1641            .key_context("DebugPanel")
1642            .child(h_flex().children(self.top_controls_strip(window, cx)))
1643            .track_focus(&self.focus_handle(cx))
1644            .on_action({
1645                let this = this.clone();
1646                move |_: &workspace::ActivatePaneLeft, window, cx| {
1647                    this.update(cx, |this, cx| {
1648                        this.activate_pane_in_direction(SplitDirection::Left, window, cx);
1649                    })
1650                    .ok();
1651                }
1652            })
1653            .on_action({
1654                let this = this.clone();
1655                move |_: &workspace::ActivatePaneRight, window, cx| {
1656                    this.update(cx, |this, cx| {
1657                        this.activate_pane_in_direction(SplitDirection::Right, window, cx);
1658                    })
1659                    .ok();
1660                }
1661            })
1662            .on_action({
1663                let this = this.clone();
1664                move |_: &workspace::ActivatePaneUp, window, cx| {
1665                    this.update(cx, |this, cx| {
1666                        this.activate_pane_in_direction(SplitDirection::Up, window, cx);
1667                    })
1668                    .ok();
1669                }
1670            })
1671            .on_action({
1672                let this = this.clone();
1673                move |_: &workspace::ActivatePaneDown, window, cx| {
1674                    this.update(cx, |this, cx| {
1675                        this.activate_pane_in_direction(SplitDirection::Down, window, cx);
1676                    })
1677                    .ok();
1678                }
1679            })
1680            .on_action({
1681                let this = this.clone();
1682                move |_: &FocusConsole, window, cx| {
1683                    this.update(cx, |this, cx| {
1684                        this.activate_item(DebuggerPaneItem::Console, window, cx);
1685                    })
1686                    .ok();
1687                }
1688            })
1689            .on_action({
1690                let this = this.clone();
1691                move |_: &FocusVariables, window, cx| {
1692                    this.update(cx, |this, cx| {
1693                        this.activate_item(DebuggerPaneItem::Variables, window, cx);
1694                    })
1695                    .ok();
1696                }
1697            })
1698            .on_action({
1699                let this = this.clone();
1700                move |_: &FocusBreakpointList, window, cx| {
1701                    this.update(cx, |this, cx| {
1702                        this.activate_item(DebuggerPaneItem::BreakpointList, window, cx);
1703                    })
1704                    .ok();
1705                }
1706            })
1707            .on_action({
1708                let this = this.clone();
1709                move |_: &FocusFrames, window, cx| {
1710                    this.update(cx, |this, cx| {
1711                        this.activate_item(DebuggerPaneItem::Frames, window, cx);
1712                    })
1713                    .ok();
1714                }
1715            })
1716            .on_action({
1717                let this = this.clone();
1718                move |_: &FocusModules, window, cx| {
1719                    this.update(cx, |this, cx| {
1720                        this.activate_item(DebuggerPaneItem::Modules, window, cx);
1721                    })
1722                    .ok();
1723                }
1724            })
1725            .on_action({
1726                let this = this.clone();
1727                move |_: &FocusLoadedSources, window, cx| {
1728                    this.update(cx, |this, cx| {
1729                        this.activate_item(DebuggerPaneItem::LoadedSources, window, cx);
1730                    })
1731                    .ok();
1732                }
1733            })
1734            .on_action({
1735                let this = this.clone();
1736                move |_: &FocusTerminal, window, cx| {
1737                    this.update(cx, |this, cx| {
1738                        this.activate_item(DebuggerPaneItem::Terminal, window, cx);
1739                    })
1740                    .ok();
1741                }
1742            })
1743            .on_action({
1744                let this = this.clone();
1745                move |_: &ToggleThreadPicker, window, cx| {
1746                    this.update(cx, |this, cx| {
1747                        this.toggle_thread_picker(window, cx);
1748                    })
1749                    .ok();
1750                }
1751            })
1752            .on_action({
1753                move |_: &ToggleSessionPicker, window, cx| {
1754                    this.update(cx, |this, cx| {
1755                        this.toggle_session_picker(window, cx);
1756                    })
1757                    .ok();
1758                }
1759            })
1760            .on_action(cx.listener(Self::toggle_zoom))
1761            .on_action(cx.listener(|panel, _: &ToggleExpandItem, _, cx| {
1762                let Some(session) = panel.active_session() else {
1763                    return;
1764                };
1765                let active_pane = session
1766                    .read(cx)
1767                    .running_state()
1768                    .read(cx)
1769                    .active_pane()
1770                    .clone();
1771                active_pane.update(cx, |pane, cx| {
1772                    let is_zoomed = pane.is_zoomed();
1773                    pane.set_zoomed(!is_zoomed, cx);
1774                });
1775                cx.notify();
1776            }))
1777            .on_action(cx.listener(Self::copy_debug_adapter_arguments))
1778            .when(self.active_session.is_some(), |this| {
1779                this.on_mouse_down(
1780                    MouseButton::Right,
1781                    cx.listener(|this, event: &MouseDownEvent, window, cx| {
1782                        if this
1783                            .active_session
1784                            .as_ref()
1785                            .map(|session| {
1786                                let state = session.read(cx).running_state();
1787                                state.read(cx).has_pane_at_position(event.position)
1788                            })
1789                            .unwrap_or(false)
1790                        {
1791                            this.deploy_context_menu(event.position, window, cx);
1792                        }
1793                    }),
1794                )
1795                .children(self.context_menu.as_ref().map(|(menu, position, _)| {
1796                    deferred(
1797                        anchored()
1798                            .position(*position)
1799                            .anchor(gpui::Corner::TopLeft)
1800                            .child(menu.clone()),
1801                    )
1802                    .with_priority(1)
1803                }))
1804            })
1805            .map(|this| {
1806                if let Some(active_session) = self.active_session.clone() {
1807                    this.child(active_session)
1808                } else {
1809                    let docked_to_bottom = self.position(window, cx) == DockPosition::Bottom;
1810
1811                    let welcome_experience = v_flex()
1812                        .when_else(
1813                            docked_to_bottom,
1814                            |this| this.w_2_3().h_full().pr_8(),
1815                            |this| this.w_full().h_1_3(),
1816                        )
1817                        .items_center()
1818                        .justify_center()
1819                        .gap_2()
1820                        .child(
1821                            Button::new("spawn-new-session-empty-state", "New Session")
1822                                .icon(IconName::Plus)
1823                                .icon_size(IconSize::Small)
1824                                .icon_color(Color::Muted)
1825                                .icon_position(IconPosition::Start)
1826                                .on_click(|_, window, cx| {
1827                                    window.dispatch_action(crate::Start.boxed_clone(), cx);
1828                                }),
1829                        )
1830                        .child(
1831                            Button::new("edit-debug-settings", "Edit debug.json")
1832                                .icon(IconName::Code)
1833                                .icon_size(IconSize::Small)
1834                                .icon_color(Color::Muted)
1835                                .icon_position(IconPosition::Start)
1836                                .on_click(|_, window, cx| {
1837                                    window.dispatch_action(
1838                                        zed_actions::OpenProjectDebugTasks.boxed_clone(),
1839                                        cx,
1840                                    );
1841                                }),
1842                        )
1843                        .child(
1844                            Button::new("open-debugger-docs", "Debugger Docs")
1845                                .icon(IconName::Book)
1846                                .icon_size(IconSize::Small)
1847                                .icon_color(Color::Muted)
1848                                .icon_position(IconPosition::Start)
1849                                .on_click(|_, _, cx| cx.open_url("https://zed.dev/docs/debugger")),
1850                        )
1851                        .child(
1852                            Button::new(
1853                                "spawn-new-session-install-extensions",
1854                                "Debugger Extensions",
1855                            )
1856                            .icon(IconName::Blocks)
1857                            .icon_size(IconSize::Small)
1858                            .icon_color(Color::Muted)
1859                            .icon_position(IconPosition::Start)
1860                            .on_click(|_, window, cx| {
1861                                window.dispatch_action(
1862                                    zed_actions::Extensions {
1863                                        category_filter: Some(
1864                                            zed_actions::ExtensionCategoryFilter::DebugAdapters,
1865                                        ),
1866                                        id: None,
1867                                    }
1868                                    .boxed_clone(),
1869                                    cx,
1870                                );
1871                            }),
1872                        );
1873
1874                    let has_breakpoints = self
1875                        .project
1876                        .read(cx)
1877                        .breakpoint_store()
1878                        .read(cx)
1879                        .all_source_breakpoints(cx)
1880                        .values()
1881                        .any(|breakpoints| !breakpoints.is_empty());
1882
1883                    let breakpoint_list = v_flex()
1884                        .group("base-breakpoint-list")
1885                        .when_else(
1886                            docked_to_bottom,
1887                            |this| this.min_w_1_3().h_full(),
1888                            |this| this.size_full().h_2_3(),
1889                        )
1890                        .child(
1891                            h_flex()
1892                                .track_focus(&self.breakpoint_list.focus_handle(cx))
1893                                .h(Tab::container_height(cx))
1894                                .p_1p5()
1895                                .w_full()
1896                                .justify_between()
1897                                .border_b_1()
1898                                .border_color(cx.theme().colors().border_variant)
1899                                .child(Label::new("Breakpoints").size(LabelSize::Small))
1900                                .child(
1901                                    h_flex().visible_on_hover("base-breakpoint-list").child(
1902                                        self.breakpoint_list.read(cx).render_control_strip(),
1903                                    ),
1904                                ),
1905                        )
1906                        .when(has_breakpoints, |this| {
1907                            this.child(self.breakpoint_list.clone())
1908                        })
1909                        .when(!has_breakpoints, |this| {
1910                            this.child(
1911                                v_flex().size_full().items_center().justify_center().child(
1912                                    Label::new("No Breakpoints Set")
1913                                        .size(LabelSize::Small)
1914                                        .color(Color::Muted),
1915                                ),
1916                            )
1917                        });
1918
1919                    this.child(
1920                        v_flex()
1921                            .size_full()
1922                            .overflow_hidden()
1923                            .gap_1()
1924                            .items_center()
1925                            .justify_center()
1926                            .map(|this| {
1927                                if docked_to_bottom {
1928                                    this.child(
1929                                        h_flex()
1930                                            .size_full()
1931                                            .child(breakpoint_list)
1932                                            .child(Divider::vertical())
1933                                            .child(welcome_experience)
1934                                            .child(Divider::vertical()),
1935                                    )
1936                                } else {
1937                                    this.child(
1938                                        v_flex()
1939                                            .size_full()
1940                                            .child(welcome_experience)
1941                                            .child(Divider::horizontal())
1942                                            .child(breakpoint_list),
1943                                    )
1944                                }
1945                            }),
1946                    )
1947                }
1948            })
1949            .into_any()
1950    }
1951}
1952
1953struct DebuggerProvider(Entity<DebugPanel>);
1954
1955impl workspace::DebuggerProvider for DebuggerProvider {
1956    fn start_session(
1957        &self,
1958        definition: DebugScenario,
1959        context: SharedTaskContext,
1960        buffer: Option<Entity<Buffer>>,
1961        worktree_id: Option<WorktreeId>,
1962        window: &mut Window,
1963        cx: &mut App,
1964    ) {
1965        self.0.update(cx, |_, cx| {
1966            cx.defer_in(window, move |this, window, cx| {
1967                this.start_session(definition, context, buffer, worktree_id, window, cx);
1968            })
1969        })
1970    }
1971
1972    fn spawn_task_or_modal(
1973        &self,
1974        workspace: &mut Workspace,
1975        action: &tasks_ui::Spawn,
1976        window: &mut Window,
1977        cx: &mut Context<Workspace>,
1978    ) {
1979        spawn_task_or_modal(workspace, action, window, cx);
1980    }
1981
1982    fn debug_scenario_scheduled(&self, cx: &mut App) {
1983        self.0.update(cx, |this, _| {
1984            this.debug_scenario_scheduled_last = true;
1985        });
1986    }
1987
1988    fn task_scheduled(&self, cx: &mut App) {
1989        self.0.update(cx, |this, _| {
1990            this.debug_scenario_scheduled_last = false;
1991        })
1992    }
1993
1994    fn debug_scenario_scheduled_last(&self, cx: &App) -> bool {
1995        self.0.read(cx).debug_scenario_scheduled_last
1996    }
1997
1998    fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus> {
1999        let session = self.0.read(cx).active_session()?;
2000        let thread = session.read(cx).running_state().read(cx).thread_id()?;
2001        session.read(cx).session(cx).read(cx).thread_state(thread)
2002    }
2003}