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("debug-step-over", IconName::ArrowRight)
 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(
 766                                            "debug-step-into",
 767                                            IconName::ArrowDownRight,
 768                                        )
 769                                        .icon_size(IconSize::Small)
 770                                        .on_click(window.listener_for(
 771                                            running_state,
 772                                            |this, _, _window, cx| {
 773                                                this.step_in(cx);
 774                                            },
 775                                        ))
 776                                        .disabled(thread_status != ThreadStatus::Stopped)
 777                                        .tooltip({
 778                                            let focus_handle = focus_handle.clone();
 779                                            move |_window, cx| {
 780                                                Tooltip::for_action_in(
 781                                                    "Step In",
 782                                                    &StepInto,
 783                                                    &focus_handle,
 784                                                    cx,
 785                                                )
 786                                            }
 787                                        }),
 788                                    )
 789                                    .child(
 790                                        IconButton::new("debug-step-out", IconName::ArrowUpRight)
 791                                            .icon_size(IconSize::Small)
 792                                            .on_click(window.listener_for(
 793                                                running_state,
 794                                                |this, _, _window, cx| {
 795                                                    this.step_out(cx);
 796                                                },
 797                                            ))
 798                                            .disabled(thread_status != ThreadStatus::Stopped)
 799                                            .tooltip({
 800                                                let focus_handle = focus_handle.clone();
 801                                                move |_window, cx| {
 802                                                    Tooltip::for_action_in(
 803                                                        "Step Out",
 804                                                        &StepOut,
 805                                                        &focus_handle,
 806                                                        cx,
 807                                                    )
 808                                                }
 809                                            }),
 810                                    )
 811                                    .child(Divider::vertical())
 812                                    .child(
 813                                        IconButton::new("debug-restart", IconName::RotateCcw)
 814                                            .icon_size(IconSize::Small)
 815                                            .on_click(window.listener_for(
 816                                                running_state,
 817                                                |this, _, window, cx| {
 818                                                    this.rerun_session(window, cx);
 819                                                },
 820                                            ))
 821                                            .tooltip({
 822                                                let focus_handle = focus_handle.clone();
 823                                                move |_window, cx| {
 824                                                    Tooltip::for_action_in(
 825                                                        "Rerun Session",
 826                                                        &RerunSession,
 827                                                        &focus_handle,
 828                                                        cx,
 829                                                    )
 830                                                }
 831                                            }),
 832                                    )
 833                                    .child(
 834                                        IconButton::new("debug-stop", IconName::Power)
 835                                            .icon_size(IconSize::Small)
 836                                            .on_click(window.listener_for(
 837                                                running_state,
 838                                                |this, _, _window, cx| {
 839                                                    if this.session().read(cx).is_building() {
 840                                                        this.session().update(cx, |session, cx| {
 841                                                            session.shutdown(cx).detach()
 842                                                        });
 843                                                    } else {
 844                                                        this.stop_thread(cx);
 845                                                    }
 846                                                },
 847                                            ))
 848                                            .disabled(active_session.as_ref().is_none_or(
 849                                                |session| {
 850                                                    session
 851                                                        .read(cx)
 852                                                        .session(cx)
 853                                                        .read(cx)
 854                                                        .is_terminated()
 855                                                },
 856                                            ))
 857                                            .tooltip({
 858                                                let focus_handle = focus_handle.clone();
 859                                                let label = if capabilities
 860                                                    .supports_terminate_threads_request
 861                                                    .unwrap_or_default()
 862                                                {
 863                                                    "Terminate Thread"
 864                                                } else {
 865                                                    "Terminate All Threads"
 866                                                };
 867                                                move |_window, cx| {
 868                                                    Tooltip::for_action_in(
 869                                                        label,
 870                                                        &Stop,
 871                                                        &focus_handle,
 872                                                        cx,
 873                                                    )
 874                                                }
 875                                            }),
 876                                    )
 877                                    .when(
 878                                        supports_detach,
 879                                        |div| {
 880                                            div.child(
 881                                                IconButton::new(
 882                                                    "debug-disconnect",
 883                                                    IconName::DebugDetach,
 884                                                )
 885                                                .disabled(
 886                                                    thread_status != ThreadStatus::Stopped
 887                                                        && thread_status != ThreadStatus::Running,
 888                                                )
 889                                                .icon_size(IconSize::Small)
 890                                                .on_click(window.listener_for(
 891                                                    running_state,
 892                                                    |this, _, _, cx| {
 893                                                        this.detach_client(cx);
 894                                                    },
 895                                                ))
 896                                                .tooltip({
 897                                                    let focus_handle = focus_handle.clone();
 898                                                    move |_window, cx| {
 899                                                        Tooltip::for_action_in(
 900                                                            "Detach",
 901                                                            &Detach,
 902                                                            &focus_handle,
 903                                                            cx,
 904                                                        )
 905                                                    }
 906                                                }),
 907                                            )
 908                                        },
 909                                    )
 910                                },
 911                            ),
 912                        )
 913                        .when(is_side, |this| {
 914                            this.child(new_session_button())
 915                                .child(edit_debug_json_button())
 916                                .child(documentation_button())
 917                                .child(logs_button())
 918                        }),
 919                )
 920                .child(
 921                    h_flex()
 922                        .gap_0p5()
 923                        .when(is_side, |this| this.justify_between())
 924                        .child(
 925                            h_flex().when_some(
 926                                active_session
 927                                    .as_ref()
 928                                    .map(|session| session.read(cx).running_state())
 929                                    .cloned(),
 930                                |this, running_state| {
 931                                    this.children({
 932                                        let threads =
 933                                            running_state.update(cx, |running_state, cx| {
 934                                                let session = running_state.session();
 935                                                session.read(cx).is_started().then(|| {
 936                                                    session.update(cx, |session, cx| {
 937                                                        session.threads(cx)
 938                                                    })
 939                                                })
 940                                            });
 941
 942                                        threads.and_then(|threads| {
 943                                            self.render_thread_dropdown(
 944                                                &running_state,
 945                                                threads,
 946                                                window,
 947                                                cx,
 948                                            )
 949                                        })
 950                                    })
 951                                    .when(!is_side, |this| {
 952                                        this.gap_0p5().child(Divider::vertical())
 953                                    })
 954                                },
 955                            ),
 956                        )
 957                        .child(
 958                            h_flex()
 959                                .gap_0p5()
 960                                .children(self.render_session_menu(
 961                                    self.active_session(),
 962                                    self.running_state(cx),
 963                                    window,
 964                                    cx,
 965                                ))
 966                                .when(!is_side, |this| {
 967                                    this.child(new_session_button())
 968                                        .child(edit_debug_json_button())
 969                                        .child(documentation_button())
 970                                        .child(logs_button())
 971                                        .child(close_bottom_panel_button)
 972                                }),
 973                        ),
 974                ),
 975        )
 976    }
 977
 978    pub(crate) fn activate_pane_in_direction(
 979        &mut self,
 980        direction: SplitDirection,
 981        window: &mut Window,
 982        cx: &mut Context<Self>,
 983    ) {
 984        if let Some(session) = self.active_session() {
 985            session.update(cx, |session, cx| {
 986                session.running_state().update(cx, |running, cx| {
 987                    running.activate_pane_in_direction(direction, window, cx);
 988                })
 989            });
 990        }
 991    }
 992
 993    pub(crate) fn activate_item(
 994        &mut self,
 995        item: DebuggerPaneItem,
 996        window: &mut Window,
 997        cx: &mut Context<Self>,
 998    ) {
 999        if let Some(session) = self.active_session() {
1000            session.update(cx, |session, cx| {
1001                session.running_state().update(cx, |running, cx| {
1002                    running.activate_item(item, window, cx);
1003                });
1004            });
1005        }
1006    }
1007
1008    pub(crate) fn activate_session_by_id(
1009        &mut self,
1010        session_id: SessionId,
1011        window: &mut Window,
1012        cx: &mut Context<Self>,
1013    ) {
1014        if let Some(session) = self
1015            .sessions_with_children
1016            .keys()
1017            .find(|session| session.read(cx).session_id(cx) == session_id)
1018        {
1019            self.activate_session(session.clone(), window, cx);
1020        }
1021    }
1022
1023    pub(crate) fn activate_session(
1024        &mut self,
1025        session_item: Entity<DebugSession>,
1026        window: &mut Window,
1027        cx: &mut Context<Self>,
1028    ) {
1029        debug_assert!(self.sessions_with_children.contains_key(&session_item));
1030        session_item.focus_handle(cx).focus(window);
1031        session_item.update(cx, |this, cx| {
1032            this.running_state().update(cx, |this, cx| {
1033                this.go_to_selected_stack_frame(window, cx);
1034            });
1035        });
1036        self.active_session = Some(session_item);
1037        cx.notify();
1038    }
1039
1040    pub(crate) fn go_to_scenario_definition(
1041        &self,
1042        kind: TaskSourceKind,
1043        scenario: DebugScenario,
1044        worktree_id: WorktreeId,
1045        window: &mut Window,
1046        cx: &mut Context<Self>,
1047    ) -> Task<Result<()>> {
1048        let Some(workspace) = self.workspace.upgrade() else {
1049            return Task::ready(Ok(()));
1050        };
1051        let project_path = match kind {
1052            TaskSourceKind::AbsPath { abs_path, .. } => {
1053                let Some(project_path) = workspace
1054                    .read(cx)
1055                    .project()
1056                    .read(cx)
1057                    .project_path_for_absolute_path(&abs_path, cx)
1058                else {
1059                    return Task::ready(Err(anyhow!("no abs path")));
1060                };
1061
1062                project_path
1063            }
1064            TaskSourceKind::Worktree {
1065                id,
1066                directory_in_worktree: dir,
1067                ..
1068            } => {
1069                let relative_path = if dir.ends_with(RelPath::unix(".vscode").unwrap()) {
1070                    dir.join(RelPath::unix("launch.json").unwrap())
1071                } else {
1072                    dir.join(RelPath::unix("debug.json").unwrap())
1073                };
1074                ProjectPath {
1075                    worktree_id: id,
1076                    path: relative_path,
1077                }
1078            }
1079            _ => return self.save_scenario(scenario, worktree_id, window, cx),
1080        };
1081
1082        let editor = workspace.update(cx, |workspace, cx| {
1083            workspace.open_path(project_path, None, true, window, cx)
1084        });
1085        cx.spawn_in(window, async move |_, cx| {
1086            let editor = editor.await?;
1087            let editor = cx
1088                .update(|_, cx| editor.act_as::<Editor>(cx))?
1089                .context("expected editor")?;
1090
1091            // unfortunately debug tasks don't have an easy way to globally
1092            // identify them. to jump to the one that you just created or an
1093            // 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
1094            editor.update_in(cx, |editor, window, cx| {
1095                let row = editor.text(cx).lines().enumerate().find_map(|(row, text)| {
1096                    if text.contains(scenario.label.as_ref()) && text.contains("\"label\": ") {
1097                        Some(row)
1098                    } else {
1099                        None
1100                    }
1101                });
1102                if let Some(row) = row {
1103                    editor.go_to_singleton_buffer_point(
1104                        text::Point::new(row as u32, 4),
1105                        window,
1106                        cx,
1107                    );
1108                }
1109            })?;
1110
1111            Ok(())
1112        })
1113    }
1114
1115    pub(crate) fn save_scenario(
1116        &self,
1117        scenario: DebugScenario,
1118        worktree_id: WorktreeId,
1119        window: &mut Window,
1120        cx: &mut Context<Self>,
1121    ) -> Task<Result<()>> {
1122        let this = cx.weak_entity();
1123        let project = self.project.clone();
1124        self.workspace
1125            .update(cx, |workspace, cx| {
1126                let Some(mut path) = workspace.absolute_path_of_worktree(worktree_id, cx) else {
1127                    return Task::ready(Err(anyhow!("Couldn't get worktree path")));
1128                };
1129
1130                let serialized_scenario = serde_json::to_value(scenario);
1131
1132                cx.spawn_in(window, async move |workspace, cx| {
1133                    let serialized_scenario = serialized_scenario?;
1134                    let fs =
1135                        workspace.read_with(cx, |workspace, _| workspace.app_state().fs.clone())?;
1136
1137                    path.push(paths::local_settings_folder_name());
1138                    if !fs.is_dir(path.as_path()).await {
1139                        fs.create_dir(path.as_path()).await?;
1140                    }
1141                    path.pop();
1142
1143                    path.push(paths::local_debug_file_relative_path().as_std_path());
1144                    let path = path.as_path();
1145
1146                    if !fs.is_file(path).await {
1147                        fs.create_file(path, Default::default()).await?;
1148                        fs.write(
1149                            path,
1150                            settings::initial_local_debug_tasks_content()
1151                                .to_string()
1152                                .as_bytes(),
1153                        )
1154                        .await?;
1155                    }
1156                    let project_path = workspace.update(cx, |workspace, cx| {
1157                        workspace
1158                            .project()
1159                            .read(cx)
1160                            .project_path_for_absolute_path(path, cx)
1161                            .context(
1162                                "Couldn't get project path for .zed/debug.json in active worktree",
1163                            )
1164                    })??;
1165
1166                    let editor = this
1167                        .update_in(cx, |this, window, cx| {
1168                            this.workspace.update(cx, |workspace, cx| {
1169                                workspace.open_path(project_path, None, true, window, cx)
1170                            })
1171                        })??
1172                        .await?;
1173                    let editor = cx
1174                        .update(|_, cx| editor.act_as::<Editor>(cx))?
1175                        .context("expected editor")?;
1176
1177                    let new_scenario = serde_json_lenient::to_string_pretty(&serialized_scenario)?
1178                        .lines()
1179                        .map(|l| format!("  {l}"))
1180                        .join("\n");
1181
1182                    editor
1183                        .update_in(cx, |editor, window, cx| {
1184                            Self::insert_task_into_editor(editor, new_scenario, project, window, cx)
1185                        })??
1186                        .await
1187                })
1188            })
1189            .unwrap_or_else(|err| Task::ready(Err(err)))
1190    }
1191
1192    pub fn insert_task_into_editor(
1193        editor: &mut Editor,
1194        new_scenario: String,
1195        project: Entity<Project>,
1196        window: &mut Window,
1197        cx: &mut Context<Editor>,
1198    ) -> Result<Task<Result<()>>> {
1199        static LAST_ITEM_QUERY: LazyLock<Query> = LazyLock::new(|| {
1200            Query::new(
1201                &tree_sitter_json::LANGUAGE.into(),
1202                "(document (array (object) @object))", // TODO: use "." anchor to only match last object
1203            )
1204            .expect("Failed to create LAST_ITEM_QUERY")
1205        });
1206        static EMPTY_ARRAY_QUERY: LazyLock<Query> = LazyLock::new(|| {
1207            Query::new(
1208                &tree_sitter_json::LANGUAGE.into(),
1209                "(document (array) @array)",
1210            )
1211            .expect("Failed to create EMPTY_ARRAY_QUERY")
1212        });
1213
1214        let content = editor.text(cx);
1215        let mut parser = tree_sitter::Parser::new();
1216        parser.set_language(&tree_sitter_json::LANGUAGE.into())?;
1217        let mut cursor = tree_sitter::QueryCursor::new();
1218        let syntax_tree = parser
1219            .parse(&content, None)
1220            .context("could not parse debug.json")?;
1221        let mut matches = cursor.matches(
1222            &LAST_ITEM_QUERY,
1223            syntax_tree.root_node(),
1224            content.as_bytes(),
1225        );
1226
1227        let mut last_offset = None;
1228        while let Some(mat) = matches.next() {
1229            if let Some(pos) = mat.captures.first().map(|m| m.node.byte_range().end) {
1230                last_offset = Some(MultiBufferOffset(pos))
1231            }
1232        }
1233        let mut edits = Vec::new();
1234        let mut cursor_position = MultiBufferOffset(0);
1235
1236        if let Some(pos) = last_offset {
1237            edits.push((pos..pos, format!(",\n{new_scenario}")));
1238            cursor_position = pos + ",\n  ".len();
1239        } else {
1240            let mut matches = cursor.matches(
1241                &EMPTY_ARRAY_QUERY,
1242                syntax_tree.root_node(),
1243                content.as_bytes(),
1244            );
1245
1246            if let Some(mat) = matches.next() {
1247                if let Some(pos) = mat.captures.first().map(|m| m.node.byte_range().end - 1) {
1248                    edits.push((
1249                        MultiBufferOffset(pos)..MultiBufferOffset(pos),
1250                        format!("\n{new_scenario}\n"),
1251                    ));
1252                    cursor_position = MultiBufferOffset(pos) + "\n  ".len();
1253                }
1254            } else {
1255                edits.push((
1256                    MultiBufferOffset(0)..MultiBufferOffset(0),
1257                    format!("[\n{}\n]", new_scenario),
1258                ));
1259                cursor_position = MultiBufferOffset("[\n  ".len());
1260            }
1261        }
1262        editor.transact(window, cx, |editor, window, cx| {
1263            editor.edit(edits, cx);
1264            let snapshot = editor.buffer().read(cx).read(cx);
1265            let point = cursor_position.to_point(&snapshot);
1266            drop(snapshot);
1267            editor.go_to_singleton_buffer_point(point, window, cx);
1268        });
1269        Ok(editor.save(SaveOptions::default(), project, window, cx))
1270    }
1271
1272    pub(crate) fn toggle_thread_picker(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1273        self.thread_picker_menu_handle.toggle(window, cx);
1274    }
1275
1276    pub(crate) fn toggle_session_picker(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1277        self.session_picker_menu_handle.toggle(window, cx);
1278    }
1279
1280    fn toggle_zoom(
1281        &mut self,
1282        _: &workspace::ToggleZoom,
1283        window: &mut Window,
1284        cx: &mut Context<Self>,
1285    ) {
1286        if self.is_zoomed {
1287            cx.emit(PanelEvent::ZoomOut);
1288        } else {
1289            if !self.focus_handle(cx).contains_focused(window, cx) {
1290                cx.focus_self(window);
1291            }
1292            cx.emit(PanelEvent::ZoomIn);
1293        }
1294    }
1295
1296    fn label_for_child_session(
1297        &self,
1298        parent_session: &Entity<Session>,
1299        request: &StartDebuggingRequestArguments,
1300        cx: &mut Context<'_, Self>,
1301    ) -> Option<SharedString> {
1302        let adapter = parent_session.read(cx).adapter();
1303        if let Some(adapter) = DapRegistry::global(cx).adapter(&adapter)
1304            && let Some(label) = adapter.label_for_child_session(request)
1305        {
1306            return Some(label.into());
1307        }
1308        None
1309    }
1310
1311    fn retain_sessions(&mut self, keep: impl Fn(&Entity<DebugSession>) -> bool) {
1312        self.sessions_with_children
1313            .retain(|session, _| keep(session));
1314        for children in self.sessions_with_children.values_mut() {
1315            children.retain(|child| {
1316                let Some(child) = child.upgrade() else {
1317                    return false;
1318                };
1319                keep(&child)
1320            });
1321        }
1322    }
1323}
1324
1325async fn register_session_inner(
1326    this: &WeakEntity<DebugPanel>,
1327    session: Entity<Session>,
1328    cx: &mut AsyncWindowContext,
1329) -> Result<Entity<DebugSession>> {
1330    let adapter_name = session.read_with(cx, |session, _| session.adapter())?;
1331    this.update_in(cx, |_, window, cx| {
1332        cx.subscribe_in(
1333            &session,
1334            window,
1335            move |this, session, event: &SessionStateEvent, window, cx| match event {
1336                SessionStateEvent::Restart => {
1337                    this.handle_restart_request(session.clone(), window, cx);
1338                }
1339                SessionStateEvent::SpawnChildSession { request } => {
1340                    this.handle_start_debugging_request(request, session.clone(), window, cx);
1341                }
1342                _ => {}
1343            },
1344        )
1345        .detach();
1346    })
1347    .ok();
1348    let serialized_layout = persistence::get_serialized_layout(adapter_name).await;
1349    let debug_session = this.update_in(cx, |this, window, cx| {
1350        let parent_session = this
1351            .sessions_with_children
1352            .keys()
1353            .find(|p| Some(p.read(cx).session_id(cx)) == session.read(cx).parent_id(cx))
1354            .cloned();
1355        this.retain_sessions(|session| {
1356            !session
1357                .read(cx)
1358                .running_state()
1359                .read(cx)
1360                .session()
1361                .read(cx)
1362                .is_terminated()
1363        });
1364
1365        let debug_session = DebugSession::running(
1366            this.project.clone(),
1367            this.workspace.clone(),
1368            parent_session
1369                .as_ref()
1370                .map(|p| p.read(cx).running_state().read(cx).debug_terminal.clone()),
1371            session,
1372            serialized_layout,
1373            this.position(window, cx).axis(),
1374            window,
1375            cx,
1376        );
1377
1378        // We might want to make this an event subscription and only notify when a new thread is selected
1379        // This is used to filter the command menu correctly
1380        cx.observe(
1381            &debug_session.read(cx).running_state().clone(),
1382            |_, _, cx| cx.notify(),
1383        )
1384        .detach();
1385        let insert_position = this
1386            .sessions_with_children
1387            .keys()
1388            .position(|session| Some(session) == parent_session.as_ref())
1389            .map(|position| position + 1)
1390            .unwrap_or(this.sessions_with_children.len());
1391        // Maintain topological sort order of sessions
1392        let (_, old) = this.sessions_with_children.insert_before(
1393            insert_position,
1394            debug_session.clone(),
1395            Default::default(),
1396        );
1397        debug_assert!(old.is_none());
1398        if let Some(parent_session) = parent_session {
1399            this.sessions_with_children
1400                .entry(parent_session)
1401                .and_modify(|children| children.push(debug_session.downgrade()));
1402        }
1403
1404        debug_session
1405    })?;
1406    Ok(debug_session)
1407}
1408
1409impl EventEmitter<PanelEvent> for DebugPanel {}
1410
1411impl Focusable for DebugPanel {
1412    fn focus_handle(&self, _: &App) -> FocusHandle {
1413        self.focus_handle.clone()
1414    }
1415}
1416
1417impl Panel for DebugPanel {
1418    fn persistent_name() -> &'static str {
1419        "DebugPanel"
1420    }
1421
1422    fn panel_key() -> &'static str {
1423        DEBUG_PANEL_KEY
1424    }
1425
1426    fn position(&self, _window: &Window, cx: &App) -> DockPosition {
1427        DebuggerSettings::get_global(cx).dock.into()
1428    }
1429
1430    fn position_is_valid(&self, _: DockPosition) -> bool {
1431        true
1432    }
1433
1434    fn set_position(
1435        &mut self,
1436        position: DockPosition,
1437        window: &mut Window,
1438        cx: &mut Context<Self>,
1439    ) {
1440        if position.axis() != self.position(window, cx).axis() {
1441            self.sessions_with_children.keys().for_each(|session_item| {
1442                session_item.update(cx, |item, cx| {
1443                    item.running_state()
1444                        .update(cx, |state, _| state.invert_axies())
1445                })
1446            });
1447        }
1448
1449        settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
1450            settings.debugger.get_or_insert_default().dock = Some(position.into());
1451        });
1452    }
1453
1454    fn size(&self, _window: &Window, _: &App) -> Pixels {
1455        self.size
1456    }
1457
1458    fn set_size(&mut self, size: Option<Pixels>, _window: &mut Window, _cx: &mut Context<Self>) {
1459        self.size = size.unwrap_or(px(300.));
1460    }
1461
1462    fn remote_id() -> Option<proto::PanelId> {
1463        Some(proto::PanelId::DebugPanel)
1464    }
1465
1466    fn icon(&self, _window: &Window, _cx: &App) -> Option<IconName> {
1467        Some(IconName::Debug)
1468    }
1469
1470    fn icon_tooltip(&self, _window: &Window, cx: &App) -> Option<&'static str> {
1471        if DebuggerSettings::get_global(cx).button {
1472            Some("Debug Panel")
1473        } else {
1474            None
1475        }
1476    }
1477
1478    fn toggle_action(&self) -> Box<dyn Action> {
1479        Box::new(ToggleFocus)
1480    }
1481
1482    fn pane(&self) -> Option<Entity<Pane>> {
1483        None
1484    }
1485
1486    fn activation_priority(&self) -> u32 {
1487        9
1488    }
1489
1490    fn set_active(&mut self, _: bool, _: &mut Window, _: &mut Context<Self>) {}
1491
1492    fn is_zoomed(&self, _window: &Window, _cx: &App) -> bool {
1493        self.is_zoomed
1494    }
1495
1496    fn set_zoomed(&mut self, zoomed: bool, _window: &mut Window, cx: &mut Context<Self>) {
1497        self.is_zoomed = zoomed;
1498        cx.notify();
1499    }
1500}
1501
1502impl Render for DebugPanel {
1503    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1504        let this = cx.weak_entity();
1505
1506        if self
1507            .active_session
1508            .as_ref()
1509            .map(|session| session.read(cx).running_state())
1510            .map(|state| state.read(cx).has_open_context_menu(cx))
1511            .unwrap_or(false)
1512        {
1513            self.context_menu.take();
1514        }
1515
1516        v_flex()
1517            .when(!self.is_zoomed, |this| {
1518                this.when_else(
1519                    self.position(window, cx) == DockPosition::Bottom,
1520                    |this| this.max_h(self.size),
1521                    |this| this.max_w(self.size),
1522                )
1523            })
1524            .size_full()
1525            .key_context("DebugPanel")
1526            .child(h_flex().children(self.top_controls_strip(window, cx)))
1527            .track_focus(&self.focus_handle(cx))
1528            .on_action({
1529                let this = this.clone();
1530                move |_: &workspace::ActivatePaneLeft, window, cx| {
1531                    this.update(cx, |this, cx| {
1532                        this.activate_pane_in_direction(SplitDirection::Left, window, cx);
1533                    })
1534                    .ok();
1535                }
1536            })
1537            .on_action({
1538                let this = this.clone();
1539                move |_: &workspace::ActivatePaneRight, window, cx| {
1540                    this.update(cx, |this, cx| {
1541                        this.activate_pane_in_direction(SplitDirection::Right, window, cx);
1542                    })
1543                    .ok();
1544                }
1545            })
1546            .on_action({
1547                let this = this.clone();
1548                move |_: &workspace::ActivatePaneUp, window, cx| {
1549                    this.update(cx, |this, cx| {
1550                        this.activate_pane_in_direction(SplitDirection::Up, window, cx);
1551                    })
1552                    .ok();
1553                }
1554            })
1555            .on_action({
1556                let this = this.clone();
1557                move |_: &workspace::ActivatePaneDown, window, cx| {
1558                    this.update(cx, |this, cx| {
1559                        this.activate_pane_in_direction(SplitDirection::Down, window, cx);
1560                    })
1561                    .ok();
1562                }
1563            })
1564            .on_action({
1565                let this = this.clone();
1566                move |_: &FocusConsole, window, cx| {
1567                    this.update(cx, |this, cx| {
1568                        this.activate_item(DebuggerPaneItem::Console, window, cx);
1569                    })
1570                    .ok();
1571                }
1572            })
1573            .on_action({
1574                let this = this.clone();
1575                move |_: &FocusVariables, window, cx| {
1576                    this.update(cx, |this, cx| {
1577                        this.activate_item(DebuggerPaneItem::Variables, window, cx);
1578                    })
1579                    .ok();
1580                }
1581            })
1582            .on_action({
1583                let this = this.clone();
1584                move |_: &FocusBreakpointList, window, cx| {
1585                    this.update(cx, |this, cx| {
1586                        this.activate_item(DebuggerPaneItem::BreakpointList, window, cx);
1587                    })
1588                    .ok();
1589                }
1590            })
1591            .on_action({
1592                let this = this.clone();
1593                move |_: &FocusFrames, window, cx| {
1594                    this.update(cx, |this, cx| {
1595                        this.activate_item(DebuggerPaneItem::Frames, window, cx);
1596                    })
1597                    .ok();
1598                }
1599            })
1600            .on_action({
1601                let this = this.clone();
1602                move |_: &FocusModules, window, cx| {
1603                    this.update(cx, |this, cx| {
1604                        this.activate_item(DebuggerPaneItem::Modules, window, cx);
1605                    })
1606                    .ok();
1607                }
1608            })
1609            .on_action({
1610                let this = this.clone();
1611                move |_: &FocusLoadedSources, window, cx| {
1612                    this.update(cx, |this, cx| {
1613                        this.activate_item(DebuggerPaneItem::LoadedSources, window, cx);
1614                    })
1615                    .ok();
1616                }
1617            })
1618            .on_action({
1619                let this = this.clone();
1620                move |_: &FocusTerminal, window, cx| {
1621                    this.update(cx, |this, cx| {
1622                        this.activate_item(DebuggerPaneItem::Terminal, window, cx);
1623                    })
1624                    .ok();
1625                }
1626            })
1627            .on_action({
1628                let this = this.clone();
1629                move |_: &ToggleThreadPicker, window, cx| {
1630                    this.update(cx, |this, cx| {
1631                        this.toggle_thread_picker(window, cx);
1632                    })
1633                    .ok();
1634                }
1635            })
1636            .on_action({
1637                move |_: &ToggleSessionPicker, window, cx| {
1638                    this.update(cx, |this, cx| {
1639                        this.toggle_session_picker(window, cx);
1640                    })
1641                    .ok();
1642                }
1643            })
1644            .on_action(cx.listener(Self::toggle_zoom))
1645            .on_action(cx.listener(|panel, _: &ToggleExpandItem, _, cx| {
1646                let Some(session) = panel.active_session() else {
1647                    return;
1648                };
1649                let active_pane = session
1650                    .read(cx)
1651                    .running_state()
1652                    .read(cx)
1653                    .active_pane()
1654                    .clone();
1655                active_pane.update(cx, |pane, cx| {
1656                    let is_zoomed = pane.is_zoomed();
1657                    pane.set_zoomed(!is_zoomed, cx);
1658                });
1659                cx.notify();
1660            }))
1661            .on_action(cx.listener(Self::copy_debug_adapter_arguments))
1662            .when(self.active_session.is_some(), |this| {
1663                this.on_mouse_down(
1664                    MouseButton::Right,
1665                    cx.listener(|this, event: &MouseDownEvent, window, cx| {
1666                        if this
1667                            .active_session
1668                            .as_ref()
1669                            .map(|session| {
1670                                let state = session.read(cx).running_state();
1671                                state.read(cx).has_pane_at_position(event.position)
1672                            })
1673                            .unwrap_or(false)
1674                        {
1675                            this.deploy_context_menu(event.position, window, cx);
1676                        }
1677                    }),
1678                )
1679                .children(self.context_menu.as_ref().map(|(menu, position, _)| {
1680                    deferred(
1681                        anchored()
1682                            .position(*position)
1683                            .anchor(gpui::Corner::TopLeft)
1684                            .child(menu.clone()),
1685                    )
1686                    .with_priority(1)
1687                }))
1688            })
1689            .map(|this| {
1690                if let Some(active_session) = self.active_session.clone() {
1691                    this.child(active_session)
1692                } else {
1693                    let docked_to_bottom = self.position(window, cx) == DockPosition::Bottom;
1694
1695                    let welcome_experience = v_flex()
1696                        .when_else(
1697                            docked_to_bottom,
1698                            |this| this.w_2_3().h_full().pr_8(),
1699                            |this| this.w_full().h_1_3(),
1700                        )
1701                        .items_center()
1702                        .justify_center()
1703                        .gap_2()
1704                        .child(
1705                            Button::new("spawn-new-session-empty-state", "New Session")
1706                                .icon(IconName::Plus)
1707                                .icon_size(IconSize::Small)
1708                                .icon_color(Color::Muted)
1709                                .icon_position(IconPosition::Start)
1710                                .on_click(|_, window, cx| {
1711                                    window.dispatch_action(crate::Start.boxed_clone(), cx);
1712                                }),
1713                        )
1714                        .child(
1715                            Button::new("edit-debug-settings", "Edit debug.json")
1716                                .icon(IconName::Code)
1717                                .icon_size(IconSize::Small)
1718                                .icon_color(Color::Muted)
1719                                .icon_position(IconPosition::Start)
1720                                .on_click(|_, window, cx| {
1721                                    window.dispatch_action(
1722                                        zed_actions::OpenProjectDebugTasks.boxed_clone(),
1723                                        cx,
1724                                    );
1725                                }),
1726                        )
1727                        .child(
1728                            Button::new("open-debugger-docs", "Debugger Docs")
1729                                .icon(IconName::Book)
1730                                .icon_size(IconSize::Small)
1731                                .icon_color(Color::Muted)
1732                                .icon_position(IconPosition::Start)
1733                                .on_click(|_, _, cx| cx.open_url("https://zed.dev/docs/debugger")),
1734                        )
1735                        .child(
1736                            Button::new(
1737                                "spawn-new-session-install-extensions",
1738                                "Debugger Extensions",
1739                            )
1740                            .icon(IconName::Blocks)
1741                            .icon_size(IconSize::Small)
1742                            .icon_color(Color::Muted)
1743                            .icon_position(IconPosition::Start)
1744                            .on_click(|_, window, cx| {
1745                                window.dispatch_action(
1746                                    zed_actions::Extensions {
1747                                        category_filter: Some(
1748                                            zed_actions::ExtensionCategoryFilter::DebugAdapters,
1749                                        ),
1750                                        id: None,
1751                                    }
1752                                    .boxed_clone(),
1753                                    cx,
1754                                );
1755                            }),
1756                        );
1757
1758                    let has_breakpoints = self
1759                        .project
1760                        .read(cx)
1761                        .breakpoint_store()
1762                        .read(cx)
1763                        .all_source_breakpoints(cx)
1764                        .values()
1765                        .any(|breakpoints| !breakpoints.is_empty());
1766
1767                    let breakpoint_list = v_flex()
1768                        .group("base-breakpoint-list")
1769                        .when_else(
1770                            docked_to_bottom,
1771                            |this| this.min_w_1_3().h_full(),
1772                            |this| this.size_full().h_2_3(),
1773                        )
1774                        .child(
1775                            h_flex()
1776                                .track_focus(&self.breakpoint_list.focus_handle(cx))
1777                                .h(Tab::container_height(cx))
1778                                .p_1p5()
1779                                .w_full()
1780                                .justify_between()
1781                                .border_b_1()
1782                                .border_color(cx.theme().colors().border_variant)
1783                                .child(Label::new("Breakpoints").size(LabelSize::Small))
1784                                .child(
1785                                    h_flex().visible_on_hover("base-breakpoint-list").child(
1786                                        self.breakpoint_list.read(cx).render_control_strip(),
1787                                    ),
1788                                ),
1789                        )
1790                        .when(has_breakpoints, |this| {
1791                            this.child(self.breakpoint_list.clone())
1792                        })
1793                        .when(!has_breakpoints, |this| {
1794                            this.child(
1795                                v_flex().size_full().items_center().justify_center().child(
1796                                    Label::new("No Breakpoints Set")
1797                                        .size(LabelSize::Small)
1798                                        .color(Color::Muted),
1799                                ),
1800                            )
1801                        });
1802
1803                    this.child(
1804                        v_flex()
1805                            .size_full()
1806                            .overflow_hidden()
1807                            .gap_1()
1808                            .items_center()
1809                            .justify_center()
1810                            .map(|this| {
1811                                if docked_to_bottom {
1812                                    this.child(
1813                                        h_flex()
1814                                            .size_full()
1815                                            .child(breakpoint_list)
1816                                            .child(Divider::vertical())
1817                                            .child(welcome_experience)
1818                                            .child(Divider::vertical()),
1819                                    )
1820                                } else {
1821                                    this.child(
1822                                        v_flex()
1823                                            .size_full()
1824                                            .child(welcome_experience)
1825                                            .child(Divider::horizontal())
1826                                            .child(breakpoint_list),
1827                                    )
1828                                }
1829                            }),
1830                    )
1831                }
1832            })
1833            .into_any()
1834    }
1835}
1836
1837struct DebuggerProvider(Entity<DebugPanel>);
1838
1839impl workspace::DebuggerProvider for DebuggerProvider {
1840    fn start_session(
1841        &self,
1842        definition: DebugScenario,
1843        context: TaskContext,
1844        buffer: Option<Entity<Buffer>>,
1845        worktree_id: Option<WorktreeId>,
1846        window: &mut Window,
1847        cx: &mut App,
1848    ) {
1849        self.0.update(cx, |_, cx| {
1850            cx.defer_in(window, move |this, window, cx| {
1851                this.start_session(definition, context, buffer, worktree_id, window, cx);
1852            })
1853        })
1854    }
1855
1856    fn spawn_task_or_modal(
1857        &self,
1858        workspace: &mut Workspace,
1859        action: &tasks_ui::Spawn,
1860        window: &mut Window,
1861        cx: &mut Context<Workspace>,
1862    ) {
1863        spawn_task_or_modal(workspace, action, window, cx);
1864    }
1865
1866    fn debug_scenario_scheduled(&self, cx: &mut App) {
1867        self.0.update(cx, |this, _| {
1868            this.debug_scenario_scheduled_last = true;
1869        });
1870    }
1871
1872    fn task_scheduled(&self, cx: &mut App) {
1873        self.0.update(cx, |this, _| {
1874            this.debug_scenario_scheduled_last = false;
1875        })
1876    }
1877
1878    fn debug_scenario_scheduled_last(&self, cx: &App) -> bool {
1879        self.0.read(cx).debug_scenario_scheduled_last
1880    }
1881
1882    fn active_thread_state(&self, cx: &App) -> Option<ThreadStatus> {
1883        let session = self.0.read(cx).active_session()?;
1884        let thread = session.read(cx).running_state().read(cx).thread_id()?;
1885        session.read(cx).session(cx).read(cx).thread_state(thread)
1886    }
1887}