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