debugger_panel.rs

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