Skip to main content

sui_runtime/
command.rs

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
18/// A process-local, strongly typed command identifier.
19///
20/// The stable name is retained for diagnostics and foreign-language adapters;
21/// Rust delivery additionally verifies the payload's [`TypeId`].
22pub 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
123/// Borrowed view of a command while it is delivered on the UI thread.
124pub 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    waker: RwLock<Option<Arc<ExternalWaker>>>,
176}
177
178#[derive(Default)]
179struct CommandHubState {
180    pending: VecDeque<QueuedCommand>,
181    manual_wake_pending: bool,
182}
183
184impl CommandHub {
185    fn new() -> Arc<Self> {
186        Arc::new(Self {
187            state: Mutex::new(CommandHubState::default()),
188            wake_pending: AtomicBool::new(false),
189            waker: RwLock::new(None),
190        })
191    }
192
193    fn set_waker(&self, waker: Option<Arc<ExternalWaker>>) {
194        let wake = waker.clone();
195        *self
196            .waker
197            .write()
198            .unwrap_or_else(std::sync::PoisonError::into_inner) = waker;
199        // A producer may enqueue before a platform installs its callback. In
200        // that case `wake_pending` is already true, so invoke the newly
201        // installed callback directly instead of waiting for another command.
202        if self.has_pending()
203            && let Some(wake) = wake
204        {
205            wake();
206        }
207    }
208
209    fn enqueue(&self, command: QueuedCommand) {
210        self.state
211            .lock()
212            .unwrap_or_else(std::sync::PoisonError::into_inner)
213            .pending
214            .push_back(command);
215        self.request_wake();
216    }
217
218    fn wake(&self) {
219        self.state
220            .lock()
221            .unwrap_or_else(std::sync::PoisonError::into_inner)
222            .manual_wake_pending = true;
223        self.request_wake();
224    }
225
226    fn request_wake(&self) {
227        if self.wake_pending.swap(true, Ordering::AcqRel) {
228            return;
229        }
230        if let Some(waker) = self
231            .waker
232            .read()
233            .unwrap_or_else(std::sync::PoisonError::into_inner)
234            .clone()
235        {
236            waker();
237        }
238    }
239
240    fn drain(&self) -> (bool, Vec<QueuedCommand>) {
241        let (manual_wake, commands) = {
242            let mut state = self
243                .state
244                .lock()
245                .unwrap_or_else(std::sync::PoisonError::into_inner);
246            let commands = state.pending.drain(..).collect();
247            let manual_wake = std::mem::take(&mut state.manual_wake_pending);
248            // Clear while holding the same lock producers use. A producer that
249            // arrives after this point observes false and emits a fresh wake.
250            self.wake_pending.store(false, Ordering::Release);
251            (manual_wake, commands)
252        };
253        (manual_wake, commands)
254    }
255
256    fn has_pending(&self) -> bool {
257        let state = self
258            .state
259            .lock()
260            .unwrap_or_else(std::sync::PoisonError::into_inner);
261        state.manual_wake_pending || !state.pending.is_empty()
262    }
263}
264
265/// Cloneable, thread-safe producer for application commands.
266///
267/// Enqueueing a command wakes the platform loop. [`wake`](Self::wake) only
268/// schedules the runtime; it never synthesizes a widget event.
269///
270/// Each send returns the command's sequence number, which its handlers see as
271/// [`Command::sequence`] and dispatch diagnostics record.
272#[derive(Clone)]
273pub struct CommandSender {
274    hub: Arc<CommandHub>,
275}
276
277impl CommandSender {
278    pub(crate) fn new() -> Self {
279        Self {
280            hub: CommandHub::new(),
281        }
282    }
283
284    pub fn wake(&self) {
285        self.hub.wake();
286    }
287
288    pub fn send<T>(&self, target: CommandTarget, key: CommandKey<T>, payload: T) -> u64
289    where
290        T: Send + Sync + 'static,
291    {
292        self.enqueue(target, CommandDelivery::Directed, key, payload)
293    }
294
295    pub fn broadcast<T>(&self, target: CommandTarget, key: CommandKey<T>, payload: T) -> u64
296    where
297        T: Send + Sync + 'static,
298    {
299        self.enqueue(target, CommandDelivery::Broadcast, key, payload)
300    }
301
302    pub fn send_widget<T>(
303        &self,
304        window_id: WindowId,
305        widget_id: WidgetId,
306        key: CommandKey<T>,
307        payload: T,
308    ) -> u64
309    where
310        T: Send + Sync + 'static,
311    {
312        self.send(
313            CommandTarget::Widget {
314                window_id,
315                widget_id,
316            },
317            key,
318            payload,
319        )
320    }
321
322    pub fn send_focused<T>(&self, window_id: WindowId, key: CommandKey<T>, payload: T) -> u64
323    where
324        T: Send + Sync + 'static,
325    {
326        self.send(CommandTarget::FocusedWidget(window_id), key, payload)
327    }
328
329    pub fn send_window<T>(&self, window_id: WindowId, key: CommandKey<T>, payload: T) -> u64
330    where
331        T: Send + Sync + 'static,
332    {
333        self.send(CommandTarget::Window(window_id), key, payload)
334    }
335
336    pub fn send_application<T>(&self, key: CommandKey<T>, payload: T) -> u64
337    where
338        T: Send + Sync + 'static,
339    {
340        self.send(CommandTarget::Application, key, payload)
341    }
342
343    pub fn broadcast_window<T>(&self, window_id: WindowId, key: CommandKey<T>, payload: T) -> u64
344    where
345        T: Send + Sync + 'static,
346    {
347        self.broadcast(CommandTarget::Window(window_id), key, payload)
348    }
349
350    pub fn broadcast_application<T>(&self, key: CommandKey<T>, payload: T) -> u64
351    where
352        T: Send + Sync + 'static,
353    {
354        self.broadcast(CommandTarget::Application, key, payload)
355    }
356
357    fn enqueue<T>(
358        &self,
359        target: CommandTarget,
360        delivery: CommandDelivery,
361        key: CommandKey<T>,
362        payload: T,
363    ) -> u64
364    where
365        T: Send + Sync + 'static,
366    {
367        let command = queued_command(target, delivery, key, payload);
368        let sequence = command.sequence;
369        self.hub.enqueue(command);
370        sequence
371    }
372
373    pub(crate) fn set_waker(&self, waker: Option<Arc<ExternalWaker>>) {
374        self.hub.set_waker(waker);
375    }
376
377    pub(crate) fn drain(&self) -> (bool, Vec<QueuedCommand>) {
378        self.hub.drain()
379    }
380
381    pub(crate) fn has_pending(&self) -> bool {
382        self.hub.has_pending()
383    }
384}
385
386impl fmt::Debug for CommandSender {
387    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
388        formatter
389            .debug_struct("CommandSender")
390            .field("has_pending", &self.has_pending())
391            .finish_non_exhaustive()
392    }
393}
394
395pub(crate) fn queued_command<T>(
396    target: CommandTarget,
397    delivery: CommandDelivery,
398    key: CommandKey<T>,
399    payload: T,
400) -> QueuedCommand
401where
402    T: Send + Sync + 'static,
403{
404    QueuedCommand {
405        sequence: NEXT_COMMAND_SEQUENCE.fetch_add(1, Ordering::Relaxed),
406        key: key.erased(),
407        target,
408        delivery,
409        payload: Arc::new(payload),
410    }
411}
412
413#[derive(Debug, Clone)]
414pub(crate) struct CommandInvalidation {
415    pub(crate) request: InvalidationRequest,
416    pub(crate) reason: Option<String>,
417}
418
419/// A window invalidation an application controller asked for. It has no
420/// window of its own, so every window gets it.
421pub(crate) struct EveryWindowInvalidation {
422    pub(crate) kind: InvalidationKind,
423    pub(crate) region: Option<Rect>,
424    pub(crate) reason: Option<String>,
425}
426
427/// Context supplied to window and application command controllers.
428pub struct CommandCtx {
429    sender: CommandSender,
430    window_id: Option<WindowId>,
431    handled: bool,
432    invalidations: Vec<CommandInvalidation>,
433    every_window_invalidations: Vec<EveryWindowInvalidation>,
434    /// Widgets asking for animation frames, with their window when the
435    /// controller has one.
436    animation_targets: Vec<(Option<WindowId>, WidgetId)>,
437}
438
439impl CommandCtx {
440    pub(crate) fn new(sender: CommandSender, window_id: Option<WindowId>) -> Self {
441        Self {
442            sender,
443            window_id,
444            handled: false,
445            invalidations: Vec::new(),
446            every_window_invalidations: Vec::new(),
447            animation_targets: Vec::new(),
448        }
449    }
450
451    pub const fn window_id(&self) -> Option<WindowId> {
452        self.window_id
453    }
454
455    pub const fn is_handled(&self) -> bool {
456        self.handled
457    }
458
459    pub fn set_handled(&mut self) {
460        self.handled = true;
461    }
462
463    pub fn sender(&self) -> &CommandSender {
464        &self.sender
465    }
466
467    pub fn request(&mut self, request: InvalidationRequest) {
468        self.invalidations.push(CommandInvalidation {
469            request,
470            reason: None,
471        });
472    }
473
474    pub fn request_with_reason(&mut self, request: InvalidationRequest, reason: impl Into<String>) {
475        self.invalidations.push(CommandInvalidation {
476            request,
477            reason: Some(reason.into()),
478        });
479    }
480
481    /// Invalidate this controller's window, or every window for an
482    /// application controller, which has no window of its own.
483    pub fn request_window(&mut self, kind: InvalidationKind) {
484        self.request_window_region(kind, None, None);
485    }
486
487    /// [`Self::request_window`], recording `reason` in the diagnostics.
488    pub fn request_window_with_reason(
489        &mut self,
490        kind: InvalidationKind,
491        reason: impl Into<String>,
492    ) {
493        self.request_window_region(kind, None, Some(reason.into()));
494    }
495
496    fn request_window_region(
497        &mut self,
498        kind: InvalidationKind,
499        region: Option<Rect>,
500        reason: Option<String>,
501    ) {
502        let Some(window_id) = self.window_id else {
503            self.every_window_invalidations
504                .push(EveryWindowInvalidation {
505                    kind,
506                    region,
507                    reason,
508                });
509            return;
510        };
511        let mut request = InvalidationRequest::new(InvalidationTarget::Window(window_id), kind);
512        if let Some(region) = region {
513            request = request.with_region(region);
514        }
515        self.invalidations
516            .push(CommandInvalidation { request, reason });
517    }
518
519    pub fn request_measure(&mut self) {
520        self.request_window(InvalidationKind::Measure);
521    }
522
523    pub fn request_arrange(&mut self) {
524        self.request_window(InvalidationKind::Arrange);
525    }
526
527    pub fn request_paint(&mut self) {
528        self.request_window(InvalidationKind::Paint);
529    }
530
531    pub fn request_semantics(&mut self) {
532        self.request_window(InvalidationKind::Semantics);
533    }
534
535    /// Repaint `rect` in this controller's window, or in every window for an
536    /// application controller.
537    pub fn request_paint_rect(&mut self, rect: Rect) {
538        self.request_window_region(InvalidationKind::Paint, Some(rect), None);
539    }
540
541    /// Ask `widget_id` for an animation frame. For an application controller,
542    /// whichever window shows `widget_id` gets it.
543    pub fn request_animation_frame(&mut self, widget_id: WidgetId) {
544        self.animation_targets.push((self.window_id, widget_id));
545    }
546
547    pub(crate) fn take_invalidations(&mut self) -> Vec<CommandInvalidation> {
548        std::mem::take(&mut self.invalidations)
549    }
550
551    pub(crate) fn take_every_window_invalidations(&mut self) -> Vec<EveryWindowInvalidation> {
552        std::mem::take(&mut self.every_window_invalidations)
553    }
554
555    pub(crate) fn take_animation_targets(&mut self) -> Vec<(Option<WindowId>, WidgetId)> {
556        std::mem::take(&mut self.animation_targets)
557    }
558}
559
560/// Non-widget application service that receives commands on the UI thread.
561/// Controllers are owned by their application/window builder and are dropped
562/// automatically with that owner.
563pub trait CommandController {
564    fn command(&mut self, _ctx: &mut CommandCtx, _command: &Command<'_>) {}
565
566    /// Called for an explicit scheduler-only [`CommandSender::wake`].
567    fn wake(&mut self, _ctx: &mut CommandCtx) {}
568
569    fn debug_name(&self) -> &'static str {
570        type_name::<Self>()
571    }
572}
573
574type ErasedCommandCallback = dyn FnMut(&mut CommandCtx, &dyn Any);
575
576pub(crate) struct CommandSubscription {
577    key: ErasedCommandKey,
578    handler_name: &'static str,
579    callback: Box<ErasedCommandCallback>,
580}
581
582impl CommandSubscription {
583    pub(crate) fn new<T, F>(key: CommandKey<T>, mut callback: F) -> Self
584    where
585        T: Send + Sync + 'static,
586        F: FnMut(&mut CommandCtx, &T) + 'static,
587    {
588        Self {
589            key: key.erased(),
590            handler_name: type_name::<F>(),
591            callback: Box::new(move |ctx, payload| {
592                if let Some(payload) = payload.downcast_ref::<T>() {
593                    callback(ctx, payload);
594                }
595            }),
596        }
597    }
598}
599
600pub(crate) enum CommandListener {
601    Controller(Box<dyn CommandController>),
602    Subscription(CommandSubscription),
603}
604
605#[derive(Default)]
606pub(crate) struct CommandListeners {
607    listeners: Vec<CommandListener>,
608}
609
610impl CommandListeners {
611    pub(crate) fn push_controller(&mut self, controller: impl CommandController + 'static) {
612        self.listeners
613            .push(CommandListener::Controller(Box::new(controller)));
614    }
615
616    pub(crate) fn push_subscription<T, F>(&mut self, key: CommandKey<T>, callback: F)
617    where
618        T: Send + Sync + 'static,
619        F: FnMut(&mut CommandCtx, &T) + 'static,
620    {
621        self.listeners
622            .push(CommandListener::Subscription(CommandSubscription::new(
623                key, callback,
624            )));
625    }
626
627    pub(crate) fn dispatch(
628        &mut self,
629        ctx: &mut CommandCtx,
630        command: &Command<'_>,
631        broadcast: bool,
632    ) -> Vec<String> {
633        let mut invoked = Vec::new();
634        for listener in &mut self.listeners {
635            match listener {
636                CommandListener::Controller(controller) => {
637                    invoked.push(controller.debug_name().to_string());
638                    controller.command(ctx, command);
639                }
640                CommandListener::Subscription(subscription)
641                    if subscription.key == command.inner.key =>
642                {
643                    invoked.push(subscription.handler_name.to_string());
644                    (subscription.callback)(ctx, command.inner.payload.as_ref());
645                }
646                CommandListener::Subscription(_) => continue,
647            }
648            if ctx.is_handled() && !broadcast {
649                break;
650            }
651        }
652        invoked
653    }
654
655    pub(crate) fn wake(&mut self, ctx: &mut CommandCtx) -> Vec<String> {
656        let mut invoked = Vec::new();
657        for listener in &mut self.listeners {
658            if let CommandListener::Controller(controller) = listener {
659                invoked.push(controller.debug_name().to_string());
660                controller.wake(ctx);
661            }
662        }
663        invoked
664    }
665}
666
667#[cfg(test)]
668mod tests {
669    use super::*;
670
671    static COUNT: CommandKey<u32> = CommandKey::new("test.count");
672
673    #[test]
674    fn typed_keys_reject_a_same_name_different_payload() {
675        static STRING_COUNT: CommandKey<String> = CommandKey::new("test.count");
676        let queued = queued_command(
677            CommandTarget::Application,
678            CommandDelivery::Directed,
679            COUNT,
680            7,
681        );
682        let command = Command::new(&queued);
683        assert_eq!(command.get(COUNT), Some(&7));
684        assert!(command.get(STRING_COUNT).is_none());
685    }
686
687    #[test]
688    fn command_sender_coalesces_scheduler_wakes_but_keeps_payloads() {
689        let sender = CommandSender::new();
690        let wake_count = Arc::new(AtomicU64::new(0));
691        let wake_count_for_callback = Arc::clone(&wake_count);
692        sender.set_waker(Some(Arc::new(move || {
693            wake_count_for_callback.fetch_add(1, Ordering::Relaxed);
694        })));
695
696        sender.send_application(COUNT, 1);
697        sender.send_application(COUNT, 2);
698        assert_eq!(wake_count.load(Ordering::Relaxed), 1);
699        let (_, commands) = sender.drain();
700        assert_eq!(commands.len(), 2);
701    }
702
703    #[test]
704    fn installing_a_waker_notifies_previously_queued_work() {
705        let sender = CommandSender::new();
706        sender.send_application(COUNT, 1);
707        let wake_count = Arc::new(AtomicU64::new(0));
708        let wake_count_for_callback = Arc::clone(&wake_count);
709
710        sender.set_waker(Some(Arc::new(move || {
711            wake_count_for_callback.fetch_add(1, Ordering::Relaxed);
712        })));
713
714        assert_eq!(wake_count.load(Ordering::Relaxed), 1);
715    }
716}