Skip to main content

pushrod/
event.rs

1// Event
2// Pushrod
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! # Events
17//!
18//! Events are objects that say what happened, in plain terms, with named fields.  They cover
19//! the pointer, keyboard, focus, widget semantics, lifecycle, window, time, the engine, and
20//! application-defined (custom) events.
21//!
22//! Events flow through Pushrod much like the event buffer in GEM on the Atari ST:
23//!
24//! ```text
25//!  SDL2 Event ──> WidgetCache ──> Widget::handle_event(&mut self, event, ctx)
26//!                                          │
27//!                                    ctx.emit(Clicked { .. })
28//!                                          │
29//!                                          v
30//!                                   event queue (Vec)
31//!                                          │
32//!            (after the Widget is no longer borrowed by the engine)
33//!                                          v
34//!                        Engine callbacks: on_click / on_event
35//!                          FnMut(&mut AppState, &mut Ui)
36//! ```
37//!
38//! Queueing the generated events, instead of calling application code from inside the `Widget`,
39//! is what allows callbacks to receive mutable access to both the application state and every
40//! `Widget` in the window without fighting the borrow checker.
41//!
42//! Every [`Event`] has a [`kind`](Event::kind) (used by masks and the callback registry) and an
43//! optional [`widget`](Event::widget) it concerns.
44//!
45//! ## Event reference
46//!
47//! | Group | Event | Emitted when |
48//! | --- | --- | --- |
49//! | Pointer | `PointerEntered` | The pointer moves onto a widget. |
50//! | Pointer | `PointerExited` | The pointer moves off a widget. |
51//! | Pointer | `PointerMoved` | The pointer moves; sent to the capturing widget, or the one under the pointer. |
52//! | Pointer | `PointerPressed` | A mouse button goes down over a widget. |
53//! | Pointer | `PointerReleased` | A mouse button goes up; sent to the widget that captured the press. |
54//! | Pointer | `Clicked` | A widget (such as a button) was pressed and released on itself. |
55//! | Pointer | `Scrolled` | The wheel or trackpad scrolls over a widget. |
56//! | Keyboard | `KeyPressed` | A key goes down (or repeats) while a widget has the keyboard. |
57//! | Keyboard | `KeyReleased` | A key goes up. |
58//! | Keyboard | `TextEntered` | Text is typed (after input-method composition). |
59//! | Focus | `FocusGained` | A widget becomes the keyboard focus. |
60//! | Focus | `FocusLost` | A widget stops being the keyboard focus. |
61//! | Semantic | `Activated` | A widget is activated (button, menu item, Return on a default action). |
62//! | Semantic | `Toggled` | A checkable widget changes state; `checked` is the new state. |
63//! | Semantic | `ValueChanged` | A slider, spinner, or similar changes value. |
64//! | Semantic | `SelectionChanged` | The selection in a list, table, or tab set changes. |
65//! | Semantic | `TextChanged` | The text of an editor changes. |
66//! | Semantic | `EditingFinished` | An editor loses focus or the user confirms its text. |
67//! | Semantic | `Triggered` | A named action is triggered (menu, shortcut, toolbar). |
68//! | Semantic | `ContextMenuRequested` | The user asks for a context menu at `position`. |
69//! | Semantic | `PropertyChanged` | A named property of a widget changes. |
70//! | Semantic | `ViewportChanged` | A scrolling widget's visible area moves to `offset`. |
71//! | Lifecycle | `Shown` / `Hidden` | A widget becomes visible / hidden. |
72//! | Lifecycle | `Resized` / `Moved` | A widget's size / origin changes. |
73//! | Lifecycle | `Removed` | A widget is removed from the tree. |
74//! | Window | `WindowResized` | The window size changes. |
75//! | Window | `WindowFocusChanged` | The window gains or loses focus. |
76//! | Window | `CloseRequested` | The user asks to close the window. |
77//! | Time | `Tick` | A frame passes while a widget animates; `elapsed` is the time since the last tick. |
78//! | Engine | `Engine` | Pushrod performs an internal action ([`EngineEvent`]). |
79//! | Extension | `Custom` | An application or library defines its own event ([`CustomEvent`]). |
80//!
81//! `BoundsChange` from the first release is now `PointerExited` followed by `PointerEntered`,
82//! and `SystemEvent` is split into `PointerPressed`, `PointerReleased`, and `PointerMoved`.
83//! Window-system input arrives as a backend's [`InputEvent`](crate::input::InputEvent).
84
85use crate::error::Error;
86use crate::geometry::{Point, Size};
87use crate::input::{Key, Modifiers, MouseButton};
88use crate::timer::TimerId;
89use crate::widget::WidgetId;
90use std::any::Any;
91use std::fmt;
92use std::rc::Rc;
93use std::time::Duration;
94
95/// Where a [`CustomEvent`] is delivered.
96///
97/// Whatever the target, the application's `on_custom` and `on_event` callbacks always receive the
98/// event; the target only chooses which `Widget`s see it in `handle_event`.  A `Widget` receives it
99/// only if [`EventMask::CUSTOM`] is in its mask (and in the run loop's mask).
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
101pub enum EventTarget {
102    /// One `Widget`.
103    Widget(WidgetId),
104    /// A `Widget` and all of its descendants, parents before children.
105    Subtree(WidgetId),
106    /// Every visible `Widget`, in drawing order.
107    Broadcast,
108    /// No `Widget`: only the application's callbacks receive it.
109    ApplicationOnly,
110}
111
112/// An application- or library-defined event, carried by [`Event::Custom`].
113///
114/// The payload is any `'static` value; receivers read it back with [`CustomEvent::payload`], which
115/// returns `None` for any other type.  Pushrod never looks inside a custom event, and it has no
116/// side effects on focus, mouse capture, selection, or redrawing.
117///
118/// # Examples
119///
120/// ```rust
121/// use pushrod::event::{CustomEvent, EventTarget};
122/// use std::rc::Rc;
123///
124/// struct Saved(u32);
125///
126/// let event = CustomEvent {
127///     source: None,
128///     target: EventTarget::Broadcast,
129///     payload: Rc::new(Saved(3)),
130/// };
131///
132/// assert_eq!(event.payload::<Saved>().unwrap().0, 3);
133/// assert!(event.payload::<String>().is_none());
134/// ```
135#[derive(Clone)]
136pub struct CustomEvent {
137    /// The `Widget` that posted the event, or `None` if the application or another thread did.
138    pub source: Option<WidgetId>,
139    /// Which `Widget`s receive the event.
140    pub target: EventTarget,
141    /// The application's data.
142    pub payload: Rc<dyn Any>,
143}
144
145impl CustomEvent {
146    /// Reads the payload as a `T`.
147    ///
148    /// # Returns
149    ///
150    /// The payload, or `None` if it is not a `T`.
151    pub fn payload<T: Any>(&self) -> Option<&T> {
152        self.payload.downcast_ref::<T>()
153    }
154}
155
156impl fmt::Debug for CustomEvent {
157    /// Formats the source and target; the payload is opaque, so it is not shown.
158    ///
159    /// # Arguments
160    ///
161    /// * `f` - The formatter.
162    ///
163    /// # Returns
164    ///
165    /// The formatting result.
166    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167        f.debug_struct("CustomEvent")
168            .field("source", &self.source)
169            .field("target", &self.target)
170            .finish_non_exhaustive()
171    }
172}
173
174/// A set of event classes, used to filter events for the run loop and for each `Widget`.
175///
176/// An event is handled only when its class is in both the run loop's mask
177/// ([`Engine::set_event_mask`](crate::engine::Engine::set_event_mask)) and the receiving
178/// `Widget`'s mask ([`Widget::event_mask`](crate::widget::Widget::event_mask)).  Combine classes
179/// with `|`.
180///
181/// # Examples
182///
183/// ```rust
184/// use pushrod::event::EventMask;
185///
186/// let mask = EventMask::POINTER_BUTTONS | EventMask::KEYBOARD;
187///
188/// assert!(mask.contains(EventMask::KEYBOARD));
189/// assert!(!mask.contains(EventMask::SCROLL));
190/// assert!(EventMask::ALL.contains(mask));
191/// ```
192#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
193pub struct EventMask(u16);
194
195impl EventMask {
196    /// No classes: nothing is delivered.
197    pub const NONE: EventMask = EventMask(0);
198    /// Mouse button presses and releases ([`Event::PointerPressed`], [`Event::PointerReleased`]).
199    pub const POINTER_BUTTONS: EventMask = EventMask(1);
200    /// Pointer movement ([`Event::PointerMoved`]).
201    pub const POINTER_MOTION: EventMask = EventMask(1 << 1);
202    /// The pointer entering or leaving a `Widget` ([`Event::PointerEntered`], [`Event::PointerExited`]).
203    pub const HOVER: EventMask = EventMask(1 << 2);
204    /// Scroll wheel and trackpad scrolling ([`Event::Scrolled`]).
205    pub const SCROLL: EventMask = EventMask(1 << 3);
206    /// Key presses and releases ([`Event::KeyPressed`], [`Event::KeyReleased`]).
207    pub const KEYBOARD: EventMask = EventMask(1 << 4);
208    /// Text input ([`Event::TextEntered`]).
209    pub const TEXT: EventMask = EventMask(1 << 5);
210    /// Keyboard focus changes ([`Event::FocusGained`], [`Event::FocusLost`]).
211    pub const FOCUS: EventMask = EventMask(1 << 6);
212    /// Window events ([`Event::WindowResized`], [`Event::WindowFocusChanged`]).
213    pub const WINDOW: EventMask = EventMask(1 << 7);
214    /// `Widget` lifecycle and layout changes ([`Event::Shown`], [`Event::Resized`], [`Event::Removed`], ...).
215    pub const LIFECYCLE: EventMask = EventMask(1 << 8);
216    /// Timer ticks ([`Event::Tick`]).  Without it the run loop blocks while idle.
217    pub const TIMER: EventMask = EventMask(1 << 9);
218    /// Custom events ([`Event::Custom`]) and backend wake-ups.
219    pub const CUSTOM: EventMask = EventMask(1 << 10);
220    /// Engine events ([`Event::Engine`]).  A `Widget` receives them only with this class in its mask.
221    pub const ENGINE: EventMask = EventMask(1 << 11);
222    /// Every class.
223    pub const ALL: EventMask = EventMask((1 << 12) - 1);
224
225    /// Returns whether every class in `other` is in this mask.
226    ///
227    /// # Arguments
228    ///
229    /// * `other` - The classes to look for.
230    ///
231    /// # Returns
232    ///
233    /// `true` if all of `other`'s classes are present.
234    pub fn contains(self, other: EventMask) -> bool {
235        self.0 & other.0 == other.0
236    }
237
238    /// Returns whether this mask and `other` share at least one class.
239    ///
240    /// # Arguments
241    ///
242    /// * `other` - The classes to compare with.
243    ///
244    /// # Returns
245    ///
246    /// `true` if any class is in both.
247    pub fn intersects(self, other: EventMask) -> bool {
248        self.0 & other.0 != 0
249    }
250
251    /// Returns whether the mask holds no classes.
252    ///
253    /// # Returns
254    ///
255    /// `true` for [`EventMask::NONE`].
256    pub fn is_empty(self) -> bool {
257        self.0 == 0
258    }
259}
260
261impl std::ops::BitOr for EventMask {
262    type Output = EventMask;
263
264    /// Returns the union of two masks.
265    ///
266    /// # Arguments
267    ///
268    /// * `rhs` - The classes to add.
269    ///
270    /// # Returns
271    ///
272    /// A mask with the classes of both.
273    fn bitor(self, rhs: EventMask) -> EventMask {
274        EventMask(self.0 | rhs.0)
275    }
276}
277
278impl std::ops::BitAnd for EventMask {
279    type Output = EventMask;
280
281    /// Returns the classes present in both masks.
282    ///
283    /// # Arguments
284    ///
285    /// * `rhs` - The classes to keep.
286    ///
287    /// # Returns
288    ///
289    /// A mask with only the classes in both.
290    fn bitand(self, rhs: EventMask) -> EventMask {
291        EventMask(self.0 & rhs.0)
292    }
293}
294
295impl std::ops::Not for EventMask {
296    type Output = EventMask;
297
298    /// Returns every class not in the mask.
299    ///
300    /// # Returns
301    ///
302    /// The complement of the mask within [`EventMask::ALL`].
303    fn not(self) -> EventMask {
304        EventMask(!self.0 & EventMask::ALL.0)
305    }
306}
307
308/// What an event mask belongs to, in [`EngineEvent::EventMaskChanged`].
309#[derive(Debug, Clone, Copy, PartialEq, Eq)]
310pub enum MaskScope {
311    /// The run loop's mask.
312    RunLoop,
313    /// The mask of one `Widget`.
314    Widget(WidgetId),
315}
316
317/// The kind of an [`EngineEvent`], without its data.  Used to filter which engine events a
318/// `Widget` or callback receives.
319#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
320#[non_exhaustive]
321pub enum EngineEventKind {
322    /// See [`EngineEvent::EventMaskChanged`].
323    EventMaskChanged,
324    /// See [`EngineEvent::WidgetAdded`].
325    WidgetAdded,
326    /// See [`EngineEvent::EventBroadcast`].
327    EventBroadcast,
328    /// See [`EngineEvent::CustomEventDropped`].
329    CustomEventDropped,
330    /// See [`EngineEvent::FontLoaded`].
331    FontLoaded,
332    /// See [`EngineEvent::GlyphAtlasPageAdded`].
333    GlyphAtlasPageAdded,
334    /// See [`EngineEvent::FocusChanged`].
335    FocusChanged,
336    /// See [`EngineEvent::ActionTriggered`].
337    ActionTriggered,
338    /// See [`EngineEvent::TimerFired`].
339    TimerFired,
340    /// See [`EngineEvent::TimerCancelled`].
341    TimerCancelled,
342    /// See [`EngineEvent::IdleRan`].
343    IdleRan,
344    /// See [`EngineEvent::AnimationTicked`].
345    AnimationTicked,
346    /// See [`EngineEvent::Error`].
347    Error,
348}
349
350/// An action Pushrod performs internally, carried by [`Event::Engine`].
351///
352/// Engine events are broadcast after the action has completed, to `Widget`s whose mask includes
353/// [`EventMask::ENGINE`], then to `Engine::on_engine_event` callbacks and `Engine::on_event`
354/// callbacks.  They never cause further internal actions by themselves, so they cannot loop.
355///
356/// **Rule for contributors:** any change that adds an internal action must add a variant here and
357/// emit it.  More variants are added as the engine gains the actions.
358#[derive(Debug, Clone, PartialEq, Eq)]
359#[non_exhaustive]
360pub enum EngineEvent {
361    /// A `Widget` was added to the window.  Not emitted for the root `Widget`.
362    WidgetAdded {
363        /// The ID of the new `Widget`.
364        id: WidgetId,
365        /// The ID of its parent.
366        parent: WidgetId,
367    },
368    /// An event mask changed.
369    EventMaskChanged {
370        /// Whose mask changed.
371        scope: MaskScope,
372        /// The mask before the change.
373        old: EventMask,
374        /// The mask after the change.
375        new: EventMask,
376    },
377    /// An event was broadcast to every interested `Widget`.
378    EventBroadcast {
379        /// The kind of the broadcast event.
380        kind: EventKind,
381        /// How many `Widget`s received it.
382        recipients: usize,
383    },
384    /// A custom event was discarded because the per-frame limit on custom events was reached,
385    /// which stops callbacks that re-post forever.
386    CustomEventDropped {
387        /// The target of the discarded event.
388        target: EventTarget,
389    },
390    /// A font was loaded from disk, the first time text was drawn with it.  Each
391    /// `(font_name, font_size, style)` loads once per process run.
392    FontLoaded {
393        /// The path of the font file.
394        font_name: String,
395        /// The font size in points.
396        font_size: u16,
397    },
398    /// A glyph atlas texture was created because the existing ones were full (or none existed).
399    GlyphAtlasPageAdded {
400        /// How many atlas textures exist now.
401        pages: usize,
402    },
403    /// The keyboard focus moved, by a click, Tab, an arrow key, or `set_focus`.
404    FocusChanged {
405        /// The `Widget` that had focus, if any.
406        old: Option<WidgetId>,
407        /// The `Widget` that has focus now, if any.
408        new: Option<WidgetId>,
409    },
410    /// Return or Escape activated a form's default or cancel `Widget`.
411    ActionTriggered {
412        /// The `Widget` that was activated.
413        id: WidgetId,
414        /// `false` for the default action (Return), `true` for the cancel action (Escape).
415        cancel: bool,
416    },
417    /// A timer registered with `Engine::on_timer` fired and its callback ran.
418    TimerFired {
419        /// The timer that fired.
420        id: TimerId,
421        /// `true` if it repeats; `false` if this was its only firing.
422        repeat: bool,
423    },
424    /// A timer was cancelled before it fired again, by `Ui::cancel_timer` or
425    /// `Engine::cancel_timer`.  Not sent when a one-shot timer simply finishes.
426    TimerCancelled {
427        /// The timer that was cancelled.
428        id: TimerId,
429    },
430    /// The idle callbacks ran because no events were pending.
431    IdleRan {
432        /// How many idle callbacks ran.
433        callbacks: usize,
434    },
435    /// [`Event::Tick`] was delivered to the `Widget`s that requested animation.
436    AnimationTicked {
437        /// How many `Widget`s received the tick.
438        recipients: usize,
439        /// The time since the previous frame's tick.
440        elapsed: Duration,
441    },
442    /// An operation failed while the run loop was running (a font that would not load, a texture
443    /// the driver could not create).  The loop keeps running; the failed drawing is skipped.
444    Error {
445        /// What failed.
446        error: Error,
447    },
448}
449
450impl EngineEvent {
451    /// Returns the kind of this engine event, for filtering.
452    ///
453    /// # Returns
454    ///
455    /// The [`EngineEventKind`] matching the variant.
456    pub fn kind(&self) -> EngineEventKind {
457        match self {
458            EngineEvent::EventMaskChanged { .. } => EngineEventKind::EventMaskChanged,
459            EngineEvent::WidgetAdded { .. } => EngineEventKind::WidgetAdded,
460            EngineEvent::EventBroadcast { .. } => EngineEventKind::EventBroadcast,
461            EngineEvent::CustomEventDropped { .. } => EngineEventKind::CustomEventDropped,
462            EngineEvent::FontLoaded { .. } => EngineEventKind::FontLoaded,
463            EngineEvent::GlyphAtlasPageAdded { .. } => EngineEventKind::GlyphAtlasPageAdded,
464            EngineEvent::FocusChanged { .. } => EngineEventKind::FocusChanged,
465            EngineEvent::ActionTriggered { .. } => EngineEventKind::ActionTriggered,
466            EngineEvent::TimerFired { .. } => EngineEventKind::TimerFired,
467            EngineEvent::TimerCancelled { .. } => EngineEventKind::TimerCancelled,
468            EngineEvent::IdleRan { .. } => EngineEventKind::IdleRan,
469            EngineEvent::AnimationTicked { .. } => EngineEventKind::AnimationTicked,
470            EngineEvent::Error { .. } => EngineEventKind::Error,
471        }
472    }
473}
474
475/// Returns whether an engine event passes an optional kind filter.
476///
477/// # Arguments
478///
479/// * `filter` - The accepted kinds, or `None` to accept every kind.
480/// * `event` - The engine event.
481///
482/// # Returns
483///
484/// `true` if there is no filter or the filter lists the event's kind.
485pub fn engine_filter_accepts(filter: Option<&[EngineEventKind]>, event: &EngineEvent) -> bool {
486    filter.is_none_or(|kinds| kinds.contains(&event.kind()))
487}
488
489/// The kind of an [`Event`], without its data.  Used by masks and the callback registry.
490#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
491pub enum EventKind {
492    /// See [`Event::PointerEntered`].
493    PointerEntered,
494    /// See [`Event::PointerExited`].
495    PointerExited,
496    /// See [`Event::PointerMoved`].
497    PointerMoved,
498    /// See [`Event::PointerPressed`].
499    PointerPressed,
500    /// See [`Event::PointerReleased`].
501    PointerReleased,
502    /// See [`Event::Clicked`].
503    Clicked,
504    /// See [`Event::Scrolled`].
505    Scrolled,
506    /// See [`Event::KeyPressed`].
507    KeyPressed,
508    /// See [`Event::KeyReleased`].
509    KeyReleased,
510    /// See [`Event::TextEntered`].
511    TextEntered,
512    /// See [`Event::FocusGained`].
513    FocusGained,
514    /// See [`Event::FocusLost`].
515    FocusLost,
516    /// See [`Event::Activated`].
517    Activated,
518    /// See [`Event::Toggled`].
519    Toggled,
520    /// See [`Event::ValueChanged`].
521    ValueChanged,
522    /// See [`Event::SelectionChanged`].
523    SelectionChanged,
524    /// See [`Event::TextChanged`].
525    TextChanged,
526    /// See [`Event::EditingFinished`].
527    EditingFinished,
528    /// See [`Event::Triggered`].
529    Triggered,
530    /// See [`Event::ContextMenuRequested`].
531    ContextMenuRequested,
532    /// See [`Event::PropertyChanged`].
533    PropertyChanged,
534    /// See [`Event::ViewportChanged`].
535    ViewportChanged,
536    /// See [`Event::Shown`].
537    Shown,
538    /// See [`Event::Hidden`].
539    Hidden,
540    /// See [`Event::Resized`].
541    Resized,
542    /// See [`Event::Moved`].
543    Moved,
544    /// See [`Event::Removed`].
545    Removed,
546    /// See [`Event::WindowResized`].
547    WindowResized,
548    /// See [`Event::WindowFocusChanged`].
549    WindowFocusChanged,
550    /// See [`Event::CloseRequested`].
551    CloseRequested,
552    /// See [`Event::Tick`].
553    Tick,
554    /// See [`Event::Engine`].
555    Engine,
556    /// See [`Event::Custom`].
557    Custom,
558}
559
560impl EventKind {
561    /// Returns the mask class this kind of event is filtered by.
562    ///
563    /// # Returns
564    ///
565    /// The class, or `None` when the event is never filtered: close requests, engine events, and
566    /// the events `Widget`s generate for the application (`Clicked`, `Activated`, ...).
567    pub fn mask_class(self) -> Option<EventMask> {
568        use EventKind as K;
569
570        match self {
571            K::PointerPressed | K::PointerReleased => Some(EventMask::POINTER_BUTTONS),
572            K::PointerMoved => Some(EventMask::POINTER_MOTION),
573            K::PointerEntered | K::PointerExited => Some(EventMask::HOVER),
574            K::Scrolled => Some(EventMask::SCROLL),
575            K::KeyPressed | K::KeyReleased => Some(EventMask::KEYBOARD),
576            K::TextEntered => Some(EventMask::TEXT),
577            K::FocusGained | K::FocusLost => Some(EventMask::FOCUS),
578            K::WindowResized | K::WindowFocusChanged => Some(EventMask::WINDOW),
579            K::PropertyChanged
580            | K::ViewportChanged
581            | K::Shown
582            | K::Hidden
583            | K::Resized
584            | K::Moved
585            | K::Removed => Some(EventMask::LIFECYCLE),
586            K::Tick => Some(EventMask::TIMER),
587            K::Custom => Some(EventMask::CUSTOM),
588            K::Clicked
589            | K::Activated
590            | K::Toggled
591            | K::ValueChanged
592            | K::SelectionChanged
593            | K::TextChanged
594            | K::EditingFinished
595            | K::Triggered
596            | K::ContextMenuRequested
597            | K::CloseRequested
598            | K::Engine => None,
599        }
600    }
601}
602
603impl EventKind {
604    /// Returns `true` if events of this kind travel through the capture, target, and bubble
605    /// phases.
606    ///
607    /// Pointer presses, releases, motion, scrolls, key presses and releases, and text input
608    /// propagate.  Hover (`PointerEntered`, `PointerExited`) belongs to one `Widget`, and semantic
609    /// events (`Clicked`, `ValueChanged`, ...) go to callbacks, so neither propagates.
610    ///
611    /// # Returns
612    ///
613    /// `true` if the event propagates.
614    pub fn propagates(self) -> bool {
615        matches!(
616            self,
617            EventKind::PointerPressed
618                | EventKind::PointerReleased
619                | EventKind::PointerMoved
620                | EventKind::Scrolled
621                | EventKind::KeyPressed
622                | EventKind::KeyReleased
623                | EventKind::TextEntered
624        )
625    }
626}
627
628/// An event generated by Pushrod or by a `Widget`.
629///
630/// `Widget`s receive these in [`Widget::handle_event`](crate::widget::Widget::handle_event), and
631/// applications receive the ones `Widget`s emit through callbacks or
632/// [`Engine::next_event`](crate::engine::Engine::next_event).  Positions are in window
633/// coordinates.
634#[derive(Debug, Clone)]
635pub enum Event {
636    // ---- Pointer ----
637    /// The pointer moved onto widget `id`.
638    PointerEntered {
639        /// The widget the pointer entered.
640        id: WidgetId,
641    },
642    /// The pointer moved off widget `id`.
643    PointerExited {
644        /// The widget the pointer left.
645        id: WidgetId,
646    },
647    /// The pointer moved.  Sent to the capturing widget, or the one under the pointer.
648    PointerMoved {
649        /// The widget receiving the motion.
650        id: WidgetId,
651        /// The pointer position.
652        position: Point,
653    },
654    /// A mouse button went down over widget `id`.
655    PointerPressed {
656        /// The widget under the pointer.
657        id: WidgetId,
658        /// The button that went down.
659        button: MouseButton,
660        /// The pointer position.
661        position: Point,
662        /// The click count (1 single, 2 double).
663        count: u8,
664    },
665    /// A mouse button went up.  Sent to the widget that captured the press.
666    PointerReleased {
667        /// The widget receiving the release.
668        id: WidgetId,
669        /// The button that went up.
670        button: MouseButton,
671        /// The pointer position.
672        position: Point,
673        /// The click count (1 single, 2 double).
674        count: u8,
675    },
676    /// Widget `id` was clicked.
677    Clicked {
678        /// The widget that was clicked.
679        id: WidgetId,
680        /// The button used.
681        button: MouseButton,
682        /// The click count (1 single, 2 double).
683        count: u8,
684    },
685    /// The wheel or trackpad scrolled over widget `id`.
686    Scrolled {
687        /// The widget under the pointer.
688        id: WidgetId,
689        /// How far it scrolled, horizontally (`x`) and vertically (`y`).
690        delta: Point,
691    },
692
693    // ---- Keyboard ----
694    /// A key went down (or repeated) while widget `id` had the keyboard.
695    KeyPressed {
696        /// The widget with the keyboard.
697        id: WidgetId,
698        /// The key.
699        key: Key,
700        /// The modifier keys held.
701        modifiers: Modifiers,
702        /// `true` if this is an auto-repeat.
703        repeat: bool,
704    },
705    /// A key went up while widget `id` had the keyboard.
706    KeyReleased {
707        /// The widget with the keyboard.
708        id: WidgetId,
709        /// The key.
710        key: Key,
711        /// The modifier keys held.
712        modifiers: Modifiers,
713    },
714    /// Text was typed into widget `id`.
715    TextEntered {
716        /// The widget with the keyboard.
717        id: WidgetId,
718        /// The text typed.
719        text: String,
720    },
721
722    // ---- Focus ----
723    /// Widget `id` became the keyboard focus.
724    FocusGained {
725        /// The widget that gained focus.
726        id: WidgetId,
727    },
728    /// Widget `id` stopped being the keyboard focus.
729    FocusLost {
730        /// The widget that lost focus.
731        id: WidgetId,
732    },
733
734    // ---- Semantic (emitted by widgets) ----
735    /// Widget `id` was activated.
736    Activated {
737        /// The widget activated.
738        id: WidgetId,
739    },
740    /// Widget `id` was toggled.
741    Toggled {
742        /// The widget toggled.
743        id: WidgetId,
744        /// The new state.
745        checked: bool,
746    },
747    /// The value of widget `id` changed.
748    ValueChanged {
749        /// The widget whose value changed.
750        id: WidgetId,
751    },
752    /// The selection of widget `id` changed.
753    SelectionChanged {
754        /// The widget whose selection changed.
755        id: WidgetId,
756    },
757    /// The text of widget `id` changed.
758    TextChanged {
759        /// The widget whose text changed.
760        id: WidgetId,
761    },
762    /// Editing in widget `id` finished.
763    EditingFinished {
764        /// The widget that was edited.
765        id: WidgetId,
766    },
767    /// A named action was triggered by widget `id`.
768    Triggered {
769        /// The widget that triggered it.
770        id: WidgetId,
771        /// The action name.
772        action: String,
773    },
774    /// A context menu was requested at `position` over widget `id`.
775    ContextMenuRequested {
776        /// The widget under the pointer.
777        id: WidgetId,
778        /// Where the menu was requested.
779        position: Point,
780    },
781    /// A property of widget `id` changed.
782    PropertyChanged {
783        /// The widget whose property changed.
784        id: WidgetId,
785        /// The property name.
786        name: String,
787    },
788    /// The visible area of scrolling widget `id` moved.
789    ViewportChanged {
790        /// The scrolling widget.
791        id: WidgetId,
792        /// The new scroll offset.
793        offset: Point,
794    },
795
796    // ---- Lifecycle ----
797    /// Widget `id` became visible.
798    Shown {
799        /// The widget shown.
800        id: WidgetId,
801    },
802    /// Widget `id` became hidden.
803    Hidden {
804        /// The widget hidden.
805        id: WidgetId,
806    },
807    /// Widget `id` changed size.
808    Resized {
809        /// The widget resized.
810        id: WidgetId,
811        /// Its new size.
812        size: Size,
813    },
814    /// Widget `id` changed origin.
815    Moved {
816        /// The widget moved.
817        id: WidgetId,
818        /// Its new origin.
819        origin: Point,
820    },
821    /// Widget `id` was removed from the tree.
822    Removed {
823        /// The widget removed.
824        id: WidgetId,
825    },
826
827    // ---- Window ----
828    /// The window changed size.
829    WindowResized {
830        /// The new window size.
831        size: Size,
832    },
833    /// The window gained or lost focus.
834    WindowFocusChanged {
835        /// `true` if the window now has focus.
836        focused: bool,
837    },
838    /// The user asked to close the window.
839    CloseRequested,
840
841    // ---- Time ----
842    /// A frame passed while a widget animates.
843    Tick {
844        /// The time since the previous tick.
845        elapsed: Duration,
846    },
847
848    // ---- Engine / extension ----
849    /// An action Pushrod performed internally.
850    Engine(EngineEvent),
851    /// An application- or library-defined event.
852    Custom(CustomEvent),
853}
854
855impl Event {
856    /// Reads the payload of a custom event as a `T`.
857    ///
858    /// # Returns
859    ///
860    /// The payload, or `None` if this is not [`Event::Custom`] or the payload is not a `T`.
861    pub fn payload<T: Any>(&self) -> Option<&T> {
862        match self {
863            Event::Custom(custom) => custom.payload::<T>(),
864            _ => None,
865        }
866    }
867
868    /// The widget a widget-addressed event is for.
869    ///
870    /// # Returns
871    ///
872    /// The `WidgetId`, or `None` for window-level, engine, custom and raw events.
873    pub fn widget_id(&self) -> Option<WidgetId> {
874        match self {
875            Event::PointerEntered { id }
876            | Event::PointerExited { id }
877            | Event::PointerMoved { id, .. }
878            | Event::PointerPressed { id, .. }
879            | Event::PointerReleased { id, .. }
880            | Event::Clicked { id, .. }
881            | Event::KeyPressed { id, .. }
882            | Event::FocusGained { id }
883            | Event::FocusLost { id }
884            | Event::Activated { id }
885            | Event::Toggled { id, .. }
886            | Event::ValueChanged { id }
887            | Event::SelectionChanged { id }
888            | Event::TextChanged { id }
889            | Event::EditingFinished { id }
890            | Event::ViewportChanged { id, .. } => Some(*id),
891            _ => None,
892        }
893    }
894
895    /// Returns the kind of this event, without its data.
896    ///
897    /// # Returns
898    ///
899    /// The matching [`EventKind`].
900    pub fn kind(&self) -> EventKind {
901        match self {
902            Event::PointerEntered { .. } => EventKind::PointerEntered,
903            Event::PointerExited { .. } => EventKind::PointerExited,
904            Event::PointerMoved { .. } => EventKind::PointerMoved,
905            Event::PointerPressed { .. } => EventKind::PointerPressed,
906            Event::PointerReleased { .. } => EventKind::PointerReleased,
907            Event::Clicked { .. } => EventKind::Clicked,
908            Event::Scrolled { .. } => EventKind::Scrolled,
909            Event::KeyPressed { .. } => EventKind::KeyPressed,
910            Event::KeyReleased { .. } => EventKind::KeyReleased,
911            Event::TextEntered { .. } => EventKind::TextEntered,
912            Event::FocusGained { .. } => EventKind::FocusGained,
913            Event::FocusLost { .. } => EventKind::FocusLost,
914            Event::Activated { .. } => EventKind::Activated,
915            Event::Toggled { .. } => EventKind::Toggled,
916            Event::ValueChanged { .. } => EventKind::ValueChanged,
917            Event::SelectionChanged { .. } => EventKind::SelectionChanged,
918            Event::TextChanged { .. } => EventKind::TextChanged,
919            Event::EditingFinished { .. } => EventKind::EditingFinished,
920            Event::Triggered { .. } => EventKind::Triggered,
921            Event::ContextMenuRequested { .. } => EventKind::ContextMenuRequested,
922            Event::PropertyChanged { .. } => EventKind::PropertyChanged,
923            Event::ViewportChanged { .. } => EventKind::ViewportChanged,
924            Event::Shown { .. } => EventKind::Shown,
925            Event::Hidden { .. } => EventKind::Hidden,
926            Event::Resized { .. } => EventKind::Resized,
927            Event::Moved { .. } => EventKind::Moved,
928            Event::Removed { .. } => EventKind::Removed,
929            Event::WindowResized { .. } => EventKind::WindowResized,
930            Event::WindowFocusChanged { .. } => EventKind::WindowFocusChanged,
931            Event::CloseRequested => EventKind::CloseRequested,
932            Event::Tick { .. } => EventKind::Tick,
933            Event::Engine(_) => EventKind::Engine,
934            Event::Custom(_) => EventKind::Custom,
935        }
936    }
937
938    /// Returns the widget this event concerns, if any.
939    ///
940    /// Window, time, engine, custom, and raw events concern no single widget.
941    ///
942    /// # Returns
943    ///
944    /// The `WidgetId`, or `None`.
945    pub fn widget(&self) -> Option<WidgetId> {
946        match self {
947            Event::PointerEntered { id }
948            | Event::PointerExited { id }
949            | Event::PointerMoved { id, .. }
950            | Event::PointerPressed { id, .. }
951            | Event::PointerReleased { id, .. }
952            | Event::Clicked { id, .. }
953            | Event::Scrolled { id, .. }
954            | Event::KeyPressed { id, .. }
955            | Event::KeyReleased { id, .. }
956            | Event::TextEntered { id, .. }
957            | Event::FocusGained { id }
958            | Event::FocusLost { id }
959            | Event::Activated { id }
960            | Event::Toggled { id, .. }
961            | Event::ValueChanged { id }
962            | Event::SelectionChanged { id }
963            | Event::TextChanged { id }
964            | Event::EditingFinished { id }
965            | Event::Triggered { id, .. }
966            | Event::ContextMenuRequested { id, .. }
967            | Event::PropertyChanged { id, .. }
968            | Event::ViewportChanged { id, .. }
969            | Event::Shown { id }
970            | Event::Hidden { id }
971            | Event::Resized { id, .. }
972            | Event::Moved { id, .. }
973            | Event::Removed { id } => Some(*id),
974            Event::WindowResized { .. }
975            | Event::WindowFocusChanged { .. }
976            | Event::CloseRequested
977            | Event::Tick { .. }
978            | Event::Engine(_)
979            | Event::Custom(_) => None,
980        }
981    }
982}
983
984#[cfg(test)]
985mod tests {
986    use super::*;
987    use crate::geometry::point;
988
989    fn sample_custom() -> CustomEvent {
990        CustomEvent {
991            source: None,
992            target: EventTarget::ApplicationOnly,
993            payload: Rc::new(7_u32),
994        }
995    }
996
997    #[test]
998    fn kind_matches_variant() {
999        assert_eq!(
1000            Event::PointerEntered { id: 1 }.kind(),
1001            EventKind::PointerEntered
1002        );
1003        assert_eq!(Event::CloseRequested.kind(), EventKind::CloseRequested);
1004        assert_eq!(Event::Custom(sample_custom()).kind(), EventKind::Custom);
1005        assert_eq!(
1006            Event::Tick {
1007                elapsed: Duration::from_millis(16)
1008            }
1009            .kind(),
1010            EventKind::Tick
1011        );
1012    }
1013
1014    #[test]
1015    fn widget_returns_the_target_or_none() {
1016        let clicked = Event::Clicked {
1017            id: 7,
1018            button: MouseButton::Left,
1019            count: 2,
1020        };
1021        let moved = Event::PointerMoved {
1022            id: 3,
1023            position: point(1, 2),
1024        };
1025
1026        assert_eq!(clicked.widget(), Some(7));
1027        assert_eq!(moved.widget(), Some(3));
1028        assert_eq!(Event::CloseRequested.widget(), None);
1029        assert_eq!(Event::WindowFocusChanged { focused: true }.widget(), None);
1030        assert_eq!(Event::Custom(sample_custom()).widget(), None);
1031    }
1032
1033    #[test]
1034    fn ctx_returns_events_in_order() {
1035        let mut ctx = EventCtx::default();
1036
1037        ctx.emit(Event::FocusLost { id: 1 });
1038        ctx.emit(Event::FocusGained { id: 2 });
1039
1040        let kinds: Vec<_> = ctx.into_events().iter().map(Event::kind).collect();
1041
1042        assert_eq!(kinds, vec![EventKind::FocusLost, EventKind::FocusGained]);
1043    }
1044}
1045
1046/// What a `Widget` tells the `WidgetCache` after handling an input event: keep delivering it, or
1047/// stop.
1048///
1049/// Returned by [`Widget::handle_event`](crate::widget::Widget::handle_event).  Input events
1050/// (pointer presses, releases, motion, scrolls, keys, and text) travel through three phases, see
1051/// [`EventPhase`]; returning `Stop` ends delivery, so no later `Widget` sees the event.  Events that
1052/// do not propagate ignore the value.
1053#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1054pub enum Propagation {
1055    /// The event was not consumed; deliver it to the next `Widget` in the path.
1056    #[default]
1057    Continue,
1058    /// The event was consumed; end delivery.
1059    Stop,
1060}
1061
1062/// The phase of delivery an input event is in when a `Widget` receives it.
1063///
1064/// Delivery runs **capture** from the root down to the target's parent (only `Widget`s whose
1065/// [`handles_capture`](crate::widget::Widget::handles_capture) is `true`), then **target**, then
1066/// **bubble** from the target's parent up to the root.  Read it with [`EventCtx::phase`].
1067#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1068pub enum EventPhase {
1069    /// The root-to-parent pass, before the target sees the event.
1070    Capture,
1071    /// The `Widget` the event is for: under the pointer, capturing the mouse, or focused.
1072    #[default]
1073    Target,
1074    /// The parent-to-root pass, after the target ignored the event.
1075    Bubble,
1076}
1077
1078/// The context passed to [`Widget::handle_event`](crate::widget::Widget::handle_event).
1079///
1080/// `Widget`s use it to queue the events they generate.  Queueing, instead of calling application
1081/// code from inside the `Widget`, lets callbacks later receive mutable access to both the
1082/// application state and every `Widget`.
1083#[derive(Default)]
1084pub struct EventCtx {
1085    events: Vec<Event>,
1086    source: Option<WidgetId>,
1087    phase: EventPhase,
1088    animating: Vec<WidgetId>,
1089}
1090
1091impl EventCtx {
1092    /// Queues an event generated by a `Widget`.
1093    ///
1094    /// Queued events are delivered to the application in the order in which they were emitted.
1095    ///
1096    /// # Arguments
1097    ///
1098    /// * `event` - The event to queue, such as `Event::Clicked { id, button, count }`.
1099    pub fn emit(&mut self, event: Event) {
1100        self.events.push(event);
1101    }
1102
1103    /// Posts a custom event, with the `Widget` currently handling an event as its source.
1104    ///
1105    /// The event is queued behind the events already waiting and delivered later, in order, never
1106    /// from inside this call.  See [`CustomEvent`].
1107    ///
1108    /// # Arguments
1109    ///
1110    /// * `target` - Which `Widget`s receive the event.
1111    /// * `payload` - The application's data; receivers read it with [`Event::payload`].
1112    pub fn post<T: Any>(&mut self, target: EventTarget, payload: T) {
1113        self.events.push(Event::Custom(CustomEvent {
1114            source: self.source,
1115            target,
1116            payload: Rc::new(payload),
1117        }));
1118    }
1119
1120    /// Asks for an [`Event::Tick`] on the next frame, for the `Widget` currently handling an event.
1121    ///
1122    /// The request is for one frame, like a browser's `requestAnimationFrame`: a `Widget` that
1123    /// keeps animating calls this again each time it handles a `Tick`, and stops by not calling
1124    /// it.  Only `Widget`s with [`EventMask::TIMER`] in their mask receive the tick.  Does nothing
1125    /// outside event handling.
1126    pub fn request_animation(&mut self) {
1127        if let Some(id) = self.source {
1128            self.animating.push(id);
1129        }
1130    }
1131
1132    /// Takes the animation requests made through [`EventCtx::request_animation`].
1133    ///
1134    /// # Returns
1135    ///
1136    /// The requesting `Widget`s, in the order they asked.
1137    pub(crate) fn take_animation_requests(&mut self) -> Vec<WidgetId> {
1138        std::mem::take(&mut self.animating)
1139    }
1140
1141    /// Returns the phase of delivery the current event is in.
1142    ///
1143    /// # Returns
1144    ///
1145    /// [`EventPhase::Target`] unless the event is being captured or bubbled.
1146    pub fn phase(&self) -> EventPhase {
1147        self.phase
1148    }
1149
1150    /// Records the phase of delivery for the event about to be handled.
1151    ///
1152    /// # Arguments
1153    ///
1154    /// * `phase` - The phase.
1155    pub(crate) fn set_phase(&mut self, phase: EventPhase) {
1156        self.phase = phase;
1157    }
1158
1159    /// Records which `Widget` is handling an event, so [`EventCtx::post`] can name it as the source.
1160    ///
1161    /// # Arguments
1162    ///
1163    /// * `source` - The `Widget` about to receive an event.
1164    pub(crate) fn set_source(&mut self, source: Option<WidgetId>) {
1165        self.source = source;
1166    }
1167
1168    /// Consumes the context and returns the queued events.
1169    ///
1170    /// # Returns
1171    ///
1172    /// The queued events, in the order emitted.
1173    pub fn into_events(self) -> Vec<Event> {
1174        self.events
1175    }
1176}
1177
1178#[cfg(test)]
1179mod mask_tests {
1180    use super::*;
1181
1182    #[test]
1183    fn masks_combine_and_compare() {
1184        let mask = EventMask::HOVER | EventMask::SCROLL;
1185
1186        assert!(mask.contains(EventMask::HOVER));
1187        assert!(!mask.contains(EventMask::HOVER | EventMask::KEYBOARD));
1188        assert!(mask.intersects(EventMask::HOVER | EventMask::KEYBOARD));
1189        assert!((mask & EventMask::HOVER) == EventMask::HOVER);
1190        assert!(EventMask::NONE.is_empty());
1191        assert_eq!(!EventMask::NONE, EventMask::ALL);
1192        assert_eq!(!EventMask::ALL, EventMask::NONE);
1193        assert_eq!(EventMask::default(), EventMask::NONE);
1194    }
1195
1196    #[test]
1197    fn input_kinds_have_a_class_and_outputs_and_close_have_none() {
1198        assert_eq!(
1199            EventKind::PointerMoved.mask_class(),
1200            Some(EventMask::POINTER_MOTION)
1201        );
1202        assert_eq!(EventKind::Tick.mask_class(), Some(EventMask::TIMER));
1203        assert_eq!(EventKind::Custom.mask_class(), Some(EventMask::CUSTOM));
1204        assert_eq!(EventKind::CloseRequested.mask_class(), None);
1205        assert_eq!(EventKind::Engine.mask_class(), None);
1206        assert_eq!(EventKind::Clicked.mask_class(), None);
1207    }
1208
1209    #[test]
1210    fn only_input_kinds_propagate() {
1211        assert!(EventKind::PointerPressed.propagates());
1212        assert!(EventKind::KeyPressed.propagates());
1213        assert!(EventKind::TextEntered.propagates());
1214        assert!(!EventKind::PointerEntered.propagates());
1215        assert!(!EventKind::Clicked.propagates());
1216        assert!(!EventKind::ValueChanged.propagates());
1217    }
1218
1219    #[test]
1220    fn engine_class_is_part_of_all() {
1221        assert!(EventMask::ALL.contains(EventMask::ENGINE));
1222        assert!(!(EventMask::ALL & !EventMask::ENGINE).intersects(EventMask::ENGINE));
1223    }
1224
1225    #[test]
1226    fn error_engine_events_have_their_own_kind() {
1227        let failed = EngineEvent::Error {
1228            error: Error::font("missing.ttf", "No such file"),
1229        };
1230
1231        assert_eq!(failed.kind(), EngineEventKind::Error);
1232        assert!(engine_filter_accepts(
1233            Some(&[EngineEventKind::Error]),
1234            &failed
1235        ));
1236        assert!(!engine_filter_accepts(
1237            Some(&[EngineEventKind::FontLoaded]),
1238            &failed
1239        ));
1240    }
1241
1242    #[test]
1243    fn engine_events_report_kind_and_filter() {
1244        let added = EngineEvent::WidgetAdded { id: 1, parent: 0 };
1245
1246        assert_eq!(added.kind(), EngineEventKind::WidgetAdded);
1247        assert!(engine_filter_accepts(None, &added));
1248        assert!(engine_filter_accepts(
1249            Some(&[EngineEventKind::WidgetAdded]),
1250            &added
1251        ));
1252        assert!(!engine_filter_accepts(
1253            Some(&[EngineEventKind::EventMaskChanged]),
1254            &added
1255        ));
1256    }
1257}