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