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