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#[derive(Clone)]
270pub struct CommandSender {
271    hub: Arc<CommandHub>,
272}
273
274impl CommandSender {
275    pub(crate) fn new() -> Self {
276        Self {
277            hub: CommandHub::new(),
278        }
279    }
280
281    pub fn wake(&self) {
282        self.hub.wake();
283    }
284
285    pub fn send<T>(&self, target: CommandTarget, key: CommandKey<T>, payload: T)
286    where
287        T: Send + Sync + 'static,
288    {
289        self.enqueue(target, CommandDelivery::Directed, key, payload);
290    }
291
292    pub fn broadcast<T>(&self, target: CommandTarget, key: CommandKey<T>, payload: T)
293    where
294        T: Send + Sync + 'static,
295    {
296        self.enqueue(target, CommandDelivery::Broadcast, key, payload);
297    }
298
299    pub fn send_widget<T>(
300        &self,
301        window_id: WindowId,
302        widget_id: WidgetId,
303        key: CommandKey<T>,
304        payload: T,
305    ) where
306        T: Send + Sync + 'static,
307    {
308        self.send(
309            CommandTarget::Widget {
310                window_id,
311                widget_id,
312            },
313            key,
314            payload,
315        );
316    }
317
318    pub fn send_focused<T>(&self, window_id: WindowId, key: CommandKey<T>, payload: T)
319    where
320        T: Send + Sync + 'static,
321    {
322        self.send(CommandTarget::FocusedWidget(window_id), key, payload);
323    }
324
325    pub fn send_window<T>(&self, window_id: WindowId, key: CommandKey<T>, payload: T)
326    where
327        T: Send + Sync + 'static,
328    {
329        self.send(CommandTarget::Window(window_id), key, payload);
330    }
331
332    pub fn send_application<T>(&self, key: CommandKey<T>, payload: T)
333    where
334        T: Send + Sync + 'static,
335    {
336        self.send(CommandTarget::Application, key, payload);
337    }
338
339    pub fn broadcast_window<T>(&self, window_id: WindowId, key: CommandKey<T>, payload: T)
340    where
341        T: Send + Sync + 'static,
342    {
343        self.broadcast(CommandTarget::Window(window_id), key, payload);
344    }
345
346    pub fn broadcast_application<T>(&self, key: CommandKey<T>, payload: T)
347    where
348        T: Send + Sync + 'static,
349    {
350        self.broadcast(CommandTarget::Application, key, payload);
351    }
352
353    fn enqueue<T>(
354        &self,
355        target: CommandTarget,
356        delivery: CommandDelivery,
357        key: CommandKey<T>,
358        payload: T,
359    ) where
360        T: Send + Sync + 'static,
361    {
362        self.hub
363            .enqueue(queued_command(target, delivery, key, payload));
364    }
365
366    pub(crate) fn set_waker(&self, waker: Option<Arc<ExternalWaker>>) {
367        self.hub.set_waker(waker);
368    }
369
370    pub(crate) fn drain(&self) -> (bool, Vec<QueuedCommand>) {
371        self.hub.drain()
372    }
373
374    pub(crate) fn has_pending(&self) -> bool {
375        self.hub.has_pending()
376    }
377}
378
379impl fmt::Debug for CommandSender {
380    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
381        formatter
382            .debug_struct("CommandSender")
383            .field("has_pending", &self.has_pending())
384            .finish_non_exhaustive()
385    }
386}
387
388pub(crate) fn queued_command<T>(
389    target: CommandTarget,
390    delivery: CommandDelivery,
391    key: CommandKey<T>,
392    payload: T,
393) -> QueuedCommand
394where
395    T: Send + Sync + 'static,
396{
397    QueuedCommand {
398        sequence: NEXT_COMMAND_SEQUENCE.fetch_add(1, Ordering::Relaxed),
399        key: key.erased(),
400        target,
401        delivery,
402        payload: Arc::new(payload),
403    }
404}
405
406#[derive(Debug, Clone)]
407pub(crate) struct CommandInvalidation {
408    pub(crate) request: InvalidationRequest,
409    pub(crate) reason: Option<String>,
410}
411
412/// Context supplied to window and application command controllers.
413pub struct CommandCtx {
414    sender: CommandSender,
415    window_id: Option<WindowId>,
416    handled: bool,
417    invalidations: Vec<CommandInvalidation>,
418    animation_targets: Vec<(WindowId, WidgetId)>,
419}
420
421impl CommandCtx {
422    pub(crate) fn new(sender: CommandSender, window_id: Option<WindowId>) -> Self {
423        Self {
424            sender,
425            window_id,
426            handled: false,
427            invalidations: Vec::new(),
428            animation_targets: Vec::new(),
429        }
430    }
431
432    pub const fn window_id(&self) -> Option<WindowId> {
433        self.window_id
434    }
435
436    pub const fn is_handled(&self) -> bool {
437        self.handled
438    }
439
440    pub fn set_handled(&mut self) {
441        self.handled = true;
442    }
443
444    pub fn sender(&self) -> &CommandSender {
445        &self.sender
446    }
447
448    pub fn request(&mut self, request: InvalidationRequest) {
449        self.invalidations.push(CommandInvalidation {
450            request,
451            reason: None,
452        });
453    }
454
455    pub fn request_with_reason(&mut self, request: InvalidationRequest, reason: impl Into<String>) {
456        self.invalidations.push(CommandInvalidation {
457            request,
458            reason: Some(reason.into()),
459        });
460    }
461
462    pub fn request_window(&mut self, kind: InvalidationKind) {
463        let window_id = self
464            .window_id
465            .expect("window invalidation requires a window-scoped command controller");
466        self.request(InvalidationRequest::new(
467            InvalidationTarget::Window(window_id),
468            kind,
469        ));
470    }
471
472    pub fn request_window_with_reason(
473        &mut self,
474        kind: InvalidationKind,
475        reason: impl Into<String>,
476    ) {
477        let window_id = self
478            .window_id
479            .expect("window invalidation requires a window-scoped command controller");
480        self.request_with_reason(
481            InvalidationRequest::new(InvalidationTarget::Window(window_id), kind),
482            reason,
483        );
484    }
485
486    pub fn request_measure(&mut self) {
487        self.request_window(InvalidationKind::Measure);
488    }
489
490    pub fn request_arrange(&mut self) {
491        self.request_window(InvalidationKind::Arrange);
492    }
493
494    pub fn request_paint(&mut self) {
495        self.request_window(InvalidationKind::Paint);
496    }
497
498    pub fn request_semantics(&mut self) {
499        self.request_window(InvalidationKind::Semantics);
500    }
501
502    pub fn request_paint_rect(&mut self, rect: Rect) {
503        let window_id = self
504            .window_id
505            .expect("window invalidation requires a window-scoped command controller");
506        self.request(
507            InvalidationRequest::new(
508                InvalidationTarget::Window(window_id),
509                InvalidationKind::Paint,
510            )
511            .with_region(rect),
512        );
513    }
514
515    pub fn request_animation_frame(&mut self, widget_id: WidgetId) {
516        let window_id = self
517            .window_id
518            .expect("animation requests require a window-scoped command controller");
519        self.animation_targets.push((window_id, widget_id));
520    }
521
522    pub(crate) fn take_invalidations(&mut self) -> Vec<CommandInvalidation> {
523        std::mem::take(&mut self.invalidations)
524    }
525
526    pub(crate) fn take_animation_targets(&mut self) -> Vec<(WindowId, WidgetId)> {
527        std::mem::take(&mut self.animation_targets)
528    }
529}
530
531/// Non-widget application service that receives commands on the UI thread.
532/// Controllers are owned by their application/window builder and are dropped
533/// automatically with that owner.
534pub trait CommandController {
535    fn command(&mut self, _ctx: &mut CommandCtx, _command: &Command<'_>) {}
536
537    /// Called for an explicit scheduler-only [`CommandSender::wake`].
538    fn wake(&mut self, _ctx: &mut CommandCtx) {}
539
540    fn debug_name(&self) -> &'static str {
541        type_name::<Self>()
542    }
543}
544
545type ErasedCommandCallback = dyn FnMut(&mut CommandCtx, &dyn Any);
546
547pub(crate) struct CommandSubscription {
548    key: ErasedCommandKey,
549    handler_name: &'static str,
550    callback: Box<ErasedCommandCallback>,
551}
552
553impl CommandSubscription {
554    pub(crate) fn new<T, F>(key: CommandKey<T>, mut callback: F) -> Self
555    where
556        T: Send + Sync + 'static,
557        F: FnMut(&mut CommandCtx, &T) + 'static,
558    {
559        Self {
560            key: key.erased(),
561            handler_name: type_name::<F>(),
562            callback: Box::new(move |ctx, payload| {
563                if let Some(payload) = payload.downcast_ref::<T>() {
564                    callback(ctx, payload);
565                }
566            }),
567        }
568    }
569}
570
571pub(crate) enum CommandListener {
572    Controller(Box<dyn CommandController>),
573    Subscription(CommandSubscription),
574}
575
576#[derive(Default)]
577pub(crate) struct CommandListeners {
578    listeners: Vec<CommandListener>,
579}
580
581impl CommandListeners {
582    pub(crate) fn push_controller(&mut self, controller: impl CommandController + 'static) {
583        self.listeners
584            .push(CommandListener::Controller(Box::new(controller)));
585    }
586
587    pub(crate) fn push_subscription<T, F>(&mut self, key: CommandKey<T>, callback: F)
588    where
589        T: Send + Sync + 'static,
590        F: FnMut(&mut CommandCtx, &T) + 'static,
591    {
592        self.listeners
593            .push(CommandListener::Subscription(CommandSubscription::new(
594                key, callback,
595            )));
596    }
597
598    pub(crate) fn dispatch(
599        &mut self,
600        ctx: &mut CommandCtx,
601        command: &Command<'_>,
602        broadcast: bool,
603    ) -> Vec<String> {
604        let mut invoked = Vec::new();
605        for listener in &mut self.listeners {
606            match listener {
607                CommandListener::Controller(controller) => {
608                    invoked.push(controller.debug_name().to_string());
609                    controller.command(ctx, command);
610                }
611                CommandListener::Subscription(subscription)
612                    if subscription.key == command.inner.key =>
613                {
614                    invoked.push(subscription.handler_name.to_string());
615                    (subscription.callback)(ctx, command.inner.payload.as_ref());
616                }
617                CommandListener::Subscription(_) => continue,
618            }
619            if ctx.is_handled() && !broadcast {
620                break;
621            }
622        }
623        invoked
624    }
625
626    pub(crate) fn wake(&mut self, ctx: &mut CommandCtx) -> Vec<String> {
627        let mut invoked = Vec::new();
628        for listener in &mut self.listeners {
629            if let CommandListener::Controller(controller) = listener {
630                invoked.push(controller.debug_name().to_string());
631                controller.wake(ctx);
632            }
633        }
634        invoked
635    }
636}
637
638#[cfg(test)]
639mod tests {
640    use super::*;
641
642    static COUNT: CommandKey<u32> = CommandKey::new("test.count");
643
644    #[test]
645    fn typed_keys_reject_a_same_name_different_payload() {
646        static STRING_COUNT: CommandKey<String> = CommandKey::new("test.count");
647        let queued = queued_command(
648            CommandTarget::Application,
649            CommandDelivery::Directed,
650            COUNT,
651            7,
652        );
653        let command = Command::new(&queued);
654        assert_eq!(command.get(COUNT), Some(&7));
655        assert!(command.get(STRING_COUNT).is_none());
656    }
657
658    #[test]
659    fn command_sender_coalesces_scheduler_wakes_but_keeps_payloads() {
660        let sender = CommandSender::new();
661        let wake_count = Arc::new(AtomicU64::new(0));
662        let wake_count_for_callback = Arc::clone(&wake_count);
663        sender.set_waker(Some(Arc::new(move || {
664            wake_count_for_callback.fetch_add(1, Ordering::Relaxed);
665        })));
666
667        sender.send_application(COUNT, 1);
668        sender.send_application(COUNT, 2);
669        assert_eq!(wake_count.load(Ordering::Relaxed), 1);
670        let (_, commands) = sender.drain();
671        assert_eq!(commands.len(), 2);
672    }
673
674    #[test]
675    fn installing_a_waker_notifies_previously_queued_work() {
676        let sender = CommandSender::new();
677        sender.send_application(COUNT, 1);
678        let wake_count = Arc::new(AtomicU64::new(0));
679        let wake_count_for_callback = Arc::clone(&wake_count);
680
681        sender.set_waker(Some(Arc::new(move || {
682            wake_count_for_callback.fetch_add(1, Ordering::Relaxed);
683        })));
684
685        assert_eq!(wake_count.load(Ordering::Relaxed), 1);
686    }
687}