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