Skip to main content

uzor_framework/handle/
mod.rs

1//! ROLE handle: the app's only door into on-screen state (design §6.1).
2//!
3//! [`Handle`] is `Clone + Send + Sync`: a back-office task thread can
4//! dispatch a visual command ("open the error modal") without touching the
5//! UI thread, and read the last published snapshot lock-free. This module
6//! and the hosts are the only places channels and `Arc` exist (SWC Law
7//! 2-3, ban F5). There is no `subscribe`: observers poll
8//! [`Handle::revision`]; the in-thread event channel is [`App::intent`].
9//!
10//! [`App::intent`]: crate::handle::App::intent
11
12mod app;
13
14pub use app::{
15    App, FrameTime, HookOp, HookOps, InitCx, IntentCx, OverlayCx, PanelCx, VisualView, Widgets,
16};
17
18use std::sync::mpsc::SyncSender;
19use std::sync::Arc;
20
21use arc_swap::ArcSwap;
22
23use crate::types::command::AppCommand;
24use crate::types::ids::Revision;
25use crate::types::snapshot::VisualSnapshot;
26use crate::types::spec::Spec;
27
28/// Bounded command inbox capacity (design §6.1).
29pub(crate) const INBOX_CAP: usize = 1024;
30
31/// Wakes the host loop after a dispatch so a command never waits for the
32/// next input event. Native: `EventLoopProxy::send_event`; web: a RAF
33/// request; headless: a no-op.
34#[derive(Clone)]
35pub struct Waker(Arc<dyn Fn() + Send + Sync>);
36
37impl Waker {
38    /// A waker from any thread-safe closure.
39    pub fn new(f: impl Fn() + Send + Sync + 'static) -> Self {
40        Self(Arc::new(f))
41    }
42
43    /// A waker that does nothing (headless host, tests).
44    pub fn noop() -> Self {
45        Self(Arc::new(|| {}))
46    }
47
48    /// Ask the host loop to run a tick.
49    pub fn wake(&self) {
50        (self.0)();
51    }
52}
53
54impl std::fmt::Debug for Waker {
55    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56        f.debug_struct("Waker").finish_non_exhaustive()
57    }
58}
59
60/// Why a dispatch failed.
61#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
62pub enum HandleError {
63    /// The inbox is at capacity; the command was NOT queued (never a
64    /// silent drop). The app should coalesce and retry.
65    #[error("inbox full")]
66    Full,
67    /// The runtime is gone; the command went nowhere.
68    #[error("runtime stopped")]
69    Closed,
70}
71
72/// The app's door into on-screen state (design §6.1).
73///
74/// Cheap to clone, `Send + Sync` when the spec's vocabularies are (given
75/// by [`Spec`]). Produced by [`Runtime::new`](crate::Runtime::new); the
76/// app hands clones to whatever threads need them.
77pub struct Handle<S: Spec> {
78    pub(crate) tx: SyncSender<AppCommand<S>>,
79    pub(crate) snap: Arc<ArcSwap<VisualSnapshot<S>>>,
80    pub(crate) waker: Waker,
81}
82
83impl<S: Spec> Clone for Handle<S> {
84    fn clone(&self) -> Self {
85        Self {
86            tx: self.tx.clone(),
87            snap: Arc::clone(&self.snap),
88            waker: self.waker.clone(),
89        }
90    }
91}
92
93impl<S: Spec> std::fmt::Debug for Handle<S> {
94    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95        f.debug_struct("Handle")
96            .field("revision", &self.revision())
97            .finish_non_exhaustive()
98    }
99}
100
101impl<S: Spec> Handle<S> {
102    /// Enqueue a visual command and wake the loop. Never blocks; a full
103    /// inbox surfaces as [`HandleError::Full`], a dead runtime as
104    /// [`HandleError::Closed`].
105    pub fn dispatch(&self, cmd: AppCommand<S>) -> Result<(), HandleError> {
106        self.tx.try_send(cmd).map_err(|e| match e {
107            std::sync::mpsc::TrySendError::Full(_) => HandleError::Full,
108            std::sync::mpsc::TrySendError::Disconnected(_) => HandleError::Closed,
109        })?;
110        self.waker.wake();
111        Ok(())
112    }
113
114    /// The last published snapshot: lock-free, at most one tick old.
115    pub fn snapshot(&self) -> Arc<VisualSnapshot<S>> {
116        self.snap.load_full()
117    }
118
119    /// The published revision; observers compare it to know whether to
120    /// re-read the snapshot.
121    pub fn revision(&self) -> Revision {
122        self.snap.load().revision
123    }
124}