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