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