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};
17pub(crate) use app::VisualQuery;
18
19use std::sync::mpsc::SyncSender;
20use std::sync::Arc;
21
22use arc_swap::ArcSwap;
23
24use crate::types::command::AppCommand;
25use crate::types::ids::Revision;
26use crate::types::snapshot::VisualSnapshot;
27use crate::types::spec::Spec;
28
29/// Bounded command inbox capacity (design §6.1).
30pub(crate) const INBOX_CAP: usize = 1024;
31
32/// Wakes the host loop after a dispatch so a command never waits for the
33/// next input event. Native: `EventLoopProxy::send_event`; web: a RAF
34/// request; headless: a no-op.
35#[derive(Clone)]
36pub struct Waker(Arc<dyn Fn() + Send + Sync>);
37
38impl Waker {
39    /// A waker from any thread-safe closure.
40    pub fn new(f: impl Fn() + Send + Sync + 'static) -> Self {
41        Self(Arc::new(f))
42    }
43
44    /// A waker that does nothing (headless host, tests).
45    pub fn noop() -> Self {
46        Self(Arc::new(|| {}))
47    }
48
49    /// Ask the host loop to run a tick.
50    pub fn wake(&self) {
51        (self.0)();
52    }
53}
54
55impl std::fmt::Debug for Waker {
56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        f.debug_struct("Waker").finish_non_exhaustive()
58    }
59}
60
61/// Why a dispatch failed.
62#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
63pub enum HandleError {
64    /// The inbox is at capacity; the command was NOT queued (never a
65    /// silent drop). The app should coalesce and retry.
66    #[error("inbox full")]
67    Full,
68    /// The runtime is gone; the command went nowhere.
69    #[error("runtime stopped")]
70    Closed,
71}
72
73/// The app's door into on-screen state (design §6.1).
74///
75/// Cheap to clone, `Send + Sync` when the spec's vocabularies are (given
76/// by [`Spec`]). Produced by [`Runtime::new`](crate::Runtime::new); the
77/// app hands clones to whatever threads need them.
78pub struct Handle<S: Spec> {
79    pub(crate) tx: SyncSender<AppCommand<S>>,
80    pub(crate) snap: Arc<ArcSwap<VisualSnapshot<S>>>,
81    pub(crate) waker: Waker,
82}
83
84impl<S: Spec> Clone for Handle<S> {
85    fn clone(&self) -> Self {
86        Self {
87            tx: self.tx.clone(),
88            snap: Arc::clone(&self.snap),
89            waker: self.waker.clone(),
90        }
91    }
92}
93
94impl<S: Spec> std::fmt::Debug for Handle<S> {
95    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96        f.debug_struct("Handle")
97            .field("revision", &self.revision())
98            .finish_non_exhaustive()
99    }
100}
101
102impl<S: Spec> Handle<S> {
103    /// Enqueue a visual command and wake the loop. Never blocks; a full
104    /// inbox surfaces as [`HandleError::Full`], a dead runtime as
105    /// [`HandleError::Closed`].
106    pub fn dispatch(&self, cmd: AppCommand<S>) -> Result<(), HandleError> {
107        self.tx.try_send(cmd).map_err(|e| match e {
108            std::sync::mpsc::TrySendError::Full(_) => HandleError::Full,
109            std::sync::mpsc::TrySendError::Disconnected(_) => HandleError::Closed,
110        })?;
111        self.waker.wake();
112        Ok(())
113    }
114
115    /// Ask for a repaint of `win` from outside a hook (network data,
116    /// background work): an [`AppCommand::Cadence`] invalidate plus a wake.
117    /// The host then paints on demand instead of polling every frame.
118    pub fn request_repaint(&self, win: crate::WindowId) -> Result<(), HandleError> {
119        self.dispatch(AppCommand::Cadence(crate::CadenceCmd::Invalidate {
120            win,
121            region: None,
122            bits: uzor::render::InvalidateBits::ALL,
123        }))
124    }
125
126    /// The last published snapshot: lock-free, at most one tick old.
127    pub fn snapshot(&self) -> Arc<VisualSnapshot<S>> {
128        self.snap.load_full()
129    }
130
131    /// The published revision; observers compare it to know whether to
132    /// re-read the snapshot.
133    pub fn revision(&self) -> Revision {
134        self.snap.load().revision
135    }
136}