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