workflow_egui/runtime/events.rs
1use crate::imports::*;
2
3/// The repaint-aware channel over which [`RuntimeEvent`]s are delivered to the
4/// application event loop.
5pub type ApplicationEventsChannel = crate::runtime::channel::Channel<RuntimeEvent>;
6
7#[derive(Clone, Debug)]
8/// A type-erased, cheaply-cloneable container for an application-defined event,
9/// downcast back to its concrete type by the consumer.
10pub struct ApplicationEvent(Arc<dyn Any + Send + Sync>);
11
12impl ApplicationEvent {
13 /// Wraps an arbitrary value as a type-erased application event.
14 pub fn new<T>(event: T) -> Self
15 where
16 T: Any + Send + Sync + 'static,
17 {
18 ApplicationEvent(Arc::new(event))
19 }
20
21 #[allow(clippy::should_implement_trait)]
22 /// Borrows the wrapped value as `&T`, panicking if the concrete type does
23 /// not match `T`.
24 pub fn as_ref<T>(&self) -> &T
25 where
26 T: Any,
27 {
28 self.0.downcast_ref::<T>().unwrap()
29 }
30
31 // pub fn into<T>(self) -> T
32 // where
33 // T: Any + Send + Sync,
34 // {
35 // let this = self
36 // .0
37 // .downcast::<T>()
38 // .expect("unknown application event type");
39 // // Arc::into_inner(this).expect("multiple references to application event type")
40 // Arc::unwrap_or_clone(this).expect("multiple references to application event type")
41 // }
42
43 /// Consumes the event and returns the wrapped value as an `Arc<T>`,
44 /// panicking if the concrete type does not match `T`.
45 pub fn as_arc<T>(self) -> Arc<T>
46 where
47 T: Any + Send + Sync,
48 {
49 self.0
50 .downcast::<T>()
51 .expect("unknown application event type")
52 }
53}
54
55#[derive(Clone, Debug)]
56/// Events delivered to the runtime event loop, covering runtime lifecycle
57/// signals as well as custom application-defined events.
58pub enum RuntimeEvent {
59 /// An error condition reported to the runtime, carrying a message.
60 Error(String),
61 /// A request to gracefully shut down the application.
62 Exit,
63 /// A change in the application window's visibility state.
64 VisibilityState(VisibilityState),
65 /// A custom application-defined event.
66 Application(ApplicationEvent),
67}
68
69impl RuntimeEvent {
70 /// Wraps an arbitrary application-defined event in a
71 /// [`RuntimeEvent::Application`] variant.
72 pub fn new<T>(event: T) -> Self
73 where
74 T: Any + Send + Sync + 'static,
75 {
76 RuntimeEvent::Application(ApplicationEvent::new(event))
77 }
78}