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