1use std::{
2 any::{Any, TypeId, type_name},
3 collections::VecDeque,
4 fmt,
5 marker::PhantomData,
6 sync::{
7 Arc, Mutex, RwLock,
8 atomic::{AtomicBool, AtomicU64, Ordering},
9 },
10};
11
12use sui_core::{
13 InvalidationKind, InvalidationRequest, InvalidationTarget, Rect, WidgetId, WindowId,
14};
15
16static NEXT_COMMAND_SEQUENCE: AtomicU64 = AtomicU64::new(1);
17
18pub struct CommandKey<T: 'static> {
23 name: &'static str,
24 marker: PhantomData<fn() -> T>,
25}
26
27impl<T: 'static> CommandKey<T> {
28 pub const fn new(name: &'static str) -> Self {
29 Self {
30 name,
31 marker: PhantomData,
32 }
33 }
34
35 pub const fn name(self) -> &'static str {
36 self.name
37 }
38
39 fn erased(self) -> ErasedCommandKey {
40 ErasedCommandKey {
41 name: self.name,
42 payload_type: TypeId::of::<T>(),
43 payload_type_name: type_name::<T>(),
44 }
45 }
46}
47
48impl<T: 'static> Clone for CommandKey<T> {
49 fn clone(&self) -> Self {
50 *self
51 }
52}
53
54impl<T: 'static> Copy for CommandKey<T> {}
55
56impl<T: 'static> fmt::Debug for CommandKey<T> {
57 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
58 formatter
59 .debug_struct("CommandKey")
60 .field("name", &self.name)
61 .field("payload", &type_name::<T>())
62 .finish()
63 }
64}
65
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
67pub enum CommandTarget {
68 Widget {
69 window_id: WindowId,
70 widget_id: WidgetId,
71 },
72 FocusedWidget(WindowId),
73 Window(WindowId),
74 Application,
75}
76
77impl CommandTarget {
78 pub const fn window_id(self) -> Option<WindowId> {
79 match self {
80 Self::Widget { window_id, .. }
81 | Self::FocusedWidget(window_id)
82 | Self::Window(window_id) => Some(window_id),
83 Self::Application => None,
84 }
85 }
86}
87
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
89pub enum CommandDelivery {
90 Directed,
91 Broadcast,
92}
93
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95pub(crate) struct ErasedCommandKey {
96 pub(crate) name: &'static str,
97 pub(crate) payload_type: TypeId,
98 pub(crate) payload_type_name: &'static str,
99}
100
101#[derive(Clone)]
102pub(crate) struct QueuedCommand {
103 pub(crate) sequence: u64,
104 pub(crate) key: ErasedCommandKey,
105 pub(crate) target: CommandTarget,
106 pub(crate) delivery: CommandDelivery,
107 pub(crate) payload: Arc<dyn Any + Send + Sync>,
108}
109
110impl fmt::Debug for QueuedCommand {
111 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
112 formatter
113 .debug_struct("QueuedCommand")
114 .field("sequence", &self.sequence)
115 .field("name", &self.key.name)
116 .field("payload_type", &self.key.payload_type_name)
117 .field("target", &self.target)
118 .field("delivery", &self.delivery)
119 .finish_non_exhaustive()
120 }
121}
122
123pub struct Command<'a> {
125 inner: &'a QueuedCommand,
126}
127
128impl<'a> Command<'a> {
129 pub(crate) const fn new(inner: &'a QueuedCommand) -> Self {
130 Self { inner }
131 }
132
133 pub const fn sequence(&self) -> u64 {
134 self.inner.sequence
135 }
136
137 pub const fn name(&self) -> &'static str {
138 self.inner.key.name
139 }
140
141 pub const fn payload_type_name(&self) -> &'static str {
142 self.inner.key.payload_type_name
143 }
144
145 pub const fn target(&self) -> CommandTarget {
146 self.inner.target
147 }
148
149 pub const fn delivery(&self) -> CommandDelivery {
150 self.inner.delivery
151 }
152
153 pub fn is<T: 'static>(&self, key: CommandKey<T>) -> bool {
154 self.inner.key == key.erased()
155 }
156
157 pub fn get<T: Send + Sync + 'static>(&self, key: CommandKey<T>) -> Option<&T> {
158 self.is(key)
159 .then(|| self.inner.payload.downcast_ref::<T>())
160 .flatten()
161 }
162}
163
164impl fmt::Debug for Command<'_> {
165 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
166 self.inner.fmt(formatter)
167 }
168}
169
170type ExternalWaker = dyn Fn() + Send + Sync + 'static;
171
172struct CommandHub {
173 state: Mutex<CommandHubState>,
174 wake_pending: AtomicBool,
175 exit_requested: AtomicBool,
176 waker: RwLock<Option<Arc<ExternalWaker>>>,
177}
178
179#[derive(Default)]
180struct CommandHubState {
181 pending: VecDeque<QueuedCommand>,
182 manual_wake_pending: bool,
183}
184
185impl CommandHub {
186 fn new() -> Arc<Self> {
187 Arc::new(Self {
188 state: Mutex::new(CommandHubState::default()),
189 wake_pending: AtomicBool::new(false),
190 exit_requested: AtomicBool::new(false),
191 waker: RwLock::new(None),
192 })
193 }
194
195 fn set_waker(&self, waker: Option<Arc<ExternalWaker>>) {
196 let wake = waker.clone();
197 *self
198 .waker
199 .write()
200 .unwrap_or_else(std::sync::PoisonError::into_inner) = waker;
201 if self.has_pending()
205 && let Some(wake) = wake
206 {
207 wake();
208 }
209 }
210
211 fn enqueue(&self, command: QueuedCommand) {
212 self.state
213 .lock()
214 .unwrap_or_else(std::sync::PoisonError::into_inner)
215 .pending
216 .push_back(command);
217 self.request_wake();
218 }
219
220 fn wake(&self) {
221 self.state
222 .lock()
223 .unwrap_or_else(std::sync::PoisonError::into_inner)
224 .manual_wake_pending = true;
225 self.request_wake();
226 }
227
228 fn request_wake(&self) {
229 if self.wake_pending.swap(true, Ordering::AcqRel) {
230 return;
231 }
232 if let Some(waker) = self
233 .waker
234 .read()
235 .unwrap_or_else(std::sync::PoisonError::into_inner)
236 .clone()
237 {
238 waker();
239 }
240 }
241
242 fn drain(&self) -> (bool, Vec<QueuedCommand>) {
243 let (manual_wake, commands) = {
244 let mut state = self
245 .state
246 .lock()
247 .unwrap_or_else(std::sync::PoisonError::into_inner);
248 let commands = state.pending.drain(..).collect();
249 let manual_wake = std::mem::take(&mut state.manual_wake_pending);
250 self.wake_pending.store(false, Ordering::Release);
253 (manual_wake, commands)
254 };
255 (manual_wake, commands)
256 }
257
258 fn has_pending(&self) -> bool {
259 let state = self
260 .state
261 .lock()
262 .unwrap_or_else(std::sync::PoisonError::into_inner);
263 state.manual_wake_pending || !state.pending.is_empty()
264 }
265}
266
267#[derive(Clone)]
275pub struct CommandSender {
276 hub: Arc<CommandHub>,
277}
278
279impl CommandSender {
280 pub(crate) fn new() -> Self {
281 Self {
282 hub: CommandHub::new(),
283 }
284 }
285
286 pub fn wake(&self) {
287 self.hub.wake();
288 }
289
290 pub fn request_exit(&self) {
295 self.hub.exit_requested.store(true, Ordering::Release);
296 self.hub.wake();
297 }
298
299 pub fn exit_requested(&self) -> bool {
301 self.hub.exit_requested.load(Ordering::Acquire)
302 }
303
304 pub fn send<T>(&self, target: CommandTarget, key: CommandKey<T>, payload: T) -> u64
305 where
306 T: Send + Sync + 'static,
307 {
308 self.enqueue(target, CommandDelivery::Directed, key, payload)
309 }
310
311 pub fn broadcast<T>(&self, target: CommandTarget, key: CommandKey<T>, payload: T) -> u64
312 where
313 T: Send + Sync + 'static,
314 {
315 self.enqueue(target, CommandDelivery::Broadcast, key, payload)
316 }
317
318 pub fn send_widget<T>(
319 &self,
320 window_id: WindowId,
321 widget_id: WidgetId,
322 key: CommandKey<T>,
323 payload: T,
324 ) -> u64
325 where
326 T: Send + Sync + 'static,
327 {
328 self.send(
329 CommandTarget::Widget {
330 window_id,
331 widget_id,
332 },
333 key,
334 payload,
335 )
336 }
337
338 pub fn send_focused<T>(&self, window_id: WindowId, key: CommandKey<T>, payload: T) -> u64
339 where
340 T: Send + Sync + 'static,
341 {
342 self.send(CommandTarget::FocusedWidget(window_id), key, payload)
343 }
344
345 pub fn send_window<T>(&self, window_id: WindowId, key: CommandKey<T>, payload: T) -> u64
346 where
347 T: Send + Sync + 'static,
348 {
349 self.send(CommandTarget::Window(window_id), key, payload)
350 }
351
352 pub fn send_application<T>(&self, key: CommandKey<T>, payload: T) -> u64
353 where
354 T: Send + Sync + 'static,
355 {
356 self.send(CommandTarget::Application, key, payload)
357 }
358
359 pub fn broadcast_window<T>(&self, window_id: WindowId, key: CommandKey<T>, payload: T) -> u64
360 where
361 T: Send + Sync + 'static,
362 {
363 self.broadcast(CommandTarget::Window(window_id), key, payload)
364 }
365
366 pub fn broadcast_application<T>(&self, key: CommandKey<T>, payload: T) -> u64
367 where
368 T: Send + Sync + 'static,
369 {
370 self.broadcast(CommandTarget::Application, key, payload)
371 }
372
373 fn enqueue<T>(
374 &self,
375 target: CommandTarget,
376 delivery: CommandDelivery,
377 key: CommandKey<T>,
378 payload: T,
379 ) -> u64
380 where
381 T: Send + Sync + 'static,
382 {
383 let command = queued_command(target, delivery, key, payload);
384 let sequence = command.sequence;
385 self.hub.enqueue(command);
386 sequence
387 }
388
389 pub(crate) fn set_waker(&self, waker: Option<Arc<ExternalWaker>>) {
390 self.hub.set_waker(waker);
391 }
392
393 pub(crate) fn drain(&self) -> (bool, Vec<QueuedCommand>) {
394 self.hub.drain()
395 }
396
397 pub(crate) fn has_pending(&self) -> bool {
398 self.hub.has_pending()
399 }
400}
401
402impl fmt::Debug for CommandSender {
403 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
404 formatter
405 .debug_struct("CommandSender")
406 .field("has_pending", &self.has_pending())
407 .finish_non_exhaustive()
408 }
409}
410
411pub(crate) fn queued_command<T>(
412 target: CommandTarget,
413 delivery: CommandDelivery,
414 key: CommandKey<T>,
415 payload: T,
416) -> QueuedCommand
417where
418 T: Send + Sync + 'static,
419{
420 QueuedCommand {
421 sequence: NEXT_COMMAND_SEQUENCE.fetch_add(1, Ordering::Relaxed),
422 key: key.erased(),
423 target,
424 delivery,
425 payload: Arc::new(payload),
426 }
427}
428
429#[derive(Debug, Clone)]
430pub(crate) struct CommandInvalidation {
431 pub(crate) request: InvalidationRequest,
432 pub(crate) reason: Option<String>,
433}
434
435pub(crate) struct EveryWindowInvalidation {
438 pub(crate) kind: InvalidationKind,
439 pub(crate) region: Option<Rect>,
440 pub(crate) reason: Option<String>,
441}
442
443pub struct CommandCtx {
445 sender: CommandSender,
446 window_id: Option<WindowId>,
447 handled: bool,
448 invalidations: Vec<CommandInvalidation>,
449 every_window_invalidations: Vec<EveryWindowInvalidation>,
450 animation_targets: Vec<(Option<WindowId>, WidgetId)>,
453}
454
455impl CommandCtx {
456 pub(crate) fn new(sender: CommandSender, window_id: Option<WindowId>) -> Self {
457 Self {
458 sender,
459 window_id,
460 handled: false,
461 invalidations: Vec::new(),
462 every_window_invalidations: Vec::new(),
463 animation_targets: Vec::new(),
464 }
465 }
466
467 pub const fn window_id(&self) -> Option<WindowId> {
468 self.window_id
469 }
470
471 pub const fn is_handled(&self) -> bool {
472 self.handled
473 }
474
475 pub fn set_handled(&mut self) {
476 self.handled = true;
477 }
478
479 pub fn sender(&self) -> &CommandSender {
480 &self.sender
481 }
482
483 pub fn request(&mut self, request: InvalidationRequest) {
484 self.invalidations.push(CommandInvalidation {
485 request,
486 reason: None,
487 });
488 }
489
490 pub fn request_with_reason(&mut self, request: InvalidationRequest, reason: impl Into<String>) {
491 self.invalidations.push(CommandInvalidation {
492 request,
493 reason: Some(reason.into()),
494 });
495 }
496
497 pub fn request_window(&mut self, kind: InvalidationKind) {
500 self.request_window_region(kind, None, None);
501 }
502
503 pub fn request_window_with_reason(
505 &mut self,
506 kind: InvalidationKind,
507 reason: impl Into<String>,
508 ) {
509 self.request_window_region(kind, None, Some(reason.into()));
510 }
511
512 fn request_window_region(
513 &mut self,
514 kind: InvalidationKind,
515 region: Option<Rect>,
516 reason: Option<String>,
517 ) {
518 let Some(window_id) = self.window_id else {
519 self.every_window_invalidations
520 .push(EveryWindowInvalidation {
521 kind,
522 region,
523 reason,
524 });
525 return;
526 };
527 let mut request = InvalidationRequest::new(InvalidationTarget::Window(window_id), kind);
528 if let Some(region) = region {
529 request = request.with_region(region);
530 }
531 self.invalidations
532 .push(CommandInvalidation { request, reason });
533 }
534
535 pub fn request_measure(&mut self) {
536 self.request_window(InvalidationKind::Measure);
537 }
538
539 pub fn request_arrange(&mut self) {
540 self.request_window(InvalidationKind::Arrange);
541 }
542
543 pub fn request_paint(&mut self) {
544 self.request_window(InvalidationKind::Paint);
545 }
546
547 pub fn request_semantics(&mut self) {
548 self.request_window(InvalidationKind::Semantics);
549 }
550
551 pub fn request_paint_rect(&mut self, rect: Rect) {
554 self.request_window_region(InvalidationKind::Paint, Some(rect), None);
555 }
556
557 pub fn request_animation_frame(&mut self, widget_id: WidgetId) {
560 self.animation_targets.push((self.window_id, widget_id));
561 }
562
563 pub(crate) fn take_invalidations(&mut self) -> Vec<CommandInvalidation> {
564 std::mem::take(&mut self.invalidations)
565 }
566
567 pub(crate) fn take_every_window_invalidations(&mut self) -> Vec<EveryWindowInvalidation> {
568 std::mem::take(&mut self.every_window_invalidations)
569 }
570
571 pub(crate) fn take_animation_targets(&mut self) -> Vec<(Option<WindowId>, WidgetId)> {
572 std::mem::take(&mut self.animation_targets)
573 }
574}
575
576pub trait CommandController {
580 fn command(&mut self, _ctx: &mut CommandCtx, _command: &Command<'_>) {}
581
582 fn wake(&mut self, _ctx: &mut CommandCtx) {}
584
585 fn debug_name(&self) -> &'static str {
586 type_name::<Self>()
587 }
588}
589
590type ErasedCommandCallback = dyn FnMut(&mut CommandCtx, &dyn Any);
591
592pub(crate) struct CommandSubscription {
593 key: ErasedCommandKey,
594 handler_name: &'static str,
595 callback: Box<ErasedCommandCallback>,
596}
597
598impl CommandSubscription {
599 pub(crate) fn new<T, F>(key: CommandKey<T>, mut callback: F) -> Self
600 where
601 T: Send + Sync + 'static,
602 F: FnMut(&mut CommandCtx, &T) + 'static,
603 {
604 Self {
605 key: key.erased(),
606 handler_name: type_name::<F>(),
607 callback: Box::new(move |ctx, payload| {
608 if let Some(payload) = payload.downcast_ref::<T>() {
609 callback(ctx, payload);
610 }
611 }),
612 }
613 }
614}
615
616pub(crate) enum CommandListener {
617 Controller(Box<dyn CommandController>),
618 Subscription(CommandSubscription),
619}
620
621#[derive(Default)]
622pub(crate) struct CommandListeners {
623 listeners: Vec<CommandListener>,
624}
625
626impl CommandListeners {
627 pub(crate) fn push_controller(&mut self, controller: impl CommandController + 'static) {
628 self.listeners
629 .push(CommandListener::Controller(Box::new(controller)));
630 }
631
632 pub(crate) fn push_subscription<T, F>(&mut self, key: CommandKey<T>, callback: F)
633 where
634 T: Send + Sync + 'static,
635 F: FnMut(&mut CommandCtx, &T) + 'static,
636 {
637 self.listeners
638 .push(CommandListener::Subscription(CommandSubscription::new(
639 key, callback,
640 )));
641 }
642
643 pub(crate) fn dispatch(
644 &mut self,
645 ctx: &mut CommandCtx,
646 command: &Command<'_>,
647 broadcast: bool,
648 ) -> Vec<String> {
649 let mut invoked = Vec::new();
650 for listener in &mut self.listeners {
651 match listener {
652 CommandListener::Controller(controller) => {
653 invoked.push(controller.debug_name().to_string());
654 controller.command(ctx, command);
655 }
656 CommandListener::Subscription(subscription)
657 if subscription.key == command.inner.key =>
658 {
659 invoked.push(subscription.handler_name.to_string());
660 (subscription.callback)(ctx, command.inner.payload.as_ref());
661 }
662 CommandListener::Subscription(_) => continue,
663 }
664 if ctx.is_handled() && !broadcast {
665 break;
666 }
667 }
668 invoked
669 }
670
671 pub(crate) fn wake(&mut self, ctx: &mut CommandCtx) -> Vec<String> {
672 let mut invoked = Vec::new();
673 for listener in &mut self.listeners {
674 if let CommandListener::Controller(controller) = listener {
675 invoked.push(controller.debug_name().to_string());
676 controller.wake(ctx);
677 }
678 }
679 invoked
680 }
681}
682
683#[cfg(test)]
684mod tests {
685 use super::*;
686
687 static COUNT: CommandKey<u32> = CommandKey::new("test.count");
688
689 #[test]
690 fn typed_keys_reject_a_same_name_different_payload() {
691 static STRING_COUNT: CommandKey<String> = CommandKey::new("test.count");
692 let queued = queued_command(
693 CommandTarget::Application,
694 CommandDelivery::Directed,
695 COUNT,
696 7,
697 );
698 let command = Command::new(&queued);
699 assert_eq!(command.get(COUNT), Some(&7));
700 assert!(command.get(STRING_COUNT).is_none());
701 }
702
703 #[test]
704 fn command_sender_coalesces_scheduler_wakes_but_keeps_payloads() {
705 let sender = CommandSender::new();
706 let wake_count = Arc::new(AtomicU64::new(0));
707 let wake_count_for_callback = Arc::clone(&wake_count);
708 sender.set_waker(Some(Arc::new(move || {
709 wake_count_for_callback.fetch_add(1, Ordering::Relaxed);
710 })));
711
712 sender.send_application(COUNT, 1);
713 sender.send_application(COUNT, 2);
714 assert_eq!(wake_count.load(Ordering::Relaxed), 1);
715 let (_, commands) = sender.drain();
716 assert_eq!(commands.len(), 2);
717 }
718
719 #[test]
720 fn installing_a_waker_notifies_previously_queued_work() {
721 let sender = CommandSender::new();
722 sender.send_application(COUNT, 1);
723 let wake_count = Arc::new(AtomicU64::new(0));
724 let wake_count_for_callback = Arc::clone(&wake_count);
725
726 sender.set_waker(Some(Arc::new(move || {
727 wake_count_for_callback.fetch_add(1, Ordering::Relaxed);
728 })));
729
730 assert_eq!(wake_count.load(Ordering::Relaxed), 1);
731 }
732
733 #[test]
734 fn exit_requests_are_sticky_and_wake_the_platform() {
735 let sender = CommandSender::new();
736 let wake_count = Arc::new(AtomicU64::new(0));
737 let wake_count_for_callback = Arc::clone(&wake_count);
738 sender.set_waker(Some(Arc::new(move || {
739 wake_count_for_callback.fetch_add(1, Ordering::Relaxed);
740 })));
741 assert!(!sender.exit_requested());
742
743 sender.clone().request_exit();
744 let _ = sender.drain();
745
746 assert!(sender.exit_requested());
747 assert_eq!(wake_count.load(Ordering::Relaxed), 1);
748 }
749}