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