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