pushrod/engine.rs
1// Engine
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//! # Engine
17//!
18//! This is the run loop processor that enables `Pushrod` to open a new window, layout the `Widget`s
19//! in the display, and handle the `Event` loop.
20//!
21//! The event loop processes input in order of receipt from the [`Backend`], which polls the
22//! window system for [`InputEvent`]s. The events are sent to the
23//! `WidgetCache`, which routes them to the `Widget`s. Any `Event`s generated by the
24//! `Widget`s are queued, and then delivered to the callbacks registered on the `Engine`.
25//!
26//! The `Engine` owns an application state object of any type `S`. Callbacks receive mutable
27//! access to that state, and to the `Widget`s through a [`Ui`] handle, in the style of Visual
28//! Basic event procedures:
29//!
30//! The example uses the standard widgets from the `pushrod-widgets` crate; the core itself
31//! contains no widgets other than the window's [`RootWidget`].
32//!
33//! ```rust,ignore
34//! use pushrod::engine::Engine;
35//! use pushrod::geometry::{point, size};
36//! use pushrod_widgets::button_widget::ButtonWidget;
37//! use pushrod_widgets::text_widget::{TextJustify, TextWidget};
38//! use pushrod::color::{Color, FontStyle};
39//!
40//! #[derive(Default)]
41//! struct AppState {
42//! clicks: u32,
43//! }
44//!
45//! let mut engine: Engine<AppState> = Engine::new(size(400, 200), 30);
46//!
47//! let font = String::from("assets/OpenSans-Regular.ttf");
48//! let label = engine.add_widget(TextWidget::new(point(20, 20), size(200, 20), font.clone(),
49//! FontStyle::NORMAL, 14, Color::BLACK, TextJustify::Left, String::from("Not clicked")));
50//! let button = engine.add_widget(ButtonWidget::new(point(20, 60), size(120, 20), font,
51//! FontStyle::NORMAL, 14, Color::BLACK, TextJustify::Center, String::from("Click me"), 2));
52//!
53//! engine.on_click(button, move |state, ui| {
54//! state.clicks += 1;
55//! ui.get_mut::<TextWidget>(label)
56//! .unwrap()
57//! .set_text(format!("Clicked {} times", state.clicks));
58//! });
59//!
60//! pushrod_sdl2::run(engine, pushrod_sdl2::WindowSettings::new("app", size(400, 200)), AppState::default());
61//! ```
62
63use crate::backend::{Backend, Waker};
64use crate::cache::WidgetCache;
65use crate::color::Color;
66use crate::error::Result;
67use crate::event::{
68 CustomEvent, EngineEvent, EngineEventKind, Event, EventKind, EventMask, EventTarget, MaskScope,
69 engine_filter_accepts,
70};
71use crate::geometry::{Point, Size};
72use crate::input::{InputEvent, Key, Modifiers};
73use crate::root_widget::RootWidget;
74use crate::timer::TimerSchedule;
75use crate::widget::{Widget, WidgetId};
76use std::any::Any;
77use std::cell::RefCell;
78use std::collections::{HashMap, VecDeque};
79use std::rc::Rc;
80use std::sync::{Arc, Mutex};
81use std::thread::sleep;
82use std::time::{Duration, Instant};
83
84/// How long an idle loop blocks waiting for an event before checking again, in milliseconds.
85const IDLE_WAIT_MS: u32 = 1000;
86
87pub use crate::timer::TimerId;
88
89/// The most custom events delivered in one frame; the rest are discarded, which stops callbacks
90/// that post a custom event in response to a custom event forever.
91pub const MAX_CUSTOM_EVENTS_PER_FRAME: usize = 1000;
92
93/// A posted payload waiting for the UI thread: the target and the `Send` data.
94type Posted = (EventTarget, Box<dyn Any + Send>);
95
96/// The mailbox shared by an [`Engine`] and its [`Sender`]s.
97#[derive(Default)]
98struct Mailbox {
99 queue: Mutex<Vec<Posted>>,
100 wake: Mutex<Option<Waker>>,
101}
102
103/// A handle other threads use to post custom events to the UI thread.
104///
105/// Get one with [`Engine::sender`]; clone it freely and move it into threads. Posting is
106/// thread-safe: the payload is queued and the run loop is woken, then delivers it on the UI thread
107/// as an [`Event::Custom`] with no source.
108///
109/// # Examples
110///
111/// ```rust
112/// use pushrod::engine::Engine;
113/// use pushrod::event::EventTarget;
114/// use pushrod::geometry::size;
115///
116/// struct Progress(u8);
117///
118/// let engine: Engine = Engine::new(size(320, 200), 30);
119/// let sender = engine.sender();
120///
121/// std::thread::spawn(move || sender.post(EventTarget::ApplicationOnly, Progress(40)))
122/// .join()
123/// .unwrap();
124/// ```
125#[derive(Clone)]
126pub struct Sender {
127 mailbox: Arc<Mailbox>,
128}
129
130impl Sender {
131 /// Posts a custom event from any thread.
132 ///
133 /// # Arguments
134 ///
135 /// * `target` - Which `Widget`s receive the event.
136 /// * `payload` - The data; it must be `Send` because it crosses threads.
137 pub fn post<T: Any + Send>(&self, target: EventTarget, payload: T) {
138 if let Ok(mut queue) = self.mailbox.queue.lock() {
139 queue.push((target, Box::new(payload)));
140 }
141
142 // Wake the run loop so it does not wait for the next input event. A backend that cannot
143 // be woken is harmless: the mailbox is also drained every frame.
144 if let Ok(wake) = self.mailbox.wake.lock()
145 && let Some(waker) = wake.as_ref()
146 {
147 waker();
148 }
149 }
150}
151
152/// Stores a new run-loop mask, tells the widget tree, and queues `EventMaskChanged` if it changed.
153///
154/// # Arguments
155///
156/// * `current` - The stored mask.
157/// * `widgets` - The widget tree, which also filters by the run-loop mask.
158/// * `mask` - The new mask.
159fn set_loop_mask(current: &mut EventMask, widgets: &mut WidgetCache, mask: EventMask) {
160 if *current == mask {
161 return;
162 }
163
164 let old = *current;
165
166 *current = mask;
167 widgets.set_loop_mask(mask);
168 widgets.queue_event(Event::Engine(EngineEvent::EventMaskChanged {
169 scope: MaskScope::RunLoop,
170 old,
171 new: mask,
172 }));
173}
174
175/// A handle identifying one registered callback, returned by every `on_*` registration method.
176///
177/// IDs are unique within an [`Engine`] and are never reused.
178#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
179pub struct CallbackId(pub u64);
180
181/// A callback stored in the registry; typed `on_*` methods wrap their closure into this form.
182type RegistryCallback<S> = Box<dyn FnMut(&mut S, &mut Ui, &Event)>;
183
184/// The registry: callbacks per `(widget, event kind)`, in registration order.
185type Registry<S> = HashMap<(WidgetId, EventKind), Vec<(CallbackId, RegistryCallback<S>)>>;
186
187/// A callback that receives every event the `Widget`s generate.
188///
189/// It receives the application state, a [`Ui`] handle for reaching the `Widget`s, and the event.
190/// Register one with [`Engine::on_event`].
191pub type EventCallback<S> = Box<dyn FnMut(&mut S, &mut Ui, &Event)>;
192
193/// A callback that receives the engine events Pushrod emits after its internal actions.
194///
195/// It receives the application state, a [`Ui`] handle, and the engine event. Register one with
196/// [`Engine::on_engine_event`] or [`Engine::on_engine_event_filtered`].
197pub type EngineEventCallback<S> = Box<dyn FnMut(&mut S, &mut Ui, &EngineEvent)>;
198
199/// A callback run by a timer; see [`Engine::on_timer`].
200type TimerCallback<S> = Box<dyn FnMut(&mut S, &mut Ui)>;
201
202/// A callback run when the loop is idle; see [`Engine::on_idle`].
203type IdleCallback<S> = Box<dyn FnMut(&mut S, &mut Ui)>;
204
205/// A callback for custom events carrying one payload type; see [`Engine::on_custom`].
206type CustomCallback<S> = Box<dyn FnMut(&mut S, &mut Ui, &CustomEvent)>;
207
208/// The handle passed to callbacks.
209///
210/// It gives callbacks access to the `Widget`s in the window, by ID and concrete type, and lets
211/// them stop the `Engine`. It borrows the `Engine`'s widget tree only for the duration of the
212/// callback.
213pub struct Ui<'a> {
214 widgets: &'a mut WidgetCache,
215 running: &'a mut bool,
216 event_mask: &'a mut EventMask,
217 posted: &'a mut Vec<Event>,
218 timers: &'a mut TimerSchedule,
219}
220
221impl<'a> Ui<'a> {
222 /// Cancels a timer started with [`Engine::on_timer`].
223 ///
224 /// Safe to call from any callback, including the timer's own: a timer cancelled while the
225 /// timers due this frame are running does not fire afterwards. Emits
226 /// [`EngineEvent::TimerCancelled`] when a waiting timer was stopped.
227 ///
228 /// # Arguments
229 ///
230 /// * `id` - The timer to cancel.
231 ///
232 /// # Returns
233 ///
234 /// `true` if the timer was still scheduled; `false` if it was a one-shot that already fired,
235 /// or was already cancelled.
236 pub fn cancel_timer(&mut self, id: TimerId) -> bool {
237 let cancelled = self.timers.cancel(id);
238
239 if cancelled {
240 self.widgets
241 .queue_event(Event::Engine(EngineEvent::TimerCancelled { id }));
242 }
243
244 cancelled
245 }
246
247 /// Asks for an [`Event::Tick`] for a `Widget` on the next frame. See
248 /// [`WidgetCache::request_animation`].
249 ///
250 /// # Arguments
251 ///
252 /// * `id` - The `Widget` to tick.
253 pub fn request_animation(&mut self, id: WidgetId) {
254 self.widgets.request_animation(id);
255 }
256
257 /// Posts a custom event, to be delivered after the callbacks currently running.
258 ///
259 /// The event is queued, never delivered from inside this call. Posting from a custom-event
260 /// callback is allowed; at most [`MAX_CUSTOM_EVENTS_PER_FRAME`] custom events are delivered per
261 /// frame, and the rest are discarded with an [`EngineEvent::CustomEventDropped`].
262 ///
263 /// # Arguments
264 ///
265 /// * `target` - Which `Widget`s receive the event.
266 /// * `payload` - The application's data; receivers read it with [`Event::payload`].
267 pub fn post<T: Any>(&mut self, target: EventTarget, payload: T) {
268 self.posted.push(Event::Custom(CustomEvent {
269 source: None,
270 target,
271 payload: Rc::new(payload),
272 }));
273 }
274
275 /// Changes the run loop's event mask. See [`Engine::set_event_mask`].
276 ///
277 /// # Arguments
278 ///
279 /// * `mask` - The new mask; it applies from the next event.
280 pub fn set_event_mask(&mut self, mask: EventMask) {
281 set_loop_mask(self.event_mask, self.widgets, mask);
282 }
283
284 /// Changes a `Widget`'s event mask. See [`WidgetCache::set_event_mask`].
285 ///
286 /// # Arguments
287 ///
288 /// * `id` - The ID of the `Widget`.
289 /// * `mask` - The new mask.
290 pub fn set_widget_event_mask(&mut self, id: WidgetId, mask: EventMask) {
291 self.widgets.set_event_mask(id, mask);
292 }
293
294 /// Retrieves a `Widget` by ID as its concrete type.
295 ///
296 /// # Arguments
297 ///
298 /// * `id` - The ID of the `Widget`.
299 ///
300 /// # Returns
301 ///
302 /// The `Widget` as a `T`, or `None` if the ID does not exist or the `Widget` is not a `T`.
303 pub fn get<T: Widget>(&self, id: WidgetId) -> Option<&T> {
304 self.widgets.get_as::<T>(id)
305 }
306
307 /// Retrieves a `Widget` by ID as its concrete type, for modification.
308 ///
309 /// # Arguments
310 ///
311 /// * `id` - The ID of the `Widget`.
312 ///
313 /// # Returns
314 ///
315 /// The `Widget` as a mutable `T`, or `None` if the ID does not exist or the `Widget` is not a `T`.
316 pub fn get_mut<T: Widget>(&mut self, id: WidgetId) -> Option<&mut T> {
317 self.widgets.get_as_mut::<T>(id)
318 }
319
320 /// Returns the window's widget tree.
321 ///
322 /// Use it to add `Widget`s from a callback, or to reach a `Widget` without knowing its concrete
323 /// type.
324 ///
325 /// # Returns
326 ///
327 /// The [`WidgetCache`] holding every `Widget` in the window.
328 pub fn widgets(&mut self) -> &mut WidgetCache {
329 self.widgets
330 }
331
332 /// Gives the keyboard focus to a `Widget`. See [`WidgetCache::set_focus`].
333 ///
334 /// # Arguments
335 ///
336 /// * `id` - The ID of the `Widget`.
337 ///
338 /// # Returns
339 ///
340 /// `true` if the `Widget` has focus afterward; `false` if it cannot take focus.
341 pub fn set_focus(&mut self, id: WidgetId) -> bool {
342 self.widgets.set_focus(id)
343 }
344
345 /// Returns the `Widget` that has the keyboard focus.
346 ///
347 /// # Returns
348 ///
349 /// The ID of the focused `Widget`, or `None` if nothing has focus.
350 pub fn focused(&self) -> Option<WidgetId> {
351 self.widgets.focused()
352 }
353
354 /// Stops the `Engine`.
355 ///
356 /// The run loop finishes the current batch of events, then returns the application state from
357 /// [`Engine::run`]; in the event-loop style, [`Engine::next_event`] returns `None`.
358 pub fn shutdown(&mut self) {
359 *self.running = false;
360 }
361}
362
363/// The run loop: owns the window's widget tree, routes input to `Widget`s, calls the application's
364/// callbacks, and draws.
365///
366/// `S` is the application state type. [`Engine::run`] takes ownership of a value of `S`, passes
367/// it to every callback, and returns it when the `Engine` stops. Applications that prefer their
368/// own loop use [`Engine::event_loop`] and [`Engine::next_event`] instead of callbacks.
369pub struct Engine<S = ()> {
370 frame_rate: u32,
371 size: Size,
372 running: bool,
373 widget_cache: WidgetCache,
374 event_mask: EventMask,
375 registry: Registry<S>,
376 next_callback_id: u64,
377 event_callbacks: Vec<EventCallback<S>>,
378 engine_callbacks: Vec<(Option<Vec<EngineEventKind>>, EngineEventCallback<S>)>,
379 custom_callbacks: Vec<CustomCallback<S>>,
380 posted: Vec<Event>,
381 mailbox: Arc<Mailbox>,
382 custom_budget: usize,
383 text_input_active: bool,
384 text_input_pending: Option<bool>,
385 timers: TimerSchedule,
386 timer_callbacks: HashMap<TimerId, TimerCallback<S>>,
387 idle_callbacks: Vec<IdleCallback<S>>,
388 last_tick: Instant,
389}
390
391impl<S> Engine<S> {
392 /// Creates an `Engine` for a window of the given size.
393 ///
394 /// A white [`RootWidget`] is created as `Widget` `0` and fills the window.
395 ///
396 /// # Arguments
397 ///
398 /// * `size` - The size of the window in pixels.
399 /// * `frame_rate` - The maximum number of frames drawn per second (for example `30` or `60`).
400 /// `0` is treated as `1`.
401 ///
402 /// # Returns
403 ///
404 /// A new `Engine` with no `Widget`s other than the root, and no callbacks.
405 pub fn new(size: Size, frame_rate: u32) -> Self {
406 let mut widget_cache = WidgetCache::default();
407 widget_cache.add(Box::new(RootWidget::new(Size::new(size.w, size.h))));
408
409 Self {
410 frame_rate,
411 size,
412 running: true,
413 widget_cache,
414 event_mask: EventMask::ALL,
415 registry: HashMap::new(),
416 next_callback_id: 0,
417 event_callbacks: Vec::new(),
418 engine_callbacks: Vec::new(),
419 custom_callbacks: Vec::new(),
420 posted: Vec::new(),
421 mailbox: Arc::new(Mailbox::default()),
422 custom_budget: MAX_CUSTOM_EVENTS_PER_FRAME,
423 text_input_active: false,
424 text_input_pending: None,
425 timers: TimerSchedule::default(),
426 timer_callbacks: HashMap::new(),
427 idle_callbacks: Vec::new(),
428 last_tick: Instant::now(),
429 }
430 }
431
432 /// Stops the `Engine`.
433 ///
434 /// The run loop exits after the current batch of events; in the event-loop style,
435 /// [`Engine::next_event`] returns `None`.
436 pub fn shutdown(&mut self) {
437 self.running = false;
438 }
439
440 /// Sets the run loop's event mask.
441 ///
442 /// Events whose class is not in the mask are dropped before routing and callbacks, and the
443 /// backend is told the mask so it can stop delivering the rest. Close requests are always delivered. The change applies from the next event
444 /// and emits [`EngineEvent::EventMaskChanged`] with [`MaskScope::RunLoop`].
445 ///
446 /// With [`EventMask::TIMER`] left out and nothing to repaint, the loop blocks waiting for
447 /// input instead of polling, so an idle application uses almost no CPU.
448 ///
449 /// # Arguments
450 ///
451 /// * `mask` - The classes of events to handle. The default is [`EventMask::ALL`].
452 ///
453 /// # Examples
454 ///
455 /// ```rust
456 /// use pushrod::engine::Engine;
457 /// use pushrod::event::EventMask;
458 /// use pushrod::geometry::size;
459 ///
460 /// let mut engine: Engine = Engine::new(size(320, 200), 60);
461 ///
462 /// // No hover effects: stop pointer motion at the source.
463 /// engine.set_event_mask(EventMask::ALL & !EventMask::POINTER_MOTION & !EventMask::HOVER);
464 ///
465 /// assert!(!engine.event_mask().contains(EventMask::HOVER));
466 /// ```
467 pub fn set_event_mask(&mut self, mask: EventMask) {
468 set_loop_mask(&mut self.event_mask, &mut self.widget_cache, mask);
469 }
470
471 /// Returns the run loop's event mask.
472 ///
473 /// # Returns
474 ///
475 /// The mask set with [`Engine::set_event_mask`]; [`EventMask::ALL`] by default.
476 pub fn event_mask(&self) -> EventMask {
477 self.event_mask
478 }
479
480 /// Returns whether the run loop can block waiting for input: nothing needs repainting, timer
481 /// events are masked out, and no idle callbacks want to run.
482 fn is_idle(&self) -> bool {
483 !self.event_mask.intersects(EventMask::TIMER)
484 && !self.widget_cache.needs_draw()
485 && self.idle_callbacks.is_empty()
486 }
487
488 /// Returns how long an idle loop may block waiting for input: [`IDLE_WAIT_MS`], or less when
489 /// a timer is due sooner, so timers still fire on time while the loop sleeps.
490 ///
491 /// # Arguments
492 ///
493 /// * `now` - The current time.
494 ///
495 /// # Returns
496 ///
497 /// The wait in milliseconds.
498 fn idle_wait_ms(&self, now: Instant) -> u32 {
499 match self.timers.next_wait(now) {
500 Some(wait) => (wait.as_micros().div_ceil(1000) as u32).min(IDLE_WAIT_MS),
501 None => IDLE_WAIT_MS,
502 }
503 }
504
505 /// Starts a timer.
506 ///
507 /// The callback runs from the run loop (or [`Engine::next_event_with`]) once `interval` has
508 /// passed, within one frame of it. A repeating timer runs again every `interval`; if the
509 /// application falls behind it runs once and keeps its rhythm instead of catching up in a
510 /// burst. Each firing emits [`EngineEvent::TimerFired`]. The callback receives the
511 /// application state and a [`Ui`]; call [`Ui::cancel_timer`] to stop a timer, even from its
512 /// own callback.
513 ///
514 /// # Arguments
515 ///
516 /// * `interval` - The time until the timer fires, and between firings if it repeats.
517 /// * `repeat` - `true` to fire every `interval`; `false` to fire once.
518 /// * `callback` - Runs each time the timer fires.
519 ///
520 /// # Returns
521 ///
522 /// The timer's [`TimerId`], for cancelling it.
523 ///
524 /// # Examples
525 ///
526 /// ```rust
527 /// use pushrod::engine::Engine;
528 /// use pushrod::geometry::size;
529 /// use std::time::Duration;
530 ///
531 /// let mut engine: Engine<u32> = Engine::new(size(320, 200), 60);
532 ///
533 /// // Counts seconds; the application reads the count from its state.
534 /// let clock = engine.on_timer(Duration::from_secs(1), true, |seconds, _ui| *seconds += 1);
535 ///
536 /// assert!(engine.cancel_timer(clock));
537 /// ```
538 pub fn on_timer<F>(&mut self, interval: Duration, repeat: bool, callback: F) -> TimerId
539 where
540 F: FnMut(&mut S, &mut Ui) + 'static,
541 {
542 let id = self.timers.add(Instant::now(), interval, repeat);
543
544 self.timer_callbacks.insert(id, Box::new(callback));
545
546 id
547 }
548
549 /// Cancels a timer started with [`Engine::on_timer`]. Emits [`EngineEvent::TimerCancelled`]
550 /// when a waiting timer was stopped.
551 ///
552 /// # Arguments
553 ///
554 /// * `id` - The timer to cancel.
555 ///
556 /// # Returns
557 ///
558 /// `true` if the timer was still scheduled.
559 pub fn cancel_timer(&mut self, id: TimerId) -> bool {
560 let cancelled = self.timers.cancel(id);
561
562 if cancelled {
563 self.timer_callbacks.remove(&id);
564 self.widget_cache
565 .queue_event(Event::Engine(EngineEvent::TimerCancelled { id }));
566 }
567
568 cancelled
569 }
570
571 /// Registers a callback that runs when the loop is idle: once per loop iteration in which no
572 /// events were waiting. Use it for work that should yield to input, such as deferred layout
573 /// or incremental loading. While any idle callback is registered the loop polls once per
574 /// frame instead of blocking, so keep the callback short. Each run emits
575 /// [`EngineEvent::IdleRan`].
576 ///
577 /// # Arguments
578 ///
579 /// * `callback` - Receives the application state and a [`Ui`].
580 ///
581 /// # Examples
582 ///
583 /// ```rust
584 /// use pushrod::engine::Engine;
585 /// use pushrod::geometry::size;
586 ///
587 /// let mut engine: Engine<Vec<u32>> = Engine::new(size(320, 200), 60);
588 ///
589 /// // Loads one item per idle iteration.
590 /// engine.on_idle(|loaded, _ui| loaded.push(loaded.len() as u32));
591 /// ```
592 pub fn on_idle<F>(&mut self, callback: F)
593 where
594 F: FnMut(&mut S, &mut Ui) + 'static,
595 {
596 self.idle_callbacks.push(Box::new(callback));
597 }
598
599 /// Runs the timers that are due at `now`, in due order. Events they cause are queued, not
600 /// delivered.
601 ///
602 /// # Arguments
603 ///
604 /// * `now` - The current time.
605 /// * `state` - The application state passed to the callbacks.
606 fn run_due_timers(&mut self, now: Instant, state: &mut S) {
607 for id in self.timers.due(now) {
608 // Skip a timer an earlier callback cancelled in this same pass.
609 let Some(repeat) = self.timers.complete(id, now) else {
610 continue;
611 };
612
613 self.widget_cache
614 .queue_event(Event::Engine(EngineEvent::TimerFired { id, repeat }));
615
616 let Some(mut callback) = self.timer_callbacks.remove(&id) else {
617 continue;
618 };
619 let mut ui = Ui {
620 widgets: &mut self.widget_cache,
621 running: &mut self.running,
622 event_mask: &mut self.event_mask,
623 posted: &mut self.posted,
624 timers: &mut self.timers,
625 };
626
627 callback(state, &mut ui);
628
629 if repeat && self.timers.contains(id) {
630 self.timer_callbacks.insert(id, callback);
631 }
632 }
633
634 let timers = &self.timers;
635
636 self.timer_callbacks.retain(|id, _| timers.contains(*id));
637 }
638
639 /// Runs the idle callbacks, if there are any. Queues [`EngineEvent::IdleRan`].
640 ///
641 /// # Arguments
642 ///
643 /// * `state` - The application state passed to the callbacks.
644 fn run_idle_callbacks(&mut self, state: &mut S) {
645 if self.idle_callbacks.is_empty() {
646 return;
647 }
648
649 let mut ui = Ui {
650 widgets: &mut self.widget_cache,
651 running: &mut self.running,
652 event_mask: &mut self.event_mask,
653 posted: &mut self.posted,
654 timers: &mut self.timers,
655 };
656
657 for callback in self.idle_callbacks.iter_mut() {
658 callback(state, &mut ui);
659 }
660
661 let callbacks = self.idle_callbacks.len();
662
663 self.widget_cache
664 .queue_event(Event::Engine(EngineEvent::IdleRan { callbacks }));
665 }
666
667 /// Delivers [`Event::Tick`] to the `Widget`s that requested animation, measuring the time
668 /// since the previous call.
669 ///
670 /// # Arguments
671 ///
672 /// * `now` - The current time.
673 ///
674 /// # Returns
675 ///
676 /// The events the `Widget`s generated while handling the tick.
677 fn tick_widgets(&mut self, now: Instant) -> Vec<Event> {
678 let elapsed = now.saturating_duration_since(self.last_tick);
679
680 self.last_tick = now;
681
682 let generated = self.widget_cache.tick(elapsed);
683
684 self.expand_custom(generated)
685 }
686
687 /// Advances the engine's clock to `now`: runs the timers that are due, then delivers one
688 /// [`Event::Tick`] to the `Widget`s that requested animation, and delivers everything they
689 /// cause to the callbacks. [`Engine::run`] calls this once per frame; call it directly to
690 /// test an application's timers headless, with times of your own choosing.
691 ///
692 /// # Arguments
693 ///
694 /// * `now` - The current time.
695 /// * `state` - The application state passed to the callbacks.
696 pub fn advance(&mut self, now: Instant, state: &mut S) {
697 self.custom_budget = MAX_CUSTOM_EVENTS_PER_FRAME;
698 self.run_due_timers(now, state);
699
700 for event in self.tick_widgets(now) {
701 self.fire(&event, state);
702 }
703
704 self.flush_pending(state);
705 }
706
707 /// Runs the idle callbacks and delivers the events they cause. [`Engine::run`] calls this
708 /// when a frame had no events to process; call it directly to test idle callbacks headless.
709 ///
710 /// # Arguments
711 ///
712 /// * `state` - The application state passed to the callbacks.
713 pub fn run_idle(&mut self, state: &mut S) {
714 self.custom_budget = MAX_CUSTOM_EVENTS_PER_FRAME;
715 self.run_idle_callbacks(state);
716 self.flush_pending(state);
717 }
718
719 /// Takes the engine events queued by internal actions and broadcasts each to the `Widget`s
720 /// that want it.
721 ///
722 /// # Returns
723 ///
724 /// Each engine event followed by the events the `Widget`s generated in response, in order.
725 fn drain_pending(&mut self) -> Vec<Event> {
726 self.sync_text_input();
727
728 let mut drained = Vec::new();
729 let mut posted = std::mem::take(&mut self.posted);
730
731 if let Ok(mut queue) = self.mailbox.queue.lock() {
732 posted.extend(queue.drain(..).map(|(target, payload)| {
733 let payload: Rc<dyn Any + Send> = Rc::from(payload);
734
735 Event::Custom(CustomEvent {
736 source: None,
737 target,
738 payload,
739 })
740 }));
741 }
742
743 drained.extend(self.expand_custom(posted));
744
745 for event in self.widget_cache.take_pending_events() {
746 let generated = match &event {
747 Event::Engine(engine_event) => {
748 self.widget_cache.broadcast_engine_event(engine_event)
749 }
750 _ => Vec::new(),
751 };
752
753 drained.push(event);
754 drained.extend(self.expand_custom(generated));
755 }
756
757 drained
758 }
759
760 /// Notes when text input should start or stop to match the focused `Widget`: on while a text
761 /// editor has focus, off otherwise. The run loop applies the change to the backend.
762 fn sync_text_input(&mut self) {
763 let wanted = self.widget_cache.text_input_wanted();
764
765 if wanted != self.text_input_active {
766 self.text_input_active = wanted;
767 self.text_input_pending = Some(wanted);
768 }
769 }
770
771 /// Passes changes made since the last call on to the backend: the event mask and text input.
772 ///
773 /// # Arguments
774 ///
775 /// * `backend` - The backend to update.
776 /// * `applied` - The mask the backend is configured for; updated to the current mask.
777 fn sync_backend(&mut self, backend: &mut dyn Backend, applied: &mut EventMask) {
778 if *applied != self.event_mask {
779 backend.set_event_mask(self.event_mask);
780 *applied = self.event_mask;
781 }
782
783 if let Some(active) = self.text_input_pending.take() {
784 backend.set_text_input(active);
785 }
786 }
787
788 /// Delivers every custom event in `events` to its target `Widget`s, in order.
789 ///
790 /// Each custom event is followed in the result by nothing of its own; the events the `Widget`s
791 /// generate while handling it join the back of the queue, so custom events posted during
792 /// delivery are delivered after the ones already waiting. Once the frame's budget of
793 /// [`MAX_CUSTOM_EVENTS_PER_FRAME`] is spent, further custom events are dropped and an
794 /// [`EngineEvent::CustomEventDropped`] is returned in place of each.
795 ///
796 /// # Arguments
797 ///
798 /// * `events` - The events to expand; other kinds pass through unchanged.
799 ///
800 /// # Returns
801 ///
802 /// The events to give the callbacks, in delivery order.
803 fn expand_custom(&mut self, events: Vec<Event>) -> Vec<Event> {
804 let mut out = Vec::with_capacity(events.len());
805 let mut queue: VecDeque<Event> = events.into();
806
807 while let Some(event) = queue.pop_front() {
808 let Event::Custom(custom) = &event else {
809 out.push(event);
810 continue;
811 };
812
813 if self.custom_budget == 0 {
814 out.push(Event::Engine(EngineEvent::CustomEventDropped {
815 target: custom.target,
816 }));
817 continue;
818 }
819
820 self.custom_budget -= 1;
821 queue.extend(self.widget_cache.deliver_custom(custom));
822 out.push(event);
823 }
824
825 out
826 }
827
828 /// Delivers the engine events queued by internal actions to the `Widget`s and callbacks.
829 fn flush_pending(&mut self, state: &mut S) {
830 loop {
831 let pending = self.drain_pending();
832
833 if pending.is_empty() {
834 break;
835 }
836
837 for event in pending {
838 self.fire(&event, state);
839 }
840 }
841 }
842
843 /// Returns whether the `Engine` is running.
844 ///
845 /// # Returns
846 ///
847 /// `true` until the window is closed or [`shutdown`](Engine::shutdown) is called.
848 pub fn is_running(&self) -> bool {
849 self.running
850 }
851
852 /// Adds a `Widget` to the window, as a child of the root `Widget`.
853 ///
854 /// # Arguments
855 ///
856 /// * `widget` - The `Widget` to add. Its origin is relative to the window.
857 ///
858 /// # Returns
859 ///
860 /// The ID assigned to the `Widget`; use it to register callbacks and to reach the `Widget` later.
861 pub fn add_widget<W: Widget>(&mut self, widget: W) -> WidgetId {
862 self.widget_cache.add(Box::new(widget))
863 }
864
865 /// Adds a `Widget` as a child of another `Widget`.
866 ///
867 /// Children move with their parent, are hidden with it, and are drawn on top of it.
868 ///
869 /// # Arguments
870 ///
871 /// * `parent` - The ID of the parent `Widget`.
872 /// * `widget` - The `Widget` to add. Its origin is relative to the parent.
873 ///
874 /// # Returns
875 ///
876 /// The ID assigned to the `Widget`.
877 ///
878 /// # Panics
879 ///
880 /// Panics if `parent` does not exist.
881 pub fn add_child_widget<W: Widget>(&mut self, parent: WidgetId, widget: W) -> WidgetId {
882 self.widget_cache.add_child(parent, Box::new(widget))
883 }
884
885 /// Adds a `Widget` as a child of another, reporting an unknown parent as an error instead of
886 /// panicking. Behaves like [`add_child_widget`](Engine::add_child_widget) otherwise.
887 ///
888 /// # Arguments
889 ///
890 /// * `parent` - The ID of the parent `Widget`.
891 /// * `widget` - The `Widget` to add. Its origin is relative to the parent.
892 ///
893 /// # Returns
894 ///
895 /// The ID assigned to the `Widget`.
896 ///
897 /// # Errors
898 ///
899 /// Returns [`Error::UnknownWidget`](crate::error::Error::UnknownWidget) if `parent` does not exist.
900 pub fn try_add_child_widget<W: Widget>(
901 &mut self,
902 parent: WidgetId,
903 widget: W,
904 ) -> Result<WidgetId> {
905 self.widget_cache.try_add_child(parent, Box::new(widget))
906 }
907
908 /// Returns the window's widget tree.
909 ///
910 /// # Returns
911 ///
912 /// The [`WidgetCache`] holding every `Widget` in the window.
913 pub fn widgets(&mut self) -> &mut WidgetCache {
914 &mut self.widget_cache
915 }
916
917 /// Stores a callback in the registry under `(id, kind)`.
918 ///
919 /// # Returns
920 ///
921 /// The new callback's [`CallbackId`].
922 fn register(
923 &mut self,
924 id: WidgetId,
925 kind: EventKind,
926 callback: RegistryCallback<S>,
927 ) -> CallbackId {
928 let callback_id = CallbackId(self.next_callback_id);
929 self.next_callback_id += 1;
930 self.registry
931 .entry((id, kind))
932 .or_default()
933 .push((callback_id, callback));
934 callback_id
935 }
936
937 /// Registers a callback that runs when a `Widget` is clicked.
938 ///
939 /// Several callbacks may be registered for the same `Widget`; they run in the order registered,
940 /// before any [`on_event`](Engine::on_event) callbacks. Callbacks run with
941 /// [`Engine::run`], [`Engine::dispatch`] and [`Engine::next_event_with`]. Every `on_*`
942 /// method below works the same way: it fires only for its `Widget` and event kind, in
943 /// registration order, after the `Widget` has updated itself.
944 ///
945 /// # Arguments
946 ///
947 /// * `id` - The ID of the `Widget`.
948 /// * `callback` - Called with the application state and a [`Ui`] handle.
949 ///
950 /// # Returns
951 ///
952 /// The [`CallbackId`] of the registered callback.
953 ///
954 /// # Examples
955 ///
956 /// ```rust
957 /// use pushrod::engine::Engine;
958 /// use pushrod::geometry::size;
959 ///
960 /// let mut engine: Engine<u32> = Engine::new(size(320, 200), 30);
961 ///
962 /// engine.on_click(0, |clicks, _ui| *clicks += 1);
963 /// ```
964 pub fn on_click<F>(&mut self, id: WidgetId, mut callback: F) -> CallbackId
965 where
966 F: FnMut(&mut S, &mut Ui) + 'static,
967 {
968 self.register(
969 id,
970 EventKind::Clicked,
971 Box::new(move |s, ui, _| callback(s, ui)),
972 )
973 }
974
975 /// Registers a callback that runs when a mouse button goes down on the `Widget`.
976 ///
977 /// # Arguments
978 ///
979 /// * `id` - The ID of the `Widget`.
980 /// * `callback` - Called with the application state and a [`Ui`] handle.
981 ///
982 /// # Returns
983 ///
984 /// The [`CallbackId`] of the registered callback.
985 pub fn on_press<F>(&mut self, id: WidgetId, mut callback: F) -> CallbackId
986 where
987 F: FnMut(&mut S, &mut Ui) + 'static,
988 {
989 self.register(
990 id,
991 EventKind::PointerPressed,
992 Box::new(move |s, ui, _| callback(s, ui)),
993 )
994 }
995
996 /// Registers a callback that runs when a mouse button goes up, inside or outside the `Widget` (it is sent to the `Widget` that captured the press).
997 ///
998 /// # Arguments
999 ///
1000 /// * `id` - The ID of the `Widget`.
1001 /// * `callback` - Called with the application state and a [`Ui`] handle.
1002 ///
1003 /// # Returns
1004 ///
1005 /// The [`CallbackId`] of the registered callback.
1006 pub fn on_release<F>(&mut self, id: WidgetId, mut callback: F) -> CallbackId
1007 where
1008 F: FnMut(&mut S, &mut Ui) + 'static,
1009 {
1010 self.register(
1011 id,
1012 EventKind::PointerReleased,
1013 Box::new(move |s, ui, _| callback(s, ui)),
1014 )
1015 }
1016
1017 /// Registers a callback that runs when a `Widget` is activated.
1018 ///
1019 /// # Arguments
1020 ///
1021 /// * `id` - The ID of the `Widget`.
1022 /// * `callback` - Called with the application state and a [`Ui`] handle.
1023 ///
1024 /// # Returns
1025 ///
1026 /// The [`CallbackId`] of the registered callback.
1027 pub fn on_activate<F>(&mut self, id: WidgetId, mut callback: F) -> CallbackId
1028 where
1029 F: FnMut(&mut S, &mut Ui) + 'static,
1030 {
1031 self.register(
1032 id,
1033 EventKind::Activated,
1034 Box::new(move |s, ui, _| callback(s, ui)),
1035 )
1036 }
1037
1038 /// Registers a callback that runs when a `Widget`'s value changes.
1039 ///
1040 /// # Arguments
1041 ///
1042 /// * `id` - The ID of the `Widget`.
1043 /// * `callback` - Called with the application state and a [`Ui`] handle.
1044 ///
1045 /// # Returns
1046 ///
1047 /// The [`CallbackId`] of the registered callback.
1048 pub fn on_value_change<F>(&mut self, id: WidgetId, mut callback: F) -> CallbackId
1049 where
1050 F: FnMut(&mut S, &mut Ui) + 'static,
1051 {
1052 self.register(
1053 id,
1054 EventKind::ValueChanged,
1055 Box::new(move |s, ui, _| callback(s, ui)),
1056 )
1057 }
1058
1059 /// Registers a callback that runs when a `Widget`'s selection changes.
1060 ///
1061 /// # Arguments
1062 ///
1063 /// * `id` - The ID of the `Widget`.
1064 /// * `callback` - Called with the application state and a [`Ui`] handle.
1065 ///
1066 /// # Returns
1067 ///
1068 /// The [`CallbackId`] of the registered callback.
1069 pub fn on_selection_change<F>(&mut self, id: WidgetId, mut callback: F) -> CallbackId
1070 where
1071 F: FnMut(&mut S, &mut Ui) + 'static,
1072 {
1073 self.register(
1074 id,
1075 EventKind::SelectionChanged,
1076 Box::new(move |s, ui, _| callback(s, ui)),
1077 )
1078 }
1079
1080 /// Registers a callback that runs when a `Widget`'s text changes.
1081 ///
1082 /// # Arguments
1083 ///
1084 /// * `id` - The ID of the `Widget`.
1085 /// * `callback` - Called with the application state and a [`Ui`] handle.
1086 ///
1087 /// # Returns
1088 ///
1089 /// The [`CallbackId`] of the registered callback.
1090 pub fn on_text_change<F>(&mut self, id: WidgetId, mut callback: F) -> CallbackId
1091 where
1092 F: FnMut(&mut S, &mut Ui) + 'static,
1093 {
1094 self.register(
1095 id,
1096 EventKind::TextChanged,
1097 Box::new(move |s, ui, _| callback(s, ui)),
1098 )
1099 }
1100
1101 /// Registers a callback that runs when editing in a `Widget` finishes.
1102 ///
1103 /// # Arguments
1104 ///
1105 /// * `id` - The ID of the `Widget`.
1106 /// * `callback` - Called with the application state and a [`Ui`] handle.
1107 ///
1108 /// # Returns
1109 ///
1110 /// The [`CallbackId`] of the registered callback.
1111 pub fn on_editing_finished<F>(&mut self, id: WidgetId, mut callback: F) -> CallbackId
1112 where
1113 F: FnMut(&mut S, &mut Ui) + 'static,
1114 {
1115 self.register(
1116 id,
1117 EventKind::EditingFinished,
1118 Box::new(move |s, ui, _| callback(s, ui)),
1119 )
1120 }
1121
1122 /// Registers a callback that runs when a `Widget` is toggled.
1123 ///
1124 /// # Arguments
1125 ///
1126 /// * `id` - The ID of the `Widget`.
1127 /// * `callback` - Called with the application state, a [`Ui`] handle, and the new `checked` state.
1128 ///
1129 /// # Returns
1130 ///
1131 /// The [`CallbackId`] of the registered callback.
1132 pub fn on_toggle<F>(&mut self, id: WidgetId, mut callback: F) -> CallbackId
1133 where
1134 F: FnMut(&mut S, &mut Ui, bool) + 'static,
1135 {
1136 self.register(
1137 id,
1138 EventKind::Toggled,
1139 Box::new(move |s, ui, event| {
1140 if let Event::Toggled { checked, .. } = event {
1141 callback(s, ui, *checked);
1142 }
1143 }),
1144 )
1145 }
1146
1147 /// Registers a callback that runs when a scrolling `Widget`'s visible area moves.
1148 ///
1149 /// # Arguments
1150 ///
1151 /// * `id` - The ID of the `Widget`.
1152 /// * `callback` - Called with the application state, a [`Ui`] handle, and the new scroll offset.
1153 ///
1154 /// # Returns
1155 ///
1156 /// The [`CallbackId`] of the registered callback.
1157 pub fn on_viewport_change<F>(&mut self, id: WidgetId, mut callback: F) -> CallbackId
1158 where
1159 F: FnMut(&mut S, &mut Ui, Point) + 'static,
1160 {
1161 self.register(
1162 id,
1163 EventKind::ViewportChanged,
1164 Box::new(move |s, ui, event| {
1165 if let Event::ViewportChanged { offset, .. } = event {
1166 callback(s, ui, *offset);
1167 }
1168 }),
1169 )
1170 }
1171
1172 /// Registers a callback that runs when a key goes down (or repeats) while the `Widget` has the keyboard.
1173 ///
1174 /// # Arguments
1175 ///
1176 /// * `id` - The ID of the `Widget`.
1177 /// * `callback` - Called with the application state, a [`Ui`] handle, the key, and the modifiers held.
1178 ///
1179 /// # Returns
1180 ///
1181 /// The [`CallbackId`] of the registered callback.
1182 pub fn on_key_press<F>(&mut self, id: WidgetId, mut callback: F) -> CallbackId
1183 where
1184 F: FnMut(&mut S, &mut Ui, Key, Modifiers) + 'static,
1185 {
1186 self.register(
1187 id,
1188 EventKind::KeyPressed,
1189 Box::new(move |s, ui, event| {
1190 if let Event::KeyPressed { key, modifiers, .. } = event {
1191 callback(s, ui, *key, *modifiers);
1192 }
1193 }),
1194 )
1195 }
1196
1197 /// Registers a callback that runs when a `Widget` gains or loses keyboard focus.
1198 ///
1199 /// # Arguments
1200 ///
1201 /// * `id` - The ID of the `Widget`.
1202 /// * `callback` - Called with the application state, a [`Ui`] handle, and `true` if focus was gained.
1203 ///
1204 /// # Returns
1205 ///
1206 /// The [`CallbackId`] of the registered callback.
1207 pub fn on_focus_change<F>(&mut self, id: WidgetId, callback: F) -> CallbackId
1208 where
1209 F: FnMut(&mut S, &mut Ui, bool) + 'static,
1210 {
1211 self.register_pair(id, EventKind::FocusGained, EventKind::FocusLost, callback)
1212 }
1213
1214 /// Registers a callback that runs when the pointer enters or leaves a `Widget`.
1215 ///
1216 /// # Arguments
1217 ///
1218 /// * `id` - The ID of the `Widget`.
1219 /// * `callback` - Called with the application state, a [`Ui`] handle, and `true` if the pointer is inside.
1220 ///
1221 /// # Returns
1222 ///
1223 /// The [`CallbackId`] of the registered callback.
1224 pub fn on_hover<F>(&mut self, id: WidgetId, callback: F) -> CallbackId
1225 where
1226 F: FnMut(&mut S, &mut Ui, bool) + 'static,
1227 {
1228 self.register_pair(
1229 id,
1230 EventKind::PointerEntered,
1231 EventKind::PointerExited,
1232 callback,
1233 )
1234 }
1235
1236 /// Registers one callback for an "on" kind (passes `true`) and an "off" kind (passes `false`).
1237 fn register_pair<F>(
1238 &mut self,
1239 id: WidgetId,
1240 on: EventKind,
1241 off: EventKind,
1242 callback: F,
1243 ) -> CallbackId
1244 where
1245 F: FnMut(&mut S, &mut Ui, bool) + 'static,
1246 {
1247 let shared = Rc::new(RefCell::new(callback));
1248 let on_shared = shared.clone();
1249 let callback_id = self.register(
1250 id,
1251 on,
1252 Box::new(move |s, ui, _| (on_shared.borrow_mut())(s, ui, true)),
1253 );
1254 self.registry.entry((id, off)).or_default().push((
1255 callback_id,
1256 Box::new(move |s, ui, _| (shared.borrow_mut())(s, ui, false)),
1257 ));
1258 callback_id
1259 }
1260
1261 /// Registers a callback that receives every event the `Widget`s generate.
1262 ///
1263 /// These callbacks run after the `Widget`-specific callbacks for the same event, in the order
1264 /// registered.
1265 ///
1266 /// # Arguments
1267 ///
1268 /// * `callback` - Called with the application state, a [`Ui`] handle, and the event.
1269 pub fn on_event<F>(&mut self, callback: F)
1270 where
1271 F: FnMut(&mut S, &mut Ui, &Event) + 'static,
1272 {
1273 self.event_callbacks.push(Box::new(callback));
1274 }
1275
1276 /// Registers a callback that receives every [`EngineEvent`].
1277 ///
1278 /// Engine events are emitted after an internal action completes (an event mask change, a
1279 /// `Widget` added, ...). They run before [`on_event`](Engine::on_event) callbacks. Engine
1280 /// events never trigger further internal actions by themselves.
1281 ///
1282 /// # Arguments
1283 ///
1284 /// * `callback` - Called with the application state, a [`Ui`] handle, and the engine event.
1285 ///
1286 /// # Examples
1287 ///
1288 /// ```rust
1289 /// use pushrod::engine::Engine;
1290 /// use pushrod::event::EngineEvent;
1291 /// use pushrod::geometry::size;
1292 ///
1293 /// let mut engine: Engine<Vec<String>> = Engine::new(size(320, 200), 30);
1294 ///
1295 /// engine.on_engine_event(|log, _ui, event| log.push(format!("{:?}", event)));
1296 /// ```
1297 pub fn on_engine_event<F>(&mut self, callback: F)
1298 where
1299 F: FnMut(&mut S, &mut Ui, &EngineEvent) + 'static,
1300 {
1301 self.engine_callbacks.push((None, Box::new(callback)));
1302 }
1303
1304 /// Registers a callback that receives only the listed kinds of [`EngineEvent`].
1305 ///
1306 /// # Arguments
1307 ///
1308 /// * `kinds` - The kinds of engine event to receive.
1309 /// * `callback` - Called with the application state, a [`Ui`] handle, and the engine event.
1310 pub fn on_engine_event_filtered<F>(&mut self, kinds: &[EngineEventKind], callback: F)
1311 where
1312 F: FnMut(&mut S, &mut Ui, &EngineEvent) + 'static,
1313 {
1314 self.engine_callbacks
1315 .push((Some(kinds.to_vec()), Box::new(callback)));
1316 }
1317
1318 /// Registers a callback for custom events whose payload is a `T`.
1319 ///
1320 /// Custom events are delivered to the targeted `Widget`s first, then to these callbacks, then
1321 /// to [`on_event`](Engine::on_event). Events carrying any other payload type are ignored by
1322 /// this callback.
1323 ///
1324 /// # Arguments
1325 ///
1326 /// * `callback` - Called with the application state, a [`Ui`] handle, the posting `Widget`
1327 /// (`None` if the application or another thread posted), and the payload.
1328 ///
1329 /// # Examples
1330 ///
1331 /// ```rust
1332 /// use pushrod::engine::Engine;
1333 /// use pushrod::geometry::size;
1334 ///
1335 /// struct DocumentSaved;
1336 ///
1337 /// let mut engine: Engine<u32> = Engine::new(size(320, 200), 30);
1338 ///
1339 /// engine.on_custom::<DocumentSaved, _>(|saves, _ui, _source, _payload| *saves += 1);
1340 /// ```
1341 pub fn on_custom<T, F>(&mut self, mut callback: F)
1342 where
1343 T: Any,
1344 F: FnMut(&mut S, &mut Ui, Option<WidgetId>, &T) + 'static,
1345 {
1346 self.custom_callbacks
1347 .push(Box::new(move |state, ui, custom| {
1348 if let Some(payload) = custom.payload::<T>() {
1349 callback(state, ui, custom.source, payload);
1350 }
1351 }));
1352 }
1353
1354 /// Returns a handle other threads use to post custom events to this `Engine`.
1355 ///
1356 /// # Returns
1357 ///
1358 /// A [`Sender`]; every call returns a handle to the same queue.
1359 pub fn sender(&self) -> Sender {
1360 Sender {
1361 mailbox: self.mailbox.clone(),
1362 }
1363 }
1364
1365 /// Lets [`Sender`]s wake the run loop through the backend's waker.
1366 ///
1367 /// # Arguments
1368 ///
1369 /// * `backend` - The backend the loop runs on.
1370 fn connect_sender(&mut self, backend: &dyn Backend) {
1371 if let Ok(mut wake) = self.mailbox.wake.lock() {
1372 *wake = backend.waker();
1373 }
1374 }
1375
1376 /// Sets the window's background color.
1377 ///
1378 /// This is the color of the [`RootWidget`] (ID `0`), which fills the window behind every other
1379 /// `Widget`.
1380 ///
1381 /// # Arguments
1382 ///
1383 /// * `color` - The new background color.
1384 pub fn set_background(&mut self, color: Color) {
1385 if let Some(root) = self.widget_cache.get_mut(crate::widget::ROOT_WIDGET_ID) {
1386 root.set_color(color);
1387 }
1388 }
1389
1390 /// Returns the size of the window.
1391 ///
1392 /// # Returns
1393 ///
1394 /// The window size given to [`Engine::new`].
1395 pub fn get_size(&self) -> Size {
1396 self.size
1397 }
1398
1399 /// Processes one raw input event, as the run loop does.
1400 ///
1401 /// The event is routed to the `Widget`s, and every event they generate is delivered to the
1402 /// registered callbacks, in order. Useful for testing an application without opening a window.
1403 ///
1404 /// # Arguments
1405 ///
1406 /// * `event` - The input event, as a backend would deliver it.
1407 /// * `state` - The application state passed to the callbacks.
1408 pub fn dispatch(&mut self, event: InputEvent, state: &mut S) {
1409 self.custom_budget = MAX_CUSTOM_EVENTS_PER_FRAME;
1410
1411 let routed = self.route(event);
1412
1413 for pushrod_event in self.expand_custom(routed) {
1414 self.fire(&pushrod_event, state);
1415 }
1416
1417 self.flush_pending(state);
1418 }
1419
1420 /// Routes a single input event to the `Widget`s and returns the `Event`s they
1421 /// generated, without calling any callbacks. Window-level events (quit, expose, resize) are
1422 /// handled here.
1423 fn route(&mut self, event: InputEvent) -> Vec<Event> {
1424 if let Some(class) = event.class()
1425 && !self.event_mask.intersects(class)
1426 {
1427 return Vec::new();
1428 }
1429
1430 match event {
1431 InputEvent::Quit => {
1432 self.running = false;
1433 Vec::new()
1434 }
1435
1436 InputEvent::Exposed => {
1437 self.widget_cache.invalidate_all();
1438 Vec::new()
1439 }
1440
1441 // Only a resize is broadcast; exposure just repaints.
1442 InputEvent::Resized(new_size) => {
1443 self.widget_cache.invalidate_all();
1444 self.widget_cache
1445 .broadcast(&Event::WindowResized { size: new_size })
1446 }
1447
1448 InputEvent::FocusChanged(focused) => self
1449 .widget_cache
1450 .broadcast(&Event::WindowFocusChanged { focused }),
1451
1452 // A wake-up only ends the wait; the posted events are drained by the loop.
1453 InputEvent::Wake => Vec::new(),
1454
1455 remaining_event => self.widget_cache.handle_event(remaining_event),
1456 }
1457 }
1458
1459 /// Delivers a generated `Event` to the callbacks.
1460 fn fire(&mut self, event: &Event, state: &mut S) {
1461 let mut ui = Ui {
1462 widgets: &mut self.widget_cache,
1463 running: &mut self.running,
1464 event_mask: &mut self.event_mask,
1465 posted: &mut self.posted,
1466 timers: &mut self.timers,
1467 };
1468
1469 if let Event::Custom(custom) = event {
1470 for callback in self.custom_callbacks.iter_mut() {
1471 callback(state, &mut ui, custom);
1472 }
1473 }
1474
1475 if let Some(id) = event.widget_id()
1476 && let Some(callbacks) = self.registry.get_mut(&(id, event.kind()))
1477 {
1478 for (_, callback) in callbacks.iter_mut() {
1479 callback(state, &mut ui, event);
1480 }
1481 }
1482
1483 if let Event::Engine(engine_event) = event {
1484 for (filter, callback) in self.engine_callbacks.iter_mut() {
1485 if engine_filter_accepts(filter.as_deref(), engine_event) {
1486 callback(state, &mut ui, engine_event);
1487 }
1488 }
1489 }
1490
1491 for callback in self.event_callbacks.iter_mut() {
1492 callback(state, &mut ui, event);
1493 }
1494 }
1495
1496 /// Runs the application on a backend until the window is closed or a callback calls `shutdown`.
1497 ///
1498 /// Each frame, the loop processes waiting input events (routing them to `Widget`s and calling
1499 /// callbacks), repaints changed `Widget`s, presents the frame if anything changed, then sleeps for
1500 /// the rest of the frame time. Applications normally start this through a backend crate,
1501 /// such as `pushrod_sdl2::run`, which builds the window and calls this method.
1502 ///
1503 /// # Arguments
1504 ///
1505 /// * `backend` - The backend that owns the window.
1506 /// * `state` - The application state, passed to every callback.
1507 ///
1508 /// # Returns
1509 ///
1510 /// The application state, after the last callback has run.
1511 ///
1512 /// # Examples
1513 ///
1514 /// ```rust
1515 /// use pushrod::backend::headless::HeadlessBackend;
1516 /// use pushrod::engine::Engine;
1517 /// use pushrod::geometry::size;
1518 ///
1519 /// let mut engine: Engine<u32> = Engine::new(size(100, 100), 30);
1520 /// let mut backend = HeadlessBackend::new(size(100, 100));
1521 ///
1522 /// // With nothing scripted, the headless window closes at once.
1523 /// assert_eq!(engine.run(&mut backend, 7), 7);
1524 /// ```
1525 pub fn run(&mut self, backend: &mut dyn Backend, mut state: S) -> S {
1526 self.connect_sender(backend);
1527
1528 // Determines the amount of time to wait between frames.
1529 let frame_time = Duration::from_millis((1000.0 / self.frame_rate.max(1) as f64) as u64);
1530
1531 self.widget_cache.invalidate_all();
1532
1533 let mut applied_mask = EventMask::ALL;
1534
1535 // This is the run loop. It performs the following tasks in the following order:
1536 //
1537 // First, it pulls all of the events that have been generated by the OS, through the
1538 // backend.
1539 //
1540 // Second, each event is dispatched: the WidgetCache routes it to the appropriate Widget,
1541 // and any Events the Widgets generate are delivered to the registered callbacks,
1542 // in the order in which they were generated.
1543 //
1544 // Third, any Widgets that are invalidated are repainted into their textures, and if
1545 // anything changed, every visible Widget is copied to the screen and the canvas is
1546 // presented.
1547 //
1548 // When the loop is idle it blocks in the wait for the first event instead, and does not
1549 // sleep.
1550 //
1551 // Afterward, if the loop was ahead of the frame time, it waits before repeating, making
1552 // sure the system keeps within the desired FPS of the drawing engine.
1553 //
1554 // If the user clicks close on the window, or a callback calls `shutdown`, the run loop
1555 // terminates and the application state is returned.
1556 loop {
1557 let start = backend.now();
1558
1559 self.sync_backend(backend, &mut applied_mask);
1560 self.custom_budget = MAX_CUSTOM_EVENTS_PER_FRAME;
1561 self.flush_pending(&mut state);
1562
1563 // With no timers wanted and nothing to repaint, wait for input instead of polling.
1564 let idle = self.is_idle();
1565 let wait = idle.then(|| Duration::from_millis(self.idle_wait_ms(backend.now()) as u64));
1566 let batch = backend.poll_events(wait);
1567
1568 let had_events = !batch.is_empty();
1569
1570 for event in batch {
1571 self.dispatch(event, &mut state);
1572 }
1573
1574 // Timers and animation ticks run every frame; idle callbacks only when no events
1575 // were waiting.
1576 self.advance(backend.now(), &mut state);
1577
1578 if !had_events {
1579 self.run_idle(&mut state);
1580 }
1581
1582 if !self.running {
1583 break;
1584 }
1585
1586 self.sync_backend(backend, &mut applied_mask);
1587
1588 if self.widget_cache.draw_loop(backend) {
1589 backend.present();
1590 }
1591
1592 let elapsed = backend.now().saturating_duration_since(start);
1593
1594 if !idle && elapsed < frame_time {
1595 sleep(frame_time - elapsed);
1596 }
1597 }
1598
1599 state
1600 }
1601
1602 /// Starts an application-driven event loop, as an alternative to [`Engine::run`] and callbacks.
1603 ///
1604 /// Call [`Engine::next_event`] repeatedly to receive the events generated by the `Widget`s.
1605 /// Applications normally start this through a backend crate, such as `pushrod_sdl2::event_loop`.
1606 ///
1607 /// # Arguments
1608 ///
1609 /// * `backend` - The backend that owns the window; the loop keeps it.
1610 ///
1611 /// # Returns
1612 ///
1613 /// The [`EventLoop`] to pass to [`Engine::next_event`].
1614 ///
1615 /// # Examples
1616 ///
1617 /// ```rust
1618 /// use pushrod::backend::headless::HeadlessBackend;
1619 /// use pushrod::engine::Engine;
1620 /// use pushrod::event::Event;
1621 /// use pushrod::geometry::size;
1622 ///
1623 /// let mut engine: Engine = Engine::new(size(400, 200), 60);
1624 /// let mut events = engine.event_loop(Box::new(HeadlessBackend::new(size(400, 200))));
1625 ///
1626 /// while let Some(event) = engine.next_event(&mut events) {
1627 /// if let Event::Clicked { id, .. } = event {
1628 /// println!("widget {} clicked", id);
1629 /// }
1630 /// }
1631 /// ```
1632 pub fn event_loop(&mut self, backend: Box<dyn Backend>) -> EventLoop {
1633 self.widget_cache.invalidate_all();
1634 self.connect_sender(backend.as_ref());
1635
1636 EventLoop {
1637 backend,
1638 frame_time: Duration::from_millis((1000.0 / self.frame_rate.max(1) as f64) as u64),
1639 queue: EventQueue::default(),
1640 applied_mask: EventMask::ALL,
1641 }
1642 }
1643
1644 /// Returns the next event generated by the `Widget`s, waiting for input as needed.
1645 ///
1646 /// While waiting, the screen is kept up to date: invalidated `Widget`s are repainted and the
1647 /// frame is presented, so changes made to `Widget`s between calls appear immediately. When nothing
1648 /// happens, the call blocks without using the CPU. Callbacks registered with `on_click` and
1649 /// `on_event` are not called by this method; use [`Engine::next_event_with`] to run them too.
1650 ///
1651 /// # Arguments
1652 ///
1653 /// * `events` - The loop state returned by [`Engine::event_loop`].
1654 ///
1655 /// # Returns
1656 ///
1657 /// The next event, or `None` once the window has been closed or [`shutdown`](Engine::shutdown)
1658 /// has been called.
1659 pub fn next_event(&mut self, events: &mut EventLoop) -> Option<Event> {
1660 self.next_event_inner(events, None)
1661 }
1662
1663 /// The loop behind [`Engine::next_event`] and [`Engine::next_event_with`]. Timers and idle
1664 /// callbacks need the application state, so they run only when `state` is given.
1665 ///
1666 /// # Arguments
1667 ///
1668 /// * `events` - The loop state returned by [`Engine::event_loop`].
1669 /// * `state` - The application state, if callbacks may run.
1670 ///
1671 /// # Returns
1672 ///
1673 /// The next event, or `None` once the engine has stopped.
1674 fn next_event_inner(
1675 &mut self,
1676 events: &mut EventLoop,
1677 mut state: Option<&mut S>,
1678 ) -> Option<Event> {
1679 loop {
1680 if let Some(event) = self.next_queued(&mut events.queue) {
1681 return Some(event);
1682 }
1683
1684 if !self.running {
1685 return None;
1686 }
1687
1688 self.sync_backend(events.backend.as_mut(), &mut events.applied_mask);
1689
1690 if self.widget_cache.draw_loop(events.backend.as_mut()) {
1691 events.backend.present();
1692 }
1693
1694 // Animation ticks, and (with state) due timers, run once per pass.
1695 let now = Instant::now();
1696 let ticked = self.tick_widgets(now);
1697
1698 events.queue.pending.extend(ticked);
1699
1700 if let Some(state) = state.as_deref_mut() {
1701 self.custom_budget = MAX_CUSTOM_EVENTS_PER_FRAME;
1702 self.run_due_timers(now, state);
1703 }
1704
1705 if !events.queue.pending.is_empty() || self.widget_cache.has_pending_events() {
1706 continue;
1707 }
1708
1709 // Idle callbacks run only when nothing is waiting, and then the loop waits, so a
1710 // callback cannot spin the loop faster than a frame.
1711 if let Some(state) = state.as_deref_mut()
1712 && events.queue.raw.is_empty()
1713 {
1714 self.run_idle_callbacks(state);
1715 }
1716
1717 // Wait for one event, then take whatever else is queued. An idle loop waits long
1718 // (but not past the next timer); otherwise it wakes at most once per frame.
1719 let timeout = if self.is_idle() {
1720 Duration::from_millis(self.idle_wait_ms(now) as u64)
1721 } else {
1722 events.frame_time.max(Duration::from_millis(1))
1723 };
1724
1725 events
1726 .queue
1727 .raw
1728 .extend(events.backend.poll_events(Some(timeout)));
1729 }
1730 }
1731
1732 /// Returns the next event, after running the registered callbacks for it.
1733 ///
1734 /// This is [`Engine::next_event`] plus the callback style: the `on_click`, `on_engine_event`
1735 /// and `on_event` callbacks run for the event, with the application state, and then the event
1736 /// is returned. Use it to mix styles, for example callbacks for most `Widget`s and a loop for
1737 /// the main window's logic. Every event is delivered to both, in the same order as
1738 /// [`Engine::run`] delivers it. Events emitted by a callback's own actions are returned by
1739 /// later calls.
1740 ///
1741 /// # Arguments
1742 ///
1743 /// * `events` - The loop state returned by [`Engine::event_loop`].
1744 /// * `state` - The application state passed to the callbacks.
1745 ///
1746 /// # Returns
1747 ///
1748 /// The next event, or `None` once the window has been closed or [`shutdown`](Engine::shutdown)
1749 /// has been called.
1750 ///
1751 /// # Examples
1752 ///
1753 /// ```rust,no_run
1754 /// # use pushrod::engine::Engine;
1755 /// # use pushrod::geometry::size;
1756 /// # use pushrod::backend::headless::HeadlessBackend;
1757 /// let mut engine: Engine<u32> = Engine::new(size(400, 200), 60);
1758 /// let mut events = engine.event_loop(Box::new(HeadlessBackend::new(size(400, 200))));
1759 /// let mut clicks = 0;
1760 ///
1761 /// engine.on_click(0, |clicks, _ui| *clicks += 1);
1762 ///
1763 /// // The callback has already run when the event is returned.
1764 /// while let Some(event) = engine.next_event_with(&mut events, &mut clicks) {
1765 /// println!("{:?}, {} clicks so far", event, clicks);
1766 /// }
1767 /// ```
1768 pub fn next_event_with(&mut self, events: &mut EventLoop, state: &mut S) -> Option<Event> {
1769 let event = self.next_event_inner(events, Some(&mut *state))?;
1770
1771 self.fire(&event, state);
1772
1773 Some(event)
1774 }
1775
1776 /// Returns the next event that can be produced without waiting for input.
1777 ///
1778 /// Events come out in the order [`Engine::dispatch`] delivers them: the events a raw input
1779 /// event generated, then the engine events its actions queued, and only then the next raw
1780 /// input event.
1781 ///
1782 /// # Arguments
1783 ///
1784 /// * `queue` - The generated and raw events waiting to be returned.
1785 ///
1786 /// # Returns
1787 ///
1788 /// The next event, or `None` if the queue is empty and nothing more is pending.
1789 fn next_queued(&mut self, queue: &mut EventQueue) -> Option<Event> {
1790 loop {
1791 if let Some(event) = queue.pending.pop_front() {
1792 return Some(event);
1793 }
1794
1795 let drained = self.drain_pending();
1796
1797 if !drained.is_empty() {
1798 queue.pending.extend(drained);
1799 continue;
1800 }
1801
1802 let raw = queue.raw.pop_front()?;
1803
1804 self.custom_budget = MAX_CUSTOM_EVENTS_PER_FRAME;
1805
1806 let routed = self.route(raw);
1807
1808 queue.pending.extend(self.expand_custom(routed));
1809 }
1810 }
1811}
1812
1813/// Raw input events waiting to be routed, and generated events waiting to be returned.
1814#[derive(Default)]
1815pub(crate) struct EventQueue {
1816 raw: VecDeque<InputEvent>,
1817 pending: VecDeque<Event>,
1818}
1819
1820/// The state of an application-driven event loop.
1821///
1822/// Created by [`Engine::event_loop`] and passed to [`Engine::next_event`]. It holds the
1823/// backend, the frame time, and events that have been generated but not yet
1824/// returned.
1825pub struct EventLoop {
1826 backend: Box<dyn Backend>,
1827 frame_time: Duration,
1828 queue: EventQueue,
1829 applied_mask: EventMask,
1830}
1831
1832#[cfg(test)]
1833mod parity_tests {
1834 use super::*;
1835 use crate::geometry::size;
1836 use crate::root_widget::RootWidget;
1837 use std::cell::RefCell;
1838 use std::rc::Rc;
1839
1840 /// Scripted input: every action emits engine events, and a widget add mid-script.
1841 fn script() -> Vec<InputEvent> {
1842 vec![InputEvent::Exposed, InputEvent::Quit]
1843 }
1844
1845 /// Prepares an engine whose callbacks change the mask and add widgets, so every input
1846 /// produces engine events.
1847 fn engine_with_actions(seen: Rc<RefCell<Vec<String>>>) -> Engine<u32> {
1848 let mut engine: Engine<u32> = Engine::new(size(100, 100), 30);
1849
1850 engine.on_event(move |count, ui, event| {
1851 *count += 1;
1852 seen.borrow_mut().push(format!("cb:{:?}", event));
1853
1854 if *count == 1 {
1855 ui.widgets().add(Box::new(RootWidget::new(size(5, 5))));
1856 }
1857 });
1858
1859 engine
1860 }
1861
1862 #[test]
1863 fn both_styles_see_the_same_events_in_the_same_order() {
1864 let log = Rc::new(RefCell::new(Vec::new()));
1865 let mut by_callbacks = engine_with_actions(log.clone());
1866 let mut count = 0;
1867
1868 by_callbacks.set_event_mask(EventMask::ALL & !EventMask::HOVER);
1869 for event in script() {
1870 by_callbacks.dispatch(event, &mut count);
1871 }
1872
1873 let callback_order: Vec<String> = log.borrow().clone();
1874
1875 let log = Rc::new(RefCell::new(Vec::new()));
1876 let mut by_loop = engine_with_actions(log.clone());
1877 let mut queue = EventQueue::default();
1878 let mut count = 0;
1879 let mut returned = Vec::new();
1880
1881 by_loop.set_event_mask(EventMask::ALL & !EventMask::HOVER);
1882 queue.raw.extend(script());
1883
1884 while let Some(event) = by_loop.next_queued(&mut queue) {
1885 by_loop.fire(&event, &mut count);
1886 returned.push(format!("cb:{:?}", event));
1887 }
1888
1889 assert!(!callback_order.is_empty());
1890 assert_eq!(callback_order, returned);
1891 assert_eq!(callback_order, *log.borrow());
1892 assert!(!by_loop.is_running());
1893 }
1894
1895 #[test]
1896 fn events_are_returned_without_callbacks_by_next_queued() {
1897 let log = Rc::new(RefCell::new(Vec::new()));
1898 let mut engine = engine_with_actions(log.clone());
1899 let mut queue = EventQueue::default();
1900
1901 engine.set_event_mask(EventMask::NONE);
1902
1903 assert!(engine.next_queued(&mut queue).is_some());
1904 assert!(log.borrow().is_empty());
1905 }
1906}
1907
1908#[cfg(test)]
1909mod window_broadcast_tests {
1910 use super::*;
1911 use crate::event::{EventCtx, Propagation};
1912 use crate::geometry::{point, size};
1913 use crate::widget::{Widget, WidgetCore};
1914 use std::cell::RefCell;
1915 use std::rc::Rc;
1916
1917 /// A `Widget` that wants window events and re-emits what it receives.
1918 struct Echo {
1919 core: WidgetCore,
1920 }
1921
1922 impl Widget for Echo {
1923 /// Returns the shared state.
1924 ///
1925 /// # Returns
1926 ///
1927 /// The `WidgetCore`.
1928 fn core(&self) -> &WidgetCore {
1929 &self.core
1930 }
1931
1932 /// Returns the shared state for modification.
1933 ///
1934 /// # Returns
1935 ///
1936 /// The `WidgetCore`.
1937 fn core_mut(&mut self) -> &mut WidgetCore {
1938 &mut self.core
1939 }
1940
1941 /// Draws nothing.
1942 ///
1943 /// # Arguments
1944 ///
1945 /// * `_p` - The painter.
1946 fn paint(&self, _p: &mut dyn crate::paint::Painter) {}
1947
1948 /// Re-emits the event.
1949 ///
1950 /// # Arguments
1951 ///
1952 /// * `event` - The event.
1953 /// * `ctx` - The context.
1954 ///
1955 /// # Returns
1956 ///
1957 /// [`Propagation::Continue`].
1958 fn handle_event(&mut self, event: &Event, ctx: &mut EventCtx) -> Propagation {
1959 ctx.emit(event.clone());
1960 Propagation::Stop
1961 }
1962 }
1963
1964 /// Creates an engine with an `Echo` `Widget` whose mask is `mask`, and a log of the
1965 /// window events the application sees.
1966 fn engine(mask: EventMask) -> (Engine<()>, Rc<RefCell<Vec<String>>>) {
1967 let log = Rc::new(RefCell::new(Vec::new()));
1968 let sink = log.clone();
1969 let mut engine: Engine<()> = Engine::new(size(100, 100), 30);
1970 let mut core = WidgetCore::new(point(0, 0), size(10, 10));
1971
1972 core.set_event_mask(mask);
1973 engine.widgets().add(Box::new(Echo { core }));
1974 engine.on_event(move |_, _, event| match event {
1975 Event::WindowResized { .. } | Event::WindowFocusChanged { .. } => {
1976 sink.borrow_mut().push(format!("{event:?}"));
1977 }
1978 _ => {}
1979 });
1980
1981 (engine, log)
1982 }
1983
1984 #[test]
1985 fn focus_and_resize_reach_widgets_with_window_in_their_mask() {
1986 let (mut engine, log) = engine(EventMask::WINDOW);
1987
1988 engine.dispatch(InputEvent::FocusChanged(true), &mut ());
1989 engine.dispatch(InputEvent::FocusChanged(false), &mut ());
1990 engine.dispatch(InputEvent::Resized(size(640, 480)), &mut ());
1991
1992 assert_eq!(log.borrow().len(), 3);
1993 assert!(log.borrow()[0].contains("focused: true"));
1994 assert!(log.borrow()[1].contains("focused: false"));
1995 assert!(log.borrow()[2].contains("640"));
1996 }
1997
1998 #[test]
1999 fn widgets_without_window_in_their_mask_receive_nothing() {
2000 let (mut engine, log) = engine(EventMask::POINTER_BUTTONS);
2001
2002 engine.dispatch(InputEvent::FocusChanged(true), &mut ());
2003 engine.dispatch(InputEvent::Resized(size(640, 480)), &mut ());
2004
2005 assert!(log.borrow().is_empty());
2006 }
2007
2008 #[test]
2009 fn exposure_repaints_but_is_not_broadcast() {
2010 let (mut engine, log) = engine(EventMask::WINDOW);
2011
2012 engine.dispatch(InputEvent::Exposed, &mut ());
2013
2014 assert!(log.borrow().is_empty());
2015 }
2016}
2017
2018#[cfg(test)]
2019mod registry_tests {
2020 use super::*;
2021 use crate::geometry::{point, size};
2022 use crate::input::MouseButton;
2023
2024 fn engine() -> Engine<Vec<String>> {
2025 Engine::new(size(100, 100), 30)
2026 }
2027
2028 /// Fires `event` and returns the log the callbacks wrote.
2029 fn fire_one(engine: &mut Engine<Vec<String>>, event: Event) -> Vec<String> {
2030 let mut log = Vec::new();
2031 engine.fire(&event, &mut log);
2032 log
2033 }
2034
2035 #[test]
2036 fn each_method_fires_for_its_kind_only() {
2037 let mut e = engine();
2038 e.on_click(1, |l, _| l.push("click".into()));
2039 e.on_press(1, |l, _| l.push("press".into()));
2040 e.on_release(1, |l, _| l.push("release".into()));
2041 e.on_activate(1, |l, _| l.push("activate".into()));
2042 e.on_toggle(1, |l, _, c| l.push(format!("toggle {c}")));
2043 e.on_value_change(1, |l, _| l.push("value".into()));
2044 e.on_viewport_change(1, |l, _, o| l.push(format!("viewport {},{}", o.x, o.y)));
2045 e.on_selection_change(1, |l, _| l.push("selection".into()));
2046 e.on_text_change(1, |l, _| l.push("text".into()));
2047 e.on_editing_finished(1, |l, _| l.push("finished".into()));
2048 e.on_key_press(1, |l, _, k, _| l.push(format!("key {k:?}")));
2049 e.on_focus_change(1, |l, _, g| l.push(format!("focus {g}")));
2050 e.on_hover(1, |l, _, i| l.push(format!("hover {i}")));
2051
2052 let button = MouseButton::Left;
2053 let cases: Vec<(Event, &str)> = vec![
2054 (
2055 Event::Clicked {
2056 id: 1,
2057 button,
2058 count: 1,
2059 },
2060 "click",
2061 ),
2062 (
2063 Event::PointerPressed {
2064 id: 1,
2065 button,
2066 position: point(0, 0),
2067 count: 1,
2068 },
2069 "press",
2070 ),
2071 (
2072 Event::PointerReleased {
2073 id: 1,
2074 button,
2075 position: point(0, 0),
2076 count: 1,
2077 },
2078 "release",
2079 ),
2080 (Event::Activated { id: 1 }, "activate"),
2081 (
2082 Event::Toggled {
2083 id: 1,
2084 checked: true,
2085 },
2086 "toggle true",
2087 ),
2088 (Event::ValueChanged { id: 1 }, "value"),
2089 (
2090 Event::ViewportChanged {
2091 id: 1,
2092 offset: point(3, 4),
2093 },
2094 "viewport 3,4",
2095 ),
2096 (Event::SelectionChanged { id: 1 }, "selection"),
2097 (Event::TextChanged { id: 1 }, "text"),
2098 (Event::EditingFinished { id: 1 }, "finished"),
2099 (
2100 Event::KeyPressed {
2101 id: 1,
2102 key: Key::Char('a'),
2103 modifiers: Modifiers::empty(),
2104 repeat: false,
2105 },
2106 "key Char('a')",
2107 ),
2108 (Event::FocusGained { id: 1 }, "focus true"),
2109 (Event::FocusLost { id: 1 }, "focus false"),
2110 (Event::PointerEntered { id: 1 }, "hover true"),
2111 (Event::PointerExited { id: 1 }, "hover false"),
2112 ];
2113
2114 for (event, expected) in cases {
2115 assert_eq!(fire_one(&mut e, event), vec![expected.to_string()]);
2116 }
2117 }
2118
2119 #[test]
2120 fn callbacks_do_not_fire_for_other_widgets() {
2121 let mut e = engine();
2122 e.on_toggle(1, |l, _, _| l.push("one".into()));
2123 assert!(
2124 fire_one(
2125 &mut e,
2126 Event::Toggled {
2127 id: 2,
2128 checked: true
2129 }
2130 )
2131 .is_empty()
2132 );
2133 assert!(fire_one(&mut e, Event::Activated { id: 1 }).is_empty());
2134 }
2135
2136 #[test]
2137 fn callbacks_run_in_registration_order_and_ids_are_unique() {
2138 let mut e = engine();
2139 let a = e.on_activate(1, |l, _| l.push("a".into()));
2140 let b = e.on_activate(1, |l, _| l.push("b".into()));
2141 let c = e.on_hover(1, |_, _, _| {});
2142 assert!(a != b && b != c);
2143 e.on_event(|l, _, _| l.push("catch-all".into()));
2144 assert_eq!(
2145 fire_one(&mut e, Event::Activated { id: 1 }),
2146 vec!["a", "b", "catch-all"]
2147 );
2148 }
2149}