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,
 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();
 390        let label = curr_session.read(cx).label();
 391        let quirks = curr_session.read(cx).quirks();
 392        let adapter = curr_session.read(cx).adapter();
 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();
 451        let label = self.label_for_child_session(&parent_session, request, cx);
 452        let adapter = parent_session.read(cx).adapter();
 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                {
 535                    this.active_session = this.sessions_with_children.keys().next().cloned();
 536                }
 537                cx.notify()
 538            })
 539            .ok();
 540        })
 541        .detach();
 542    }
 543
 544    pub(crate) fn deploy_context_menu(
 545        &mut self,
 546        position: Point<Pixels>,
 547        window: &mut Window,
 548        cx: &mut Context<Self>,
 549    ) {
 550        if let Some(running_state) = self
 551            .active_session
 552            .as_ref()
 553            .map(|session| session.read(cx).running_state().clone())
 554        {
 555            let pane_items_status = running_state.read(cx).pane_items_status(cx);
 556            let this = cx.weak_entity();
 557
 558            let context_menu = ContextMenu::build(window, cx, |mut menu, _window, _cx| {
 559                for (item_kind, is_visible) in pane_items_status.into_iter() {
 560                    menu = menu.toggleable_entry(item_kind, is_visible, IconPosition::End, None, {
 561                        let this = this.clone();
 562                        move |window, cx| {
 563                            this.update(cx, |this, cx| {
 564                                if let Some(running_state) = this
 565                                    .active_session
 566                                    .as_ref()
 567                                    .map(|session| session.read(cx).running_state().clone())
 568                                {
 569                                    running_state.update(cx, |state, cx| {
 570                                        if is_visible {
 571                                            state.remove_pane_item(item_kind, window, cx);
 572                                        } else {
 573                                            state.add_pane_item(item_kind, position, window, cx);
 574                                        }
 575                                    })
 576                                }
 577                            })
 578                            .ok();
 579                        }
 580                    });
 581                }
 582
 583                menu
 584            });
 585
 586            window.focus(&context_menu.focus_handle(cx));
 587            let subscription = cx.subscribe(&context_menu, |this, _, _: &DismissEvent, cx| {
 588                this.context_menu.take();
 589                cx.notify();
 590            });
 591            self.context_menu = Some((context_menu, position, subscription));
 592        }
 593    }
 594
 595    fn copy_debug_adapter_arguments(
 596        &mut self,
 597        _: &CopyDebugAdapterArguments,
 598        _window: &mut Window,
 599        cx: &mut Context<Self>,
 600    ) {
 601        let content = maybe!({
 602            let mut session = self.active_session()?.read(cx).session(cx);
 603            while let Some(parent) = session.read(cx).parent_session().cloned() {
 604                session = parent;
 605            }
 606            let binary = session.read(cx).binary()?;
 607            let content = serde_json::to_string_pretty(&binary).ok()?;
 608            Some(content)
 609        });
 610        if let Some(content) = content {
 611            cx.write_to_clipboard(ClipboardItem::new_string(content));
 612        }
 613    }
 614
 615    pub(crate) fn top_controls_strip(
 616        &mut self,
 617        window: &mut Window,
 618        cx: &mut Context<Self>,
 619    ) -> Option<Div> {
 620        let active_session = self.active_session.clone();
 621        let focus_handle = self.focus_handle.clone();
 622        let is_side = self.position(window, cx).axis() == gpui::Axis::Horizontal;
 623        let div = if is_side { v_flex() } else { h_flex() };
 624
 625        let new_session_button = || {
 626            IconButton::new("debug-new-session", IconName::Plus)
 627                .icon_size(IconSize::Small)
 628                .on_click({
 629                    move |_, window, cx| window.dispatch_action(crate::Start.boxed_clone(), cx)
 630                })
 631                .tooltip({
 632                    let focus_handle = focus_handle.clone();
 633                    move |window, cx| {
 634                        Tooltip::for_action_in(
 635                            "Start Debug Session",
 636                            &crate::Start,
 637                            &focus_handle,
 638                            window,
 639                            cx,
 640                        )
 641                    }
 642                })
 643        };
 644
 645        let documentation_button = || {
 646            IconButton::new("debug-open-documentation", IconName::CircleHelp)
 647                .icon_size(IconSize::Small)
 648                .on_click(move |_, _, cx| cx.open_url("https://zed.dev/docs/debugger"))
 649                .tooltip(Tooltip::text("Open Documentation"))
 650        };
 651
 652        let logs_button = || {
 653            IconButton::new("debug-open-logs", IconName::Notepad)
 654                .icon_size(IconSize::Small)
 655                .on_click(move |_, window, cx| {
 656                    window.dispatch_action(debugger_tools::OpenDebugAdapterLogs.boxed_clone(), cx)
 657                })
 658                .tooltip(Tooltip::text("Open Debug Adapter Logs"))
 659        };
 660
 661        Some(
 662            div.w_full()
 663                .py_1()
 664                .px_1p5()
 665                .justify_between()
 666                .border_b_1()
 667                .border_color(cx.theme().colors().border)
 668                .when(is_side, |this| this.gap_1())
 669                .child(
 670                    h_flex()
 671                        .justify_between()
 672                        .child(
 673                            h_flex().gap_1().w_full().when_some(
 674                                active_session
 675                                    .as_ref()
 676                                    .map(|session| session.read(cx).running_state()),
 677                                |this, running_state| {
 678                                    let thread_status =
 679                                        running_state.read(cx).thread_status(cx).unwrap_or(
 680                                            project::debugger::session::ThreadStatus::Exited,
 681                                        );
 682                                    let capabilities = running_state.read(cx).capabilities(cx);
 683                                    let supports_detach =
 684                                        running_state.read(cx).session().read(cx).is_attached();
 685
 686                                    this.map(|this| {
 687                                        if thread_status == ThreadStatus::Running {
 688                                            this.child(
 689                                                IconButton::new(
 690                                                    "debug-pause",
 691                                                    IconName::DebugPause,
 692                                                )
 693                                                .icon_size(IconSize::Small)
 694                                                .on_click(window.listener_for(
 695                                                    running_state,
 696                                                    |this, _, _window, cx| {
 697                                                        this.pause_thread(cx);
 698                                                    },
 699                                                ))
 700                                                .tooltip({
 701                                                    let focus_handle = focus_handle.clone();
 702                                                    move |window, cx| {
 703                                                        Tooltip::for_action_in(
 704                                                            "Pause Program",
 705                                                            &Pause,
 706                                                            &focus_handle,
 707                                                            window,
 708                                                            cx,
 709                                                        )
 710                                                    }
 711                                                }),
 712                                            )
 713                                        } else {
 714                                            this.child(
 715                                                IconButton::new(
 716                                                    "debug-continue",
 717                                                    IconName::DebugContinue,
 718                                                )
 719                                                .icon_size(IconSize::Small)
 720                                                .on_click(window.listener_for(
 721                                                    running_state,
 722                                                    |this, _, _window, cx| this.continue_thread(cx),
 723                                                ))
 724                                                .disabled(thread_status != ThreadStatus::Stopped)
 725                                                .tooltip({
 726                                                    let focus_handle = focus_handle.clone();
 727                                                    move |window, cx| {
 728                                                        Tooltip::for_action_in(
 729                                                            "Continue Program",
 730                                                            &Continue,
 731                                                            &focus_handle,
 732                                                            window,
 733                                                            cx,
 734                                                        )
 735                                                    }
 736                                                }),
 737                                            )
 738                                        }
 739                                    })
 740                                    .child(
 741                                        IconButton::new("debug-step-over", IconName::ArrowRight)
 742                                            .icon_size(IconSize::Small)
 743                                            .on_click(window.listener_for(
 744                                                running_state,
 745                                                |this, _, _window, cx| {
 746                                                    this.step_over(cx);
 747                                                },
 748                                            ))
 749                                            .disabled(thread_status != ThreadStatus::Stopped)
 750                                            .tooltip({
 751                                                let focus_handle = focus_handle.clone();
 752                                                move |window, cx| {
 753                                                    Tooltip::for_action_in(
 754                                                        "Step Over",
 755                                                        &StepOver,
 756                                                        &focus_handle,
 757                                                        window,
 758                                                        cx,
 759                                                    )
 760                                                }
 761                                            }),
 762                                    )
 763                                    .child(
 764                                        IconButton::new(
 765                                            "debug-step-into",
 766                                            IconName::ArrowDownRight,
 767                                        )
 768                                        .icon_size(IconSize::Small)
 769                                        .on_click(window.listener_for(
 770                                            running_state,
 771                                            |this, _, _window, cx| {
 772                                                this.step_in(cx);
 773                                            },
 774                                        ))
 775                                        .disabled(thread_status != ThreadStatus::Stopped)
 776                                        .tooltip({
 777                                            let focus_handle = focus_handle.clone();
 778                                            move |window, cx| {
 779                                                Tooltip::for_action_in(
 780                                                    "Step In",
 781                                                    &StepInto,
 782                                                    &focus_handle,
 783                                                    window,
 784                                                    cx,
 785                                                )
 786                                            }
 787                                        }),
 788                                    )
 789                                    .child(
 790                                        IconButton::new("debug-step-out", IconName::ArrowUpRight)
 791                                            .icon_size(IconSize::Small)
 792                                            .on_click(window.listener_for(
 793                                                running_state,
 794                                                |this, _, _window, cx| {
 795                                                    this.step_out(cx);
 796                                                },
 797                                            ))
 798                                            .disabled(thread_status != ThreadStatus::Stopped)
 799                                            .tooltip({
 800                                                let focus_handle = focus_handle.clone();
 801                                                move |window, cx| {
 802                                                    Tooltip::for_action_in(
 803                                                        "Step Out",
 804                                                        &StepOut,
 805                                                        &focus_handle,
 806                                                        window,
 807                                                        cx,
 808                                                    )
 809                                                }
 810                                            }),
 811                                    )
 812                                    .child(Divider::vertical())
 813                                    .child(
 814                                        IconButton::new("debug-restart", IconName::RotateCcw)
 815                                            .icon_size(IconSize::Small)
 816                                            .on_click(window.listener_for(
 817                                                running_state,
 818                                                |this, _, window, cx| {
 819                                                    this.rerun_session(window, cx);
 820                                                },
 821                                            ))
 822                                            .tooltip({
 823                                                let focus_handle = focus_handle.clone();
 824                                                move |window, cx| {
 825                                                    Tooltip::for_action_in(
 826                                                        "Rerun Session",
 827                                                        &RerunSession,
 828                                                        &focus_handle,
 829                                                        window,
 830                                                        cx,
 831                                                    )
 832                                                }
 833                                            }),
 834                                    )
 835                                    .child(
 836                                        IconButton::new("debug-stop", IconName::Power)
 837                                            .icon_size(IconSize::Small)
 838                                            .on_click(window.listener_for(
 839                                                running_state,
 840                                                |this, _, _window, cx| {
 841                                                    if this.session().read(cx).is_building() {
 842                                                        this.session().update(cx, |session, cx| {
 843                                                            session.shutdown(cx).detach()
 844                                                        });
 845                                                    } else {
 846                                                        this.stop_thread(cx);
 847                                                    }
 848                                                },
 849                                            ))
 850                                            .disabled(active_session.as_ref().is_none_or(
 851                                                |session| {
 852                                                    session
 853                                                        .read(cx)
 854                                                        .session(cx)
 855                                                        .read(cx)
 856                                                        .is_terminated()
 857                                                },
 858                                            ))
 859                                            .tooltip({
 860                                                let focus_handle = focus_handle.clone();
 861                                                let label = if capabilities
 862                                                    .supports_terminate_threads_request
 863                                                    .unwrap_or_default()
 864                                                {
 865                                                    "Terminate Thread"
 866                                                } else {
 867                                                    "Terminate All Threads"
 868                                                };
 869                                                move |window, cx| {
 870                                                    Tooltip::for_action_in(
 871                                                        label,
 872                                                        &Stop,
 873                                                        &focus_handle,
 874                                                        window,
 875                                                        cx,
 876                                                    )
 877                                                }
 878                                            }),
 879                                    )
 880                                    .when(
 881                                        supports_detach,
 882                                        |div| {
 883                                            div.child(
 884                                                IconButton::new(
 885                                                    "debug-disconnect",
 886                                                    IconName::DebugDetach,
 887                                                )
 888                                                .disabled(
 889                                                    thread_status != ThreadStatus::Stopped
 890                                                        && thread_status != ThreadStatus::Running,
 891                                                )
 892                                                .icon_size(IconSize::Small)
 893                                                .on_click(window.listener_for(
 894                                                    running_state,
 895                                                    |this, _, _, cx| {
 896                                                        this.detach_client(cx);
 897                                                    },
 898                                                ))
 899                                                .tooltip({
 900                                                    let focus_handle = focus_handle.clone();
 901                                                    move |window, cx| {
 902                                                        Tooltip::for_action_in(
 903                                                            "Detach",
 904                                                            &Detach,
 905                                                            &focus_handle,
 906                                                            window,
 907                                                            cx,
 908                                                        )
 909                                                    }
 910                                                }),
 911                                            )
 912                                        },
 913                                    )
 914                                },
 915                            ),
 916                        )
 917                        .when(is_side, |this| {
 918                            this.child(new_session_button())
 919                                .child(logs_button())
 920                                .child(documentation_button())
 921                        }),
 922                )
 923                .child(
 924                    h_flex()
 925                        .gap_0p5()
 926                        .when(is_side, |this| this.justify_between())
 927                        .child(
 928                            h_flex().when_some(
 929                                active_session
 930                                    .as_ref()
 931                                    .map(|session| session.read(cx).running_state())
 932                                    .cloned(),
 933                                |this, running_state| {
 934                                    this.children({
 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        {
1306            return Some(label.into());
1307        }
1308        None
1309    }
1310
1311    fn retain_sessions(&mut self, keep: impl Fn(&Entity<DebugSession>) -> bool) {
1312        self.sessions_with_children
1313            .retain(|session, _| keep(session));
1314        for children in self.sessions_with_children.values_mut() {
1315            children.retain(|child| {
1316                let Some(child) = child.upgrade() else {
1317                    return false;
1318                };
1319                keep(&child)
1320            });
1321        }
1322    }
1323}
1324
1325async fn register_session_inner(
1326    this: &WeakEntity<DebugPanel>,
1327    session: Entity<Session>,
1328    cx: &mut AsyncWindowContext,
1329) -> Result<Entity<DebugSession>> {
1330    let adapter_name = session.read_with(cx, |session, _| session.adapter())?;
1331    this.update_in(cx, |_, window, cx| {
1332        cx.subscribe_in(
1333            &session,
1334            window,
1335            move |this, session, event: &SessionStateEvent, window, cx| match event {
1336                SessionStateEvent::Restart => {
1337                    this.handle_restart_request(session.clone(), window, cx);
1338                }
1339                SessionStateEvent::SpawnChildSession { request } => {
1340                    this.handle_start_debugging_request(request, session.clone(), window, cx);
1341                }
1342                _ => {}
1343            },
1344        )
1345        .detach();
1346    })
1347    .ok();
1348    let serialized_layout = persistence::get_serialized_layout(adapter_name).await;
1349    let debug_session = this.update_in(cx, |this, window, cx| {
1350        let parent_session = this
1351            .sessions_with_children
1352            .keys()
1353            .find(|p| Some(p.read(cx).session_id(cx)) == session.read(cx).parent_id(cx))
1354            .cloned();
1355        this.retain_sessions(|session| {
1356            !session
1357                .read(cx)
1358                .running_state()
1359                .read(cx)
1360                .session()
1361                .read(cx)
1362                .is_terminated()
1363        });
1364
1365        let debug_session = DebugSession::running(
1366            this.project.clone(),
1367            this.workspace.clone(),
1368            parent_session
1369                .as_ref()
1370                .map(|p| p.read(cx).running_state().read(cx).debug_terminal.clone()),
1371            session,
1372            serialized_layout,
1373            this.position(window, cx).axis(),
1374            window,
1375            cx,
1376        );
1377
1378        // We might want to make this an event subscription and only notify when a new thread is selected
1379        // This is used to filter the command menu correctly
1380        cx.observe(
1381            &debug_session.read(cx).running_state().clone(),
1382            |_, _, cx| cx.notify(),
1383        )
1384        .detach();
1385        let insert_position = this
1386            .sessions_with_children
1387            .keys()
1388            .position(|session| Some(session) == parent_session.as_ref())
1389            .map(|position| position + 1)
1390            .unwrap_or(this.sessions_with_children.len());
1391        // Maintain topological sort order of sessions
1392        let (_, old) = this.sessions_with_children.insert_before(
1393            insert_position,
1394            debug_session.clone(),
1395            Default::default(),
1396        );
1397        debug_assert!(old.is_none());
1398        if let Some(parent_session) = parent_session {
1399            this.sessions_with_children
1400                .entry(parent_session)
1401                .and_modify(|children| children.push(debug_session.downgrade()));
1402        }
1403
1404        debug_session
1405    })?;
1406    Ok(debug_session)
1407}
1408
1409impl EventEmitter<PanelEvent> for DebugPanel {}
1410impl EventEmitter<DebugPanelEvent> for DebugPanel {}
1411
1412impl Focusable for DebugPanel {
1413    fn focus_handle(&self, _: &App) -> FocusHandle {
1414        self.focus_handle.clone()
1415    }
1416}
1417
1418impl Panel for DebugPanel {
1419    fn persistent_name() -> &'static str {
1420        "DebugPanel"
1421    }
1422
1423    fn position(&self, _window: &Window, cx: &App) -> DockPosition {
1424        match DebuggerSettings::get_global(cx).dock {
1425            DebugPanelDockPosition::Left => DockPosition::Left,
1426            DebugPanelDockPosition::Bottom => DockPosition::Bottom,
1427            DebugPanelDockPosition::Right => DockPosition::Right,
1428        }
1429    }
1430
1431    fn position_is_valid(&self, _: DockPosition) -> bool {
1432        true
1433    }
1434
1435    fn set_position(
1436        &mut self,
1437        position: DockPosition,
1438        window: &mut Window,
1439        cx: &mut Context<Self>,
1440    ) {
1441        if position.axis() != self.position(window, cx).axis() {
1442            self.sessions_with_children.keys().for_each(|session_item| {
1443                session_item.update(cx, |item, cx| {
1444                    item.running_state()
1445                        .update(cx, |state, _| state.invert_axies())
1446                })
1447            });
1448        }
1449
1450        settings::update_settings_file::<DebuggerSettings>(
1451            self.fs.clone(),
1452            cx,
1453            move |settings, _| {
1454                let dock = match position {
1455                    DockPosition::Left => DebugPanelDockPosition::Left,
1456                    DockPosition::Bottom => DebugPanelDockPosition::Bottom,
1457                    DockPosition::Right => DebugPanelDockPosition::Right,
1458                };
1459                settings.dock = dock;
1460            },
1461        );
1462    }
1463
1464    fn size(&self, _window: &Window, _: &App) -> Pixels {
1465        self.size
1466    }
1467
1468    fn set_size(&mut self, size: Option<Pixels>, _window: &mut Window, _cx: &mut Context<Self>) {
1469        self.size = size.unwrap_or(px(300.));
1470    }
1471
1472    fn remote_id() -> Option<proto::PanelId> {
1473        Some(proto::PanelId::DebugPanel)
1474    }
1475
1476    fn icon(&self, _window: &Window, _cx: &App) -> Option<IconName> {
1477        Some(IconName::Debug)
1478    }
1479
1480    fn icon_tooltip(&self, _window: &Window, cx: &App) -> Option<&'static str> {
1481        if DebuggerSettings::get_global(cx).button {
1482            Some("Debug Panel")
1483        } else {
1484            None
1485        }
1486    }
1487
1488    fn toggle_action(&self) -> Box<dyn Action> {
1489        Box::new(ToggleFocus)
1490    }
1491
1492    fn pane(&self) -> Option<Entity<Pane>> {
1493        None
1494    }
1495
1496    fn activation_priority(&self) -> u32 {
1497        9
1498    }
1499
1500    fn set_active(&mut self, _: bool, _: &mut Window, _: &mut Context<Self>) {}
1501
1502    fn is_zoomed(&self, _window: &Window, _cx: &App) -> bool {
1503        self.is_zoomed
1504    }
1505
1506    fn set_zoomed(&mut self, zoomed: bool, _window: &mut Window, cx: &mut Context<Self>) {
1507        self.is_zoomed = zoomed;
1508        cx.notify();
1509    }
1510}
1511
1512impl Render for DebugPanel {
1513    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1514        let this = cx.weak_entity();
1515
1516        if self
1517            .active_session
1518            .as_ref()
1519            .map(|session| session.read(cx).running_state())
1520            .map(|state| state.read(cx).has_open_context_menu(cx))
1521            .unwrap_or(false)
1522        {
1523            self.context_menu.take();
1524        }
1525
1526        v_flex()
1527            .when(!self.is_zoomed, |this| {
1528                this.when_else(
1529                    self.position(window, cx) == DockPosition::Bottom,
1530                    |this| this.max_h(self.size),
1531                    |this| this.max_w(self.size),
1532                )
1533            })
1534            .size_full()
1535            .key_context("DebugPanel")
1536            .child(h_flex().children(self.top_controls_strip(window, cx)))
1537            .track_focus(&self.focus_handle(cx))
1538            .on_action({
1539                let this = this.clone();
1540                move |_: &workspace::ActivatePaneLeft, window, cx| {
1541                    this.update(cx, |this, cx| {
1542                        this.activate_pane_in_direction(SplitDirection::Left, window, cx);
1543                    })
1544                    .ok();
1545                }
1546            })
1547            .on_action({
1548                let this = this.clone();
1549                move |_: &workspace::ActivatePaneRight, window, cx| {
1550                    this.update(cx, |this, cx| {
1551                        this.activate_pane_in_direction(SplitDirection::Right, window, cx);
1552                    })
1553                    .ok();
1554                }
1555            })
1556            .on_action({
1557                let this = this.clone();
1558                move |_: &workspace::ActivatePaneUp, window, cx| {
1559                    this.update(cx, |this, cx| {
1560                        this.activate_pane_in_direction(SplitDirection::Up, window, cx);
1561                    })
1562                    .ok();
1563                }
1564            })
1565            .on_action({
1566                let this = this.clone();
1567                move |_: &workspace::ActivatePaneDown, window, cx| {
1568                    this.update(cx, |this, cx| {
1569                        this.activate_pane_in_direction(SplitDirection::Down, window, cx);
1570                    })
1571                    .ok();
1572                }
1573            })
1574            .on_action({
1575                let this = this.clone();
1576                move |_: &FocusConsole, window, cx| {
1577                    this.update(cx, |this, cx| {
1578                        this.activate_item(DebuggerPaneItem::Console, window, cx);
1579                    })
1580                    .ok();
1581                }
1582            })
1583            .on_action({
1584                let this = this.clone();
1585                move |_: &FocusVariables, window, cx| {
1586                    this.update(cx, |this, cx| {
1587                        this.activate_item(DebuggerPaneItem::Variables, window, cx);
1588                    })
1589                    .ok();
1590                }
1591            })
1592            .on_action({
1593                let this = this.clone();
1594                move |_: &FocusBreakpointList, window, cx| {
1595                    this.update(cx, |this, cx| {
1596                        this.activate_item(DebuggerPaneItem::BreakpointList, window, cx);
1597                    })
1598                    .ok();
1599                }
1600            })
1601            .on_action({
1602                let this = this.clone();
1603                move |_: &FocusFrames, window, cx| {
1604                    this.update(cx, |this, cx| {
1605                        this.activate_item(DebuggerPaneItem::Frames, window, cx);
1606                    })
1607                    .ok();
1608                }
1609            })
1610            .on_action({
1611                let this = this.clone();
1612                move |_: &FocusModules, window, cx| {
1613                    this.update(cx, |this, cx| {
1614                        this.activate_item(DebuggerPaneItem::Modules, window, cx);
1615                    })
1616                    .ok();
1617                }
1618            })
1619            .on_action({
1620                let this = this.clone();
1621                move |_: &FocusLoadedSources, window, cx| {
1622                    this.update(cx, |this, cx| {
1623                        this.activate_item(DebuggerPaneItem::LoadedSources, window, cx);
1624                    })
1625                    .ok();
1626                }
1627            })
1628            .on_action({
1629                let this = this.clone();
1630                move |_: &FocusTerminal, window, cx| {
1631                    this.update(cx, |this, cx| {
1632                        this.activate_item(DebuggerPaneItem::Terminal, window, cx);
1633                    })
1634                    .ok();
1635                }
1636            })
1637            .on_action({
1638                let this = this.clone();
1639                move |_: &ToggleThreadPicker, window, cx| {
1640                    this.update(cx, |this, cx| {
1641                        this.toggle_thread_picker(window, cx);
1642                    })
1643                    .ok();
1644                }
1645            })
1646            .on_action({
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}