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