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