debugger_panel.rs

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