Skip to main content

vizia_core/events/
event.rs

1use crate::entity::Entity;
2use crate::prelude::Modifiers;
3use std::time::Instant;
4use std::{any::Any, cmp::Ordering, fmt::Debug};
5use vizia_id::GenerationalId;
6
7/// Determines how an event propagates through the tree.
8#[derive(Debug, Clone, Copy, PartialEq)]
9pub enum Propagation {
10    // /// Events propagate down the tree to the target entity, e.g. from grand-parent to parent to child (target)
11    // Down,
12    /// Events propagate up the tree from the target entity from ancestor to ancestor, e.g. from child (target) to parent to grand-parent etc.
13    Up,
14    // /// Events propagate down the tree to the target entity and then back up to the root
15    // DownUp,
16    /// Events propagate starting at the target entity and visiting every entity that is a descendent of the target.
17    Subtree,
18    /// Events propagate directly to the target entity and to no others.
19    Direct,
20}
21
22/// A wrapper around a message, providing metadata on how the event travels through the view tree.
23pub struct Event {
24    /// The meta data of the event
25    pub(crate) meta: EventMeta,
26    /// The message of the event
27    pub(crate) message: Option<Box<dyn Any>>,
28}
29
30/// A sendable event payload used by context proxies to forward events from non-UI threads.
31pub struct ProxyEvent {
32    /// The meta data of the event
33    pub(crate) meta: EventMeta,
34    /// The sendable message payload
35    pub(crate) message: Option<Box<dyn Any + Send>>,
36}
37
38impl Debug for Event {
39    fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        Ok(())
41    }
42}
43
44impl Debug for ProxyEvent {
45    fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        Ok(())
47    }
48}
49
50impl Event {
51    /// Creates a new event with a specified message.
52    pub fn new<M>(message: M) -> Self
53    where
54        M: Any,
55    {
56        Event { meta: Default::default(), message: Some(Box::new(message)) }
57    }
58
59    /// Inherit the emitting UI context once, retaining an earlier snapshot when forwarded.
60    pub(crate) fn inherit_ui_modifiers(mut self, modifiers: Modifiers) -> Self {
61        self.meta.modifiers.get_or_insert(modifiers);
62        self
63    }
64
65    /// Sets the target of the event.
66    pub fn target(mut self, entity: Entity) -> Self {
67        self.meta.target = entity;
68        self
69    }
70
71    /// Sets the origin of the event.
72    pub fn origin(mut self, entity: Entity) -> Self {
73        self.meta.origin = entity;
74        self
75    }
76
77    /// Sets the propagation of the event.
78    pub fn propagate(mut self, propagation: Propagation) -> Self {
79        self.meta.propagation = propagation;
80        self
81    }
82
83    /// Sets the propagation to directly target the `entity`.
84    pub fn direct(mut self, entity: Entity) -> Self {
85        self.meta.propagation = Propagation::Direct;
86        self.meta.target = entity;
87        self
88    }
89
90    /// Consumes the event to prevent it from continuing on its propagation path.
91    pub fn consume(&mut self) {
92        self.meta.consume();
93    }
94
95    /// Tries to downcast the event message to the specified type. If the downcast was successful,
96    /// the message and the event metadata get passed into `f`.
97    ///
98    /// # Example
99    /// ```no_run
100    /// # use vizia_core::prelude::*;
101    /// # let cx = &mut Context::default();
102    /// # use vizia_winit::application::Application;
103    /// # pub struct AppData {
104    /// #     count: i32,
105    /// # }
106    /// # pub enum AppEvent {
107    /// #     Increment,
108    /// #     Decrement,    
109    /// # }
110    /// # impl Model for AppData {
111    /// #     fn event(&mut self, _cx: &mut EventContext, event: &mut Event) {
112    /// event.map(|app_event, _| match app_event {
113    ///     AppEvent::Increment => {
114    ///         self.count += 1;
115    ///     }
116    ///
117    ///     AppEvent::Decrement => {
118    ///         self.count -= 1;
119    ///     }
120    /// });
121    /// #     }
122    /// # }
123    /// ```
124    pub fn map<M, F>(&mut self, f: F)
125    where
126        M: Any,
127        F: FnOnce(&M, &mut EventMeta),
128    {
129        if let Some(message) = &self.message
130            && let Some(message) = message.as_ref().downcast_ref()
131        {
132            (f)(message, &mut self.meta);
133        }
134    }
135
136    /// Tries to downcast the event message to the specified type. If the downcast was successful,
137    /// return the message by value and consume the event. Otherwise, do nothing.
138    ///
139    /// # Example
140    /// ```
141    /// # use vizia_core::prelude::*;
142    /// # let cx = &mut Context::default();
143    /// # use vizia_winit::application::Application;
144    /// # pub struct AppData {
145    /// #     count: i32,
146    /// # }
147    /// # pub enum AppEvent {
148    /// #     Increment,
149    /// #     Decrement,
150    /// # }
151    /// # impl Model for AppData {
152    /// #     fn event(&mut self, _cx: &mut EventContext, event: &mut Event) {
153    /// event.take(|app_event, meta| match app_event {
154    ///     AppEvent::Increment => {
155    ///         self.count += 1;
156    ///     }
157    ///
158    ///     AppEvent::Decrement => {
159    ///         self.count -= 1;
160    ///     }
161    /// });
162    /// #     }
163    /// # }
164    /// ```
165    pub fn take<M: Any, F>(&mut self, f: F)
166    where
167        F: FnOnce(M, &mut EventMeta),
168    {
169        if let Some(message) = &self.message
170            && message.as_ref().is::<M>()
171        {
172            // Safe to unwrap because we already checked it exists
173            let m = self.message.take().unwrap();
174            // Safe to unwrap because we already checked it can be cast to M
175            let v = m.downcast().unwrap();
176            self.meta.consume();
177            (f)(*v, &mut self.meta);
178        }
179    }
180}
181
182impl ProxyEvent {
183    /// Creates a new proxy event with a sendable message.
184    pub fn new<M>(message: M) -> Self
185    where
186        M: Any + Send,
187    {
188        ProxyEvent { meta: Default::default(), message: Some(Box::new(message)) }
189    }
190
191    /// Sets the target of the event.
192    pub fn target(mut self, entity: Entity) -> Self {
193        self.meta.target = entity;
194        self
195    }
196
197    /// Sets the origin of the event.
198    pub fn origin(mut self, entity: Entity) -> Self {
199        self.meta.origin = entity;
200        self
201    }
202
203    /// Sets the propagation of the event.
204    pub fn propagate(mut self, propagation: Propagation) -> Self {
205        self.meta.propagation = propagation;
206        self
207    }
208
209    /// Converts a proxy event into a normal event on the UI thread.
210    pub fn into_event(self) -> Event {
211        Event { meta: self.meta, message: self.message.map(|message| message as Box<dyn Any>) }
212    }
213}
214
215/// The metadata of an [`Event`].
216#[derive(Debug, Clone, Copy)]
217pub struct EventMeta {
218    /// The entity that produced the event.
219    pub origin: Entity,
220    /// The entity the event should be sent to (or from in the case of subtree propagation).
221    pub target: Entity,
222    /// How the event propagates through the tree.
223    pub propagation: Propagation,
224    /// Determines whether the event should continue to be propagated.
225    pub(crate) consumed: bool,
226    /// UI emission context. None denotes an event, such as a proxy payload, with no UI context;
227    /// dispatch then observes the ambient native modifier state.
228    pub(crate) modifiers: Option<Modifiers>,
229}
230
231impl EventMeta {
232    /// Consumes the event to prevent it from continuing on its propagation path.
233    pub fn consume(&mut self) {
234        self.consumed = true;
235    }
236}
237
238impl Default for EventMeta {
239    fn default() -> Self {
240        Self {
241            origin: Entity::null(),
242            target: Entity::root(),
243            propagation: Propagation::Up,
244            consumed: false,
245            modifiers: None,
246        }
247    }
248}
249
250/// A handle used to cancel a scheduled event before it is sent with `cx.cancel_scheduled`.
251#[derive(Debug, PartialEq, Eq, Copy, Clone)]
252pub struct TimedEventHandle(pub usize);
253
254#[derive(Debug)]
255pub(crate) struct TimedEvent {
256    pub ident: TimedEventHandle,
257    pub event: Event,
258    pub time: Instant,
259}
260
261impl PartialEq<Self> for TimedEvent {
262    fn eq(&self, other: &Self) -> bool {
263        self.time.eq(&other.time)
264    }
265}
266
267impl Eq for TimedEvent {}
268
269impl PartialOrd for TimedEvent {
270    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
271        Some(self.cmp(other))
272    }
273}
274
275impl Ord for TimedEvent {
276    fn cmp(&self, other: &Self) -> Ordering {
277        self.time.cmp(&other.time).reverse()
278    }
279}