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 =
 473                parent_session.update(cx, |this, _| this.has_ever_stopped())?;
 474            Self::register_session(this, session, !parent_ever_stopped, cx).await?;
 475            task.await
 476        })
 477        .detach_and_log_err(cx);
 478    }
 479
 480    pub(crate) fn close_session(
 481        &mut self,
 482        entity_id: EntityId,
 483        window: &mut Window,
 484        cx: &mut Context<Self>,
 485    ) {
 486        let Some(session) = self
 487            .sessions_with_children
 488            .keys()
 489            .find(|other| entity_id == other.entity_id())
 490            .cloned()
 491        else {
 492            return;
 493        };
 494        session.update(cx, |this, cx| {
 495            this.running_state().update(cx, |this, cx| {
 496                this.serialize_layout(window, cx);
 497            });
 498        });
 499        let session_id = session.update(cx, |this, cx| this.session_id(cx));
 500        let should_prompt = self
 501            .project
 502            .update(cx, |this, cx| {
 503                let session = this.dap_store().read(cx).session_by_id(session_id);
 504                session.map(|session| !session.read(cx).is_terminated())
 505            })
 506            .unwrap_or_default();
 507
 508        cx.spawn_in(window, async move |this, cx| {
 509            if should_prompt {
 510                let response = cx.prompt(
 511                    gpui::PromptLevel::Warning,
 512                    "This Debug Session is still running. Are you sure you want to terminate it?",
 513                    None,
 514                    &["Yes", "No"],
 515                );
 516                if response.await == Ok(1) {
 517                    return;
 518                }
 519            }
 520            session.update(cx, |session, cx| session.shutdown(cx)).ok();
 521            this.update(cx, |this, cx| {
 522                this.retain_sessions(|other| entity_id != other.entity_id());
 523                if let Some(active_session_id) = this
 524                    .active_session
 525                    .as_ref()
 526                    .map(|session| session.entity_id())
 527                    && active_session_id == entity_id
 528                {
 529                    this.active_session = this.sessions_with_children.keys().next().cloned();
 530                }
 531                cx.notify()
 532            })
 533            .ok();
 534        })
 535        .detach();
 536    }
 537
 538    pub(crate) fn deploy_context_menu(
 539        &mut self,
 540        position: Point<Pixels>,
 541        window: &mut Window,
 542        cx: &mut Context<Self>,
 543    ) {
 544        if let Some(running_state) = self
 545            .active_session
 546            .as_ref()
 547            .map(|session| session.read(cx).running_state().clone())
 548        {
 549            let pane_items_status = running_state.read(cx).pane_items_status(cx);
 550            let this = cx.weak_entity();
 551
 552            let context_menu = ContextMenu::build(window, cx, |mut menu, _window, _cx| {
 553                for (item_kind, is_visible) in pane_items_status.into_iter() {
 554                    menu = menu.toggleable_entry(item_kind, is_visible, IconPosition::End, None, {
 555                        let this = this.clone();
 556                        move |window, cx| {
 557                            this.update(cx, |this, cx| {
 558                                if let Some(running_state) = this
 559                                    .active_session
 560                                    .as_ref()
 561                                    .map(|session| session.read(cx).running_state().clone())
 562                                {
 563                                    running_state.update(cx, |state, cx| {
 564                                        if is_visible {
 565                                            state.remove_pane_item(item_kind, window, cx);
 566                                        } else {
 567                                            state.add_pane_item(item_kind, position, window, cx);
 568                                        }
 569                                    })
 570                                }
 571                            })
 572                            .ok();
 573                        }
 574                    });
 575                }
 576
 577                menu
 578            });
 579
 580            window.focus(&context_menu.focus_handle(cx));
 581            let subscription = cx.subscribe(&context_menu, |this, _, _: &DismissEvent, cx| {
 582                this.context_menu.take();
 583                cx.notify();
 584            });
 585            self.context_menu = Some((context_menu, position, subscription));
 586        }
 587    }
 588
 589    fn copy_debug_adapter_arguments(
 590        &mut self,
 591        _: &CopyDebugAdapterArguments,
 592        _window: &mut Window,
 593        cx: &mut Context<Self>,
 594    ) {
 595        let content = maybe!({
 596            let mut session = self.active_session()?.read(cx).session(cx);
 597            while let Some(parent) = session.read(cx).parent_session().cloned() {
 598                session = parent;
 599            }
 600            let binary = session.read(cx).binary()?;
 601            let content = serde_json::to_string_pretty(&binary).ok()?;
 602            Some(content)
 603        });
 604        if let Some(content) = content {
 605            cx.write_to_clipboard(ClipboardItem::new_string(content));
 606        }
 607    }
 608
 609    pub(crate) fn top_controls_strip(
 610        &mut self,
 611        window: &mut Window,
 612        cx: &mut Context<Self>,
 613    ) -> Option<Div> {
 614        let active_session = self.active_session.clone();
 615        let focus_handle = self.focus_handle.clone();
 616        let is_side = self.position(window, cx).axis() == gpui::Axis::Horizontal;
 617        let div = if is_side { v_flex() } else { h_flex() };
 618
 619        let new_session_button = || {
 620            IconButton::new("debug-new-session", IconName::Plus)
 621                .icon_size(IconSize::Small)
 622                .on_click({
 623                    move |_, window, cx| window.dispatch_action(crate::Start.boxed_clone(), cx)
 624                })
 625                .tooltip({
 626                    let focus_handle = focus_handle.clone();
 627                    move |_window, cx| {
 628                        Tooltip::for_action_in(
 629                            "Start Debug Session",
 630                            &crate::Start,
 631                            &focus_handle,
 632                            cx,
 633                        )
 634                    }
 635                })
 636        };
 637
 638        let edit_debug_json_button = || {
 639            IconButton::new("debug-edit-debug-json", IconName::Code)
 640                .icon_size(IconSize::Small)
 641                .on_click(|_, window, cx| {
 642                    window.dispatch_action(zed_actions::OpenProjectDebugTasks.boxed_clone(), cx);
 643                })
 644                .tooltip(Tooltip::text("Edit debug.json"))
 645        };
 646
 647        let documentation_button = || {
 648            IconButton::new("debug-open-documentation", IconName::CircleHelp)
 649                .icon_size(IconSize::Small)
 650                .on_click(move |_, _, cx| cx.open_url("https://zed.dev/docs/debugger"))
 651                .tooltip(Tooltip::text("Open Documentation"))
 652        };
 653
 654        let logs_button = || {
 655            IconButton::new("debug-open-logs", IconName::Notepad)
 656                .icon_size(IconSize::Small)
 657                .on_click(move |_, window, cx| {
 658                    window.dispatch_action(debugger_tools::OpenDebugAdapterLogs.boxed_clone(), cx)
 659                })
 660                .tooltip(Tooltip::text("Open Debug Adapter Logs"))
 661        };
 662
 663        let close_bottom_panel_button = {
 664            h_flex().pl_0p5().gap_1().child(Divider::vertical()).child(
 665                IconButton::new("debug-close-panel", IconName::Close)
 666                    .icon_size(IconSize::Small)
 667                    .on_click(move |_, window, cx| {
 668                        window.dispatch_action(workspace::ToggleBottomDock.boxed_clone(), cx)
 669                    })
 670                    .tooltip(Tooltip::text("Close Panel")),
 671            )
 672        };
 673
 674        let thread_status = active_session
 675            .as_ref()
 676            .map(|session| session.read(cx).running_state())
 677            .and_then(|state| state.read(cx).thread_status(cx))
 678            .unwrap_or(project::debugger::session::ThreadStatus::Exited);
 679
 680        Some(
 681            div.w_full()
 682                .py_1()
 683                .px_1p5()
 684                .justify_between()
 685                .border_b_1()
 686                .border_color(cx.theme().colors().border)
 687                .when(is_side, |this| this.gap_1().h(Tab::container_height(cx)))
 688                .child(
 689                    h_flex()
 690                        .justify_between()
 691                        .child(
 692                            h_flex().gap_1().w_full().when_some(
 693                                active_session
 694                                    .as_ref()
 695                                    .map(|session| session.read(cx).running_state()),
 696                                |this, running_state| {
 697                                    let capabilities = running_state.read(cx).capabilities(cx);
 698                                    let supports_detach =
 699                                        running_state.read(cx).session().read(cx).is_attached();
 700
 701                                    this.map(|this| {
 702                                        if thread_status == ThreadStatus::Running {
 703                                            this.child(
 704                                                IconButton::new(
 705                                                    "debug-pause",
 706                                                    IconName::DebugPause,
 707                                                )
 708                                                .icon_size(IconSize::Small)
 709                                                .on_click(window.listener_for(
 710                                                    running_state,
 711                                                    |this, _, _window, cx| {
 712                                                        this.pause_thread(cx);
 713                                                    },
 714                                                ))
 715                                                .tooltip({
 716                                                    let focus_handle = focus_handle.clone();
 717                                                    move |_window, cx| {
 718                                                        Tooltip::for_action_in(
 719                                                            "Pause Program",
 720                                                            &Pause,
 721                                                            &focus_handle,
 722                                                            cx,
 723                                                        )
 724                                                    }
 725                                                }),
 726                                            )
 727                                        } else {
 728                                            this.child(
 729                                                IconButton::new(
 730                                                    "debug-continue",
 731                                                    IconName::DebugContinue,
 732                                                )
 733                                                .icon_size(IconSize::Small)
 734                                                .on_click(window.listener_for(
 735                                                    running_state,
 736                                                    |this, _, _window, cx| this.continue_thread(cx),
 737                                                ))
 738                                                .disabled(thread_status != ThreadStatus::Stopped)
 739                                                .tooltip({
 740                                                    let focus_handle = focus_handle.clone();
 741                                                    move |_window, cx| {
 742                                                        Tooltip::for_action_in(
 743                                                            "Continue Program",
 744                                                            &Continue,
 745                                                            &focus_handle,
 746                                                            cx,
 747                                                        )
 748                                                    }
 749                                                }),
 750                                            )
 751                                        }
 752                                    })
 753                                    .child(
 754                                        IconButton::new("step-over", IconName::DebugStepOver)
 755                                            .icon_size(IconSize::Small)
 756                                            .on_click(window.listener_for(
 757                                                running_state,
 758                                                |this, _, _window, cx| {
 759                                                    this.step_over(cx);
 760                                                },
 761                                            ))
 762                                            .disabled(thread_status != ThreadStatus::Stopped)
 763                                            .tooltip({
 764                                                let focus_handle = focus_handle.clone();
 765                                                move |_window, cx| {
 766                                                    Tooltip::for_action_in(
 767                                                        "Step Over",
 768                                                        &StepOver,
 769                                                        &focus_handle,
 770                                                        cx,
 771                                                    )
 772                                                }
 773                                            }),
 774                                    )
 775                                    .child(
 776                                        IconButton::new("step-into", IconName::DebugStepInto)
 777                                            .icon_size(IconSize::Small)
 778                                            .on_click(window.listener_for(
 779                                                running_state,
 780                                                |this, _, _window, cx| {
 781                                                    this.step_in(cx);
 782                                                },
 783                                            ))
 784                                            .disabled(thread_status != ThreadStatus::Stopped)
 785                                            .tooltip({
 786                                                let focus_handle = focus_handle.clone();
 787                                                move |_window, cx| {
 788                                                    Tooltip::for_action_in(
 789                                                        "Step In",
 790                                                        &StepInto,
 791                                                        &focus_handle,
 792                                                        cx,
 793                                                    )
 794                                                }
 795                                            }),
 796                                    )
 797                                    .child(
 798                                        IconButton::new("step-out", IconName::DebugStepOut)
 799                                            .icon_size(IconSize::Small)
 800                                            .on_click(window.listener_for(
 801                                                running_state,
 802                                                |this, _, _window, cx| {
 803                                                    this.step_out(cx);
 804                                                },
 805                                            ))
 806                                            .disabled(thread_status != ThreadStatus::Stopped)
 807                                            .tooltip({
 808                                                let focus_handle = focus_handle.clone();
 809                                                move |_window, cx| {
 810                                                    Tooltip::for_action_in(
 811                                                        "Step Out",
 812                                                        &StepOut,
 813                                                        &focus_handle,
 814                                                        cx,
 815                                                    )
 816                                                }
 817                                            }),
 818                                    )
 819                                    .child(Divider::vertical())
 820                                    .child(
 821                                        IconButton::new("debug-restart", IconName::RotateCcw)
 822                                            .icon_size(IconSize::Small)
 823                                            .on_click(window.listener_for(
 824                                                running_state,
 825                                                |this, _, window, cx| {
 826                                                    this.rerun_session(window, cx);
 827                                                },
 828                                            ))
 829                                            .tooltip({
 830                                                let focus_handle = focus_handle.clone();
 831                                                move |_window, cx| {
 832                                                    Tooltip::for_action_in(
 833                                                        "Rerun Session",
 834                                                        &RerunSession,
 835                                                        &focus_handle,
 836                                                        cx,
 837                                                    )
 838                                                }
 839                                            }),
 840                                    )
 841                                    .child(
 842                                        IconButton::new("debug-stop", IconName::Power)
 843                                            .icon_size(IconSize::Small)
 844                                            .on_click(window.listener_for(
 845                                                running_state,
 846                                                |this, _, _window, cx| {
 847                                                    if this.session().read(cx).is_building() {
 848                                                        this.session().update(cx, |session, cx| {
 849                                                            session.shutdown(cx).detach()
 850                                                        });
 851                                                    } else {
 852                                                        this.stop_thread(cx);
 853                                                    }
 854                                                },
 855                                            ))
 856                                            .disabled(active_session.as_ref().is_none_or(
 857                                                |session| {
 858                                                    session
 859                                                        .read(cx)
 860                                                        .session(cx)
 861                                                        .read(cx)
 862                                                        .is_terminated()
 863                                                },
 864                                            ))
 865                                            .tooltip({
 866                                                let focus_handle = focus_handle.clone();
 867                                                let label = if capabilities
 868                                                    .supports_terminate_threads_request
 869                                                    .unwrap_or_default()
 870                                                {
 871                                                    "Terminate Thread"
 872                                                } else {
 873                                                    "Terminate All Threads"
 874                                                };
 875                                                move |_window, cx| {
 876                                                    Tooltip::for_action_in(
 877                                                        label,
 878                                                        &Stop,
 879                                                        &focus_handle,
 880                                                        cx,
 881                                                    )
 882                                                }
 883                                            }),
 884                                    )
 885                                    .when(supports_detach, |div| {
 886                                        div.child(
 887                                            IconButton::new(
 888                                                "debug-disconnect",
 889                                                IconName::DebugDetach,
 890                                            )
 891                                            .disabled(
 892                                                thread_status != ThreadStatus::Stopped
 893                                                    && thread_status != ThreadStatus::Running,
 894                                            )
 895                                            .icon_size(IconSize::Small)
 896                                            .on_click(window.listener_for(
 897                                                running_state,
 898                                                |this, _, _, cx| {
 899                                                    this.detach_client(cx);
 900                                                },
 901                                            ))
 902                                            .tooltip({
 903                                                let focus_handle = focus_handle.clone();
 904                                                move |_window, cx| {
 905                                                    Tooltip::for_action_in(
 906                                                        "Detach",
 907                                                        &Detach,
 908                                                        &focus_handle,
 909                                                        cx,
 910                                                    )
 911                                                }
 912                                            }),
 913                                        )
 914                                    })
 915                                    .when(
 916                                        cx.has_flag::<DebuggerHistoryFeatureFlag>(),
 917                                        |this| {
 918                                            this.child(Divider::vertical()).child(
 919                                                SplitButton::new(
 920                                                    self.render_history_button(
 921                                                        &running_state,
 922                                                        thread_status,
 923                                                        window,
 924                                                    ),
 925                                                    self.render_history_toggle_button(
 926                                                        thread_status,
 927                                                        &running_state,
 928                                                    )
 929                                                    .into_any_element(),
 930                                                )
 931                                                .style(ui::SplitButtonStyle::Outlined),
 932                                            )
 933                                        },
 934                                    )
 935                                },
 936                            ),
 937                        )
 938                        .when(is_side, |this| {
 939                            this.child(new_session_button())
 940                                .child(edit_debug_json_button())
 941                                .child(documentation_button())
 942                                .child(logs_button())
 943                        }),
 944                )
 945                .child(
 946                    h_flex()
 947                        .gap_0p5()
 948                        .when(is_side, |this| this.justify_between())
 949                        .child(
 950                            h_flex().when_some(
 951                                active_session
 952                                    .as_ref()
 953                                    .map(|session| session.read(cx).running_state())
 954                                    .cloned(),
 955                                |this, running_state| {
 956                                    this.children({
 957                                        let threads =
 958                                            running_state.update(cx, |running_state, cx| {
 959                                                let session = running_state.session();
 960                                                session.read(cx).is_started().then(|| {
 961                                                    session.update(cx, |session, cx| {
 962                                                        session.threads(cx)
 963                                                    })
 964                                                })
 965                                            });
 966
 967                                        threads.and_then(|threads| {
 968                                            self.render_thread_dropdown(
 969                                                &running_state,
 970                                                threads,
 971                                                window,
 972                                                cx,
 973                                            )
 974                                        })
 975                                    })
 976                                    .when(!is_side, |this| {
 977                                        this.gap_0p5().child(Divider::vertical())
 978                                    })
 979                                },
 980                            ),
 981                        )
 982                        .child(
 983                            h_flex()
 984                                .gap_0p5()
 985                                .children(self.render_session_menu(
 986                                    self.active_session(),
 987                                    self.running_state(cx),
 988                                    window,
 989                                    cx,
 990                                ))
 991                                .when(!is_side, |this| {
 992                                    this.child(new_session_button())
 993                                        .child(edit_debug_json_button())
 994                                        .child(documentation_button())
 995                                        .child(logs_button())
 996                                        .child(close_bottom_panel_button)
 997                                }),
 998                        ),
 999                ),
1000        )
1001    }
1002
1003    pub(crate) fn activate_pane_in_direction(
1004        &mut self,
1005        direction: SplitDirection,
1006        window: &mut Window,
1007        cx: &mut Context<Self>,
1008    ) {
1009        if let Some(session) = self.active_session() {
1010            session.update(cx, |session, cx| {
1011                session.running_state().update(cx, |running, cx| {
1012                    running.activate_pane_in_direction(direction, window, cx);
1013                })
1014            });
1015        }
1016    }
1017
1018    pub(crate) fn activate_item(
1019        &mut self,
1020        item: DebuggerPaneItem,
1021        window: &mut Window,
1022        cx: &mut Context<Self>,
1023    ) {
1024        if let Some(session) = self.active_session() {
1025            session.update(cx, |session, cx| {
1026                session.running_state().update(cx, |running, cx| {
1027                    running.activate_item(item, window, cx);
1028                });
1029            });
1030        }
1031    }
1032
1033    pub(crate) fn activate_session_by_id(
1034        &mut self,
1035        session_id: SessionId,
1036        window: &mut Window,
1037        cx: &mut Context<Self>,
1038    ) {
1039        if let Some(session) = self
1040            .sessions_with_children
1041            .keys()
1042            .find(|session| session.read(cx).session_id(cx) == session_id)
1043        {
1044            self.activate_session(session.clone(), window, cx);
1045        }
1046    }
1047
1048    pub(crate) fn activate_session(
1049        &mut self,
1050        session_item: Entity<DebugSession>,
1051        window: &mut Window,
1052        cx: &mut Context<Self>,
1053    ) {
1054        debug_assert!(self.sessions_with_children.contains_key(&session_item));
1055        session_item.focus_handle(cx).focus(window);
1056        session_item.update(cx, |this, cx| {
1057            this.running_state().update(cx, |this, cx| {
1058                this.go_to_selected_stack_frame(window, cx);
1059            });
1060        });
1061        self.active_session = Some(session_item);
1062        cx.notify();
1063    }
1064
1065    pub(crate) fn go_to_scenario_definition(
1066        &self,
1067        kind: TaskSourceKind,
1068        scenario: DebugScenario,
1069        worktree_id: WorktreeId,
1070        window: &mut Window,
1071        cx: &mut Context<Self>,
1072    ) -> Task<Result<()>> {
1073        let Some(workspace) = self.workspace.upgrade() else {
1074            return Task::ready(Ok(()));
1075        };
1076        let project_path = match kind {
1077            TaskSourceKind::AbsPath { abs_path, .. } => {
1078                let Some(project_path) = workspace
1079                    .read(cx)
1080                    .project()
1081                    .read(cx)
1082                    .project_path_for_absolute_path(&abs_path, cx)
1083                else {
1084                    return Task::ready(Err(anyhow!("no abs path")));
1085                };
1086
1087                project_path
1088            }
1089            TaskSourceKind::Worktree {
1090                id,
1091                directory_in_worktree: dir,
1092                ..
1093            } => {
1094                let relative_path = if dir.ends_with(RelPath::unix(".vscode").unwrap()) {
1095                    dir.join(RelPath::unix("launch.json").unwrap())
1096                } else {
1097                    dir.join(RelPath::unix("debug.json").unwrap())
1098                };
1099                ProjectPath {
1100                    worktree_id: id,
1101                    path: relative_path,
1102                }
1103            }
1104            _ => return self.save_scenario(scenario, worktree_id, window, cx),
1105        };
1106
1107        let editor = workspace.update(cx, |workspace, cx| {
1108            workspace.open_path(project_path, None, true, window, cx)
1109        });
1110        cx.spawn_in(window, async move |_, cx| {
1111            let editor = editor.await?;
1112            let editor = cx
1113                .update(|_, cx| editor.act_as::<Editor>(cx))?
1114                .context("expected editor")?;
1115
1116            // unfortunately debug tasks don't have an easy way to globally
1117            // identify them. to jump to the one that you just created or an
1118            // 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
1119            editor.update_in(cx, |editor, window, cx| {
1120                let row = editor.text(cx).lines().enumerate().find_map(|(row, text)| {
1121                    if text.contains(scenario.label.as_ref()) && text.contains("\"label\": ") {
1122                        Some(row)
1123                    } else {
1124                        None
1125                    }
1126                });
1127                if let Some(row) = row {
1128                    editor.go_to_singleton_buffer_point(
1129                        text::Point::new(row as u32, 4),
1130                        window,
1131                        cx,
1132                    );
1133                }
1134            })?;
1135
1136            Ok(())
1137        })
1138    }
1139
1140    pub(crate) fn save_scenario(
1141        &self,
1142        scenario: DebugScenario,
1143        worktree_id: WorktreeId,
1144        window: &mut Window,
1145        cx: &mut Context<Self>,
1146    ) -> Task<Result<()>> {
1147        let this = cx.weak_entity();
1148        let project = self.project.clone();
1149        self.workspace
1150            .update(cx, |workspace, cx| {
1151                let Some(mut path) = workspace.absolute_path_of_worktree(worktree_id, cx) else {
1152                    return Task::ready(Err(anyhow!("Couldn't get worktree path")));
1153                };
1154
1155                let serialized_scenario = serde_json::to_value(scenario);
1156
1157                cx.spawn_in(window, async move |workspace, cx| {
1158                    let serialized_scenario = serialized_scenario?;
1159                    let fs =
1160                        workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
1161
1162                    path.push(paths::local_settings_folder_name());
1163                    if !fs.is_dir(path.as_path()).await {
1164                        fs.create_dir(path.as_path()).await?;
1165                    }
1166                    path.pop();
1167
1168                    path.push(paths::local_debug_file_relative_path().as_std_path());
1169                    let path = path.as_path();
1170
1171                    if !fs.is_file(path).await {
1172                        fs.create_file(path, Default::default()).await?;
1173                        fs.write(
1174                            path,
1175                            settings::initial_local_debug_tasks_content()
1176                                .to_string()
1177                                .as_bytes(),
1178                        )
1179                        .await?;
1180                    }
1181                    let project_path = workspace.update(cx, |workspace, cx| {
1182                        workspace
1183                            .project()
1184                            .read(cx)
1185                            .project_path_for_absolute_path(path, cx)
1186                            .context(
1187                                "Couldn't get project path for .zed/debug.json in active worktree",
1188                            )
1189                    })??;
1190
1191                    let editor = this
1192                        .update_in(cx, |this, window, cx| {
1193                            this.workspace.update(cx, |workspace, cx| {
1194                                workspace.open_path(project_path, None, true, window, cx)
1195                            })
1196                        })??
1197                        .await?;
1198                    let editor = cx
1199                        .update(|_, cx| editor.act_as::<Editor>(cx))?
1200                        .context("expected editor")?;
1201
1202                    let new_scenario = serde_json_lenient::to_string_pretty(&serialized_scenario)?
1203                        .lines()
1204                        .map(|l| format!("  {l}"))
1205                        .join("\n");
1206
1207                    editor
1208                        .update_in(cx, |editor, window, cx| {
1209                            Self::insert_task_into_editor(editor, new_scenario, project, window, cx)
1210                        })??
1211                        .await
1212                })
1213            })
1214            .unwrap_or_else(|err| Task::ready(Err(err)))
1215    }
1216
1217    pub fn insert_task_into_editor(
1218        editor: &mut Editor,
1219        new_scenario: String,
1220        project: Entity<Project>,
1221        window: &mut Window,
1222        cx: &mut Context<Editor>,
1223    ) -> Result<Task<Result<()>>> {
1224        static LAST_ITEM_QUERY: LazyLock<Query> = LazyLock::new(|| {
1225            Query::new(
1226                &tree_sitter_json::LANGUAGE.into(),
1227                "(document (array (object) @object))", // TODO: use "." anchor to only match last object
1228            )
1229            .expect("Failed to create LAST_ITEM_QUERY")
1230        });
1231        static EMPTY_ARRAY_QUERY: LazyLock<Query> = LazyLock::new(|| {
1232            Query::new(
1233                &tree_sitter_json::LANGUAGE.into(),
1234                "(document (array) @array)",
1235            )
1236            .expect("Failed to create EMPTY_ARRAY_QUERY")
1237        });
1238
1239        let content = editor.text(cx);
1240        let mut parser = tree_sitter::Parser::new();
1241        parser.set_language(&tree_sitter_json::LANGUAGE.into())?;
1242        let mut cursor = tree_sitter::QueryCursor::new();
1243        let syntax_tree = parser
1244            .parse(&content, None)
1245            .context("could not parse debug.json")?;
1246        let mut matches = cursor.matches(
1247            &LAST_ITEM_QUERY,
1248            syntax_tree.root_node(),
1249            content.as_bytes(),
1250        );
1251
1252        let mut last_offset = None;
1253        while let Some(mat) = matches.next() {
1254            if let Some(pos) = mat.captures.first().map(|m| m.node.byte_range().end) {
1255                last_offset = Some(MultiBufferOffset(pos))
1256            }
1257        }
1258        let mut edits = Vec::new();
1259        let mut cursor_position = MultiBufferOffset(0);
1260
1261        if let Some(pos) = last_offset {
1262            edits.push((pos..pos, format!(",\n{new_scenario}")));
1263            cursor_position = pos + ",\n  ".len();
1264        } else {
1265            let mut matches = cursor.matches(
1266                &EMPTY_ARRAY_QUERY,
1267                syntax_tree.root_node(),
1268                content.as_bytes(),
1269            );
1270
1271            if let Some(mat) = matches.next() {
1272                if let Some(pos) = mat.captures.first().map(|m| m.node.byte_range().end - 1) {
1273                    edits.push((
1274                        MultiBufferOffset(pos)..MultiBufferOffset(pos),
1275                        format!("\n{new_scenario}\n"),
1276                    ));
1277                    cursor_position = MultiBufferOffset(pos) + "\n  ".len();
1278                }
1279            } else {
1280                edits.push((
1281                    MultiBufferOffset(0)..MultiBufferOffset(0),
1282                    format!("[\n{}\n]", new_scenario),
1283                ));
1284                cursor_position = MultiBufferOffset("[\n  ".len());
1285            }
1286        }
1287        editor.transact(window, cx, |editor, window, cx| {
1288            editor.edit(edits, cx);
1289            let snapshot = editor.buffer().read(cx).read(cx);
1290            let point = cursor_position.to_point(&snapshot);
1291            drop(snapshot);
1292            editor.go_to_singleton_buffer_point(point, window, cx);
1293        });
1294        Ok(editor.save(SaveOptions::default(), project, window, cx))
1295    }
1296
1297    pub(crate) fn toggle_thread_picker(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1298        self.thread_picker_menu_handle.toggle(window, cx);
1299    }
1300
1301    pub(crate) fn toggle_session_picker(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1302        self.session_picker_menu_handle.toggle(window, cx);
1303    }
1304
1305    fn toggle_zoom(
1306        &mut self,
1307        _: &workspace::ToggleZoom,
1308        window: &mut Window,
1309        cx: &mut Context<Self>,
1310    ) {
1311        if self.is_zoomed {
1312            cx.emit(PanelEvent::ZoomOut);
1313        } else {
1314            if !self.focus_handle(cx).contains_focused(window, cx) {
1315                cx.focus_self(window);
1316            }
1317            cx.emit(PanelEvent::ZoomIn);
1318        }
1319    }
1320
1321    fn label_for_child_session(
1322        &self,
1323        parent_session: &Entity<Session>,
1324        request: &StartDebuggingRequestArguments,
1325        cx: &mut Context<'_, Self>,
1326    ) -> Option<SharedString> {
1327        let adapter = parent_session.read(cx).adapter();
1328        if let Some(adapter) = DapRegistry::global(cx).adapter(&adapter)
1329            && let Some(label) = adapter.label_for_child_session(request)
1330        {
1331            return Some(label.into());
1332        }
1333        None
1334    }
1335
1336    fn retain_sessions(&mut self, keep: impl Fn(&Entity<DebugSession>) -> bool) {
1337        self.sessions_with_children
1338            .retain(|session, _| keep(session));
1339        for children in self.sessions_with_children.values_mut() {
1340            children.retain(|child| {
1341                let Some(child) = child.upgrade() else {
1342                    return false;
1343                };
1344                keep(&child)
1345            });
1346        }
1347    }
1348
1349    fn render_history_button(
1350        &self,
1351        running_state: &Entity<RunningState>,
1352        thread_status: ThreadStatus,
1353        window: &mut Window,
1354    ) -> IconButton {
1355        IconButton::new("debug-back-in-history", IconName::HistoryRerun)
1356            .icon_size(IconSize::Small)
1357            .on_click(window.listener_for(running_state, |this, _, _window, cx| {
1358                this.session().update(cx, |session, cx| {
1359                    let ix = session
1360                        .active_snapshot_index()
1361                        .unwrap_or_else(|| session.historic_snapshots().len());
1362
1363                    session.select_historic_snapshot(Some(ix.saturating_sub(1)), cx);
1364                })
1365            }))
1366            .disabled(
1367                thread_status == ThreadStatus::Running || thread_status == ThreadStatus::Stepping,
1368            )
1369    }
1370
1371    fn render_history_toggle_button(
1372        &self,
1373        thread_status: ThreadStatus,
1374        running_state: &Entity<RunningState>,
1375    ) -> impl IntoElement {
1376        PopoverMenu::new("debug-back-in-history-menu")
1377            .trigger(
1378                ui::ButtonLike::new_rounded_right("debug-back-in-history-menu-trigger")
1379                    .layer(ui::ElevationIndex::ModalSurface)
1380                    .size(ui::ButtonSize::None)
1381                    .child(
1382                        div()
1383                            .px_1()
1384                            .child(Icon::new(IconName::ChevronDown).size(IconSize::XSmall)),
1385                    )
1386                    .disabled(
1387                        thread_status == ThreadStatus::Running
1388                            || thread_status == ThreadStatus::Stepping,
1389                    ),
1390            )
1391            .menu({
1392                let running_state = running_state.clone();
1393                move |window, cx| {
1394                    let handler =
1395                        |ix: Option<usize>, running_state: Entity<RunningState>, cx: &mut App| {
1396                            running_state.update(cx, |state, cx| {
1397                                state.session().update(cx, |session, cx| {
1398                                    session.select_historic_snapshot(ix, cx);
1399                                })
1400                            })
1401                        };
1402
1403                    let running_state = running_state.clone();
1404                    Some(ContextMenu::build(
1405                        window,
1406                        cx,
1407                        move |mut context_menu, _window, cx| {
1408                            let history = running_state
1409                                .read(cx)
1410                                .session()
1411                                .read(cx)
1412                                .historic_snapshots();
1413
1414                            context_menu = context_menu.entry("Current State", None, {
1415                                let running_state = running_state.clone();
1416                                move |_window, cx| {
1417                                    handler(None, running_state.clone(), cx);
1418                                }
1419                            });
1420                            context_menu = context_menu.separator();
1421
1422                            for (ix, _) in history.iter().enumerate().rev() {
1423                                context_menu =
1424                                    context_menu.entry(format!("history-{}", ix + 1), None, {
1425                                        let running_state = running_state.clone();
1426                                        move |_window, cx| {
1427                                            handler(Some(ix), running_state.clone(), cx);
1428                                        }
1429                                    });
1430                            }
1431
1432                            context_menu
1433                        },
1434                    ))
1435                }
1436            })
1437            .anchor(Corner::TopRight)
1438    }
1439}
1440
1441async fn register_session_inner(
1442    this: &WeakEntity<DebugPanel>,
1443    session: Entity<Session>,
1444    cx: &mut AsyncWindowContext,
1445) -> Result<Entity<DebugSession>> {
1446    let adapter_name = session.read_with(cx, |session, _| session.adapter())?;
1447    this.update_in(cx, |_, window, cx| {
1448        cx.subscribe_in(
1449            &session,
1450            window,
1451            move |this, session, event: &SessionStateEvent, window, cx| match event {
1452                SessionStateEvent::Restart => {
1453                    this.handle_restart_request(session.clone(), window, cx);
1454                }
1455                SessionStateEvent::SpawnChildSession { request } => {
1456                    this.handle_start_debugging_request(request, session.clone(), window, cx);
1457                }
1458                _ => {}
1459            },
1460        )
1461        .detach();
1462    })
1463    .ok();
1464    let serialized_layout = persistence::get_serialized_layout(adapter_name).await;
1465    let debug_session = this.update_in(cx, |this, window, cx| {
1466        let parent_session = this
1467            .sessions_with_children
1468            .keys()
1469            .find(|p| Some(p.read(cx).session_id(cx)) == session.read(cx).parent_id(cx))
1470            .cloned();
1471        this.retain_sessions(|session| {
1472            !session
1473                .read(cx)
1474                .running_state()
1475                .read(cx)
1476                .session()
1477                .read(cx)
1478                .is_terminated()
1479        });
1480
1481        let debug_session = DebugSession::running(
1482            this.project.clone(),
1483            this.workspace.clone(),
1484            parent_session
1485                .as_ref()
1486                .map(|p| p.read(cx).running_state().read(cx).debug_terminal.clone()),
1487            session,
1488            serialized_layout,
1489            this.position(window, cx).axis(),
1490            window,
1491            cx,
1492        );
1493
1494        // We might want to make this an event subscription and only notify when a new thread is selected
1495        // This is used to filter the command menu correctly
1496        cx.observe(
1497            &debug_session.read(cx).running_state().clone(),
1498            |_, _, cx| cx.notify(),
1499        )
1500        .detach();
1501        let insert_position = this
1502            .sessions_with_children
1503            .keys()
1504            .position(|session| Some(session) == parent_session.as_ref())
1505            .map(|position| position + 1)
1506            .unwrap_or(this.sessions_with_children.len());
1507        // Maintain topological sort order of sessions
1508        let (_, old) = this.sessions_with_children.insert_before(
1509            insert_position,
1510            debug_session.clone(),
1511            Default::default(),
1512        );
1513        debug_assert!(old.is_none());
1514        if let Some(parent_session) = parent_session {
1515            this.sessions_with_children
1516                .entry(parent_session)
1517                .and_modify(|children| children.push(debug_session.downgrade()));
1518        }
1519
1520        debug_session
1521    })?;
1522    Ok(debug_session)
1523}
1524
1525impl EventEmitter<PanelEvent> for DebugPanel {}
1526
1527impl Focusable for DebugPanel {
1528    fn focus_handle(&self, _: &App) -> FocusHandle {
1529        self.focus_handle.clone()
1530    }
1531}
1532
1533impl Panel for DebugPanel {
1534    fn persistent_name() -> &'static str {
1535        "DebugPanel"
1536    }
1537
1538    fn panel_key() -> &'static str {
1539        DEBUG_PANEL_KEY
1540    }
1541
1542    fn position(&self, _window: &Window, cx: &App) -> DockPosition {
1543        DebuggerSettings::get_global(cx).dock.into()
1544    }
1545
1546    fn position_is_valid(&self, _: DockPosition) -> bool {
1547        true
1548    }
1549
1550    fn set_position(
1551        &mut self,
1552        position: DockPosition,
1553        window: &mut Window,
1554        cx: &mut Context<Self>,
1555    ) {
1556        if position.axis() != self.position(window, cx).axis() {
1557            self.sessions_with_children.keys().for_each(|session_item| {
1558                session_item.update(cx, |item, cx| {
1559                    item.running_state()
1560                        .update(cx, |state, cx| state.invert_axies(cx))
1561                })
1562            });
1563        }
1564
1565        settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
1566            settings.debugger.get_or_insert_default().dock = Some(position.into());
1567        });
1568    }
1569
1570    fn size(&self, _window: &Window, _: &App) -> Pixels {
1571        self.size
1572    }
1573
1574    fn set_size(&mut self, size: Option<Pixels>, _window: &mut Window, _cx: &mut Context<Self>) {
1575        self.size = size.unwrap_or(px(300.));
1576    }
1577
1578    fn remote_id() -> Option<proto::PanelId> {
1579        Some(proto::PanelId::DebugPanel)
1580    }
1581
1582    fn icon(&self, _window: &Window, _cx: &App) -> Option<IconName> {
1583        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: TaskContext,
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}