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