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