uzor_framework/handle/
mod.rs1mod 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
28pub(crate) const INBOX_CAP: usize = 1024;
30
31#[derive(Clone)]
35pub struct Waker(Arc<dyn Fn() + Send + Sync>);
36
37impl Waker {
38 pub fn new(f: impl Fn() + Send + Sync + 'static) -> Self {
40 Self(Arc::new(f))
41 }
42
43 pub fn noop() -> Self {
45 Self(Arc::new(|| {}))
46 }
47
48 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#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
62pub enum HandleError {
63 #[error("inbox full")]
66 Full,
67 #[error("runtime stopped")]
69 Closed,
70}
71
72pub 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 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 pub fn snapshot(&self) -> Arc<VisualSnapshot<S>> {
116 self.snap.load_full()
117 }
118
119 pub fn revision(&self) -> Revision {
122 self.snap.load().revision
123 }
124}