pushrod/cache.rs
1// Cache
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//! # WidgetCache
17//!
18//! The `WidgetCache` stores every `Widget` in a window, much like the `OBJECT` tree of a GEM
19//! form on the Atari ST: `Widget`s live in a flat list, are addressed by their `WidgetId` (their
20//! index in the list), and are linked to their parents and children by ID. The top-level
21//! window `Widget` is always ID `0`.
22//!
23//! ```text
24//! ID 0 RootWidget (window)
25//! ├── ID 1 BaseWidget
26//! │ ├── ID 2 TextWidget origins are relative to the parent
27//! │ └── ID 3 ButtonWidget
28//! └── ID 4 BoxWidget later siblings are drawn on top
29//! ```
30//!
31//! A flat list addressed by ID avoids reference-counted parent pointers entirely, and allows a
32//! form to be stored and reloaded by ID.
33
34use crate::backend::Backend;
35use crate::color::Color;
36use crate::error::{Error, Result};
37use crate::event::{
38 CustomEvent, EngineEvent, EngineEventKind, Event, EventCtx, EventMask, EventPhase, EventTarget,
39 MaskScope, Propagation, engine_filter_accepts,
40};
41use crate::geometry::{Point, make_rect, point};
42use crate::input::InputEvent;
43use crate::paint::{self, CachePolicy};
44use crate::widget::{ROOT_WIDGET_ID, VisualState, Widget, WidgetId};
45use std::any::Any;
46use std::collections::HashMap;
47use std::time::Duration;
48
49mod focus;
50
51/// The tree of `Widget`s in a window.
52///
53/// `Widget`s are stored in a flat list, addressed by ID, with each `Widget`'s children kept in
54/// drawing order. The cache also tracks the `Widget` under the mouse pointer and the `Widget`
55/// that captured the mouse with a button press, routes raw input events to `Widget`s, and draws
56/// them.
57///
58/// # Examples
59///
60/// ```rust
61/// use pushrod::cache::WidgetCache;
62/// use pushrod::geometry::size;
63/// use pushrod::root_widget::RootWidget;
64///
65/// let mut cache = WidgetCache::new();
66/// let root = cache.add(Box::new(RootWidget::new(size(320, 200))));
67///
68/// assert_eq!(root, 0);
69/// assert_eq!(cache.len(), 1);
70/// ```
71pub struct WidgetCache {
72 cache: Vec<Box<dyn Widget>>,
73 children: Vec<Vec<WidgetId>>,
74 current_widget_id: WidgetId,
75 captured_widget_id: Option<WidgetId>,
76 needs_full_redraw: bool,
77 cache_policy: CachePolicy,
78 pending_events: Vec<Event>,
79 loop_mask: EventMask,
80 engine_filters: HashMap<WidgetId, Vec<EngineEventKind>>,
81 focused_widget_id: Option<WidgetId>,
82 text_input_wanted: bool,
83 animating: Vec<WidgetId>,
84}
85
86impl WidgetCache {
87 /// Creates an empty `WidgetCache`.
88 ///
89 /// The first `Widget` added becomes the root `Widget` (ID `0`).
90 ///
91 /// # Returns
92 ///
93 /// A new, empty `WidgetCache`.
94 pub fn new() -> Self {
95 Self {
96 cache: Vec::new(),
97 children: Vec::new(),
98 current_widget_id: ROOT_WIDGET_ID,
99 captured_widget_id: None,
100 needs_full_redraw: true,
101 cache_policy: CachePolicy::TextureCache,
102 pending_events: Vec::new(),
103 loop_mask: EventMask::ALL,
104 engine_filters: HashMap::new(),
105 focused_widget_id: None,
106 text_input_wanted: false,
107 animating: Vec::new(),
108 }
109 }
110
111 /// Returns the cache policy of the backend the cache paints with.
112 ///
113 /// Defaults to [`CachePolicy::TextureCache`]. `draw_loop` implements `TextureCache` only;
114 /// [`CachePolicy::DirectDraw`] is declared for backends that paint straight to the screen
115 /// with clipping, and is not rendered by `draw_loop`.
116 ///
117 /// # Returns
118 ///
119 /// The [`CachePolicy`].
120 pub fn cache_policy(&self) -> CachePolicy {
121 self.cache_policy
122 }
123
124 /// Sets the cache policy, as declared by the backend.
125 ///
126 /// # Arguments
127 ///
128 /// * `policy` - The backend's [`CachePolicy`].
129 pub fn set_cache_policy(&mut self, policy: CachePolicy) {
130 self.cache_policy = policy;
131 }
132
133 /// Adds a `Widget` as a child of the root `Widget`.
134 ///
135 /// If the cache is empty, the `Widget` becomes the root `Widget` instead.
136 ///
137 /// # Arguments
138 ///
139 /// * `widget` - The `Widget` to add.
140 ///
141 /// # Returns
142 ///
143 /// The ID assigned to the `Widget`.
144 pub fn add(&mut self, widget: Box<dyn Widget>) -> WidgetId {
145 self.add_child(ROOT_WIDGET_ID, widget)
146 }
147
148 /// Adds a `Widget` as a child of another `Widget`.
149 ///
150 /// The `Widget`'s origin is relative to its parent's origin, and it is drawn after (on top of)
151 /// the parent's existing children. If the cache is empty, the `Widget` becomes the root `Widget`
152 /// and `parent` is ignored.
153 ///
154 /// # Arguments
155 ///
156 /// * `parent` - The ID of the parent `Widget`.
157 /// * `widget` - The `Widget` to add.
158 ///
159 /// # Returns
160 ///
161 /// The ID assigned to the `Widget`.
162 ///
163 /// # Panics
164 ///
165 /// Panics if the cache is not empty and `parent` does not exist.
166 pub fn add_child(&mut self, parent: WidgetId, widget: Box<dyn Widget>) -> WidgetId {
167 self.try_add_child(parent, widget)
168 .unwrap_or_else(|error| panic!("[WidgetCache::add_child] {error}"))
169 }
170
171 /// Adds a `Widget` as the last child of `parent`, reporting an unknown parent as an error
172 /// instead of panicking. Behaves like [`add_child`](WidgetCache::add_child) otherwise.
173 ///
174 /// # Arguments
175 ///
176 /// * `parent` - The ID of the parent `Widget`.
177 /// * `widget` - The `Widget` to add.
178 ///
179 /// # Returns
180 ///
181 /// The ID assigned to the `Widget`.
182 ///
183 /// # Errors
184 ///
185 /// Returns [`Error::UnknownWidget`] if the cache is not empty and `parent` does not exist.
186 pub fn try_add_child(
187 &mut self,
188 parent: WidgetId,
189 mut widget: Box<dyn Widget>,
190 ) -> Result<WidgetId> {
191 let id = self.cache.len() as WidgetId;
192 let parent = if self.cache.is_empty() {
193 id
194 } else if (parent as usize) < self.cache.len() {
195 parent
196 } else {
197 return Err(Error::UnknownWidget { id: parent });
198 };
199
200 widget.core_mut().id = id;
201 widget.core_mut().parent = parent;
202 widget.set_invalidated(true);
203
204 self.cache.push(widget);
205 self.children.push(Vec::new());
206
207 if parent != id {
208 self.children[parent as usize].push(id);
209 }
210
211 self.needs_full_redraw = true;
212
213 if parent != id {
214 self.pending_events
215 .push(Event::Engine(EngineEvent::WidgetAdded { id, parent }));
216 }
217
218 Ok(id)
219 }
220
221 /// Returns the number of `Widget`s in the cache.
222 ///
223 /// # Returns
224 ///
225 /// The number of `Widget`s, including the root `Widget`.
226 pub fn len(&self) -> usize {
227 self.cache.len()
228 }
229
230 /// Returns whether the cache contains no `Widget`s.
231 ///
232 /// # Returns
233 ///
234 /// `true` if no `Widget` (not even a root) has been added.
235 pub fn is_empty(&self) -> bool {
236 self.cache.is_empty()
237 }
238
239 /// Retrieves a `Widget` by ID.
240 ///
241 /// # Arguments
242 ///
243 /// * `id` - The ID of the `Widget`.
244 ///
245 /// # Returns
246 ///
247 /// The `Widget` as a trait object, or `None` if the ID does not exist.
248 pub fn get(&self, id: WidgetId) -> Option<&dyn Widget> {
249 self.cache.get(id as usize).map(|widget| widget.as_ref())
250 }
251
252 /// Retrieves a `Widget` by ID for modification.
253 ///
254 /// # Arguments
255 ///
256 /// * `id` - The ID of the `Widget`.
257 ///
258 /// # Returns
259 ///
260 /// The `Widget` as a mutable trait object, or `None` if the ID does not exist.
261 pub fn get_mut(&mut self, id: WidgetId) -> Option<&mut dyn Widget> {
262 match self.cache.get_mut(id as usize) {
263 Some(widget) => Some(widget.as_mut()),
264 None => None,
265 }
266 }
267
268 /// Retrieves a `Widget` by ID as its concrete type.
269 ///
270 /// # Arguments
271 ///
272 /// * `id` - The ID of the `Widget`.
273 ///
274 /// # Returns
275 ///
276 /// The `Widget` as a `T`, or `None` if the ID does not exist or the `Widget` is not a `T`.
277 ///
278 /// # Examples
279 ///
280 /// ```rust
281 /// use pushrod::cache::WidgetCache;
282 /// use pushrod::geometry::size;
283 /// use pushrod::root_widget::RootWidget;
284 ///
285 /// let mut cache = WidgetCache::new();
286 /// cache.add(Box::new(RootWidget::new(size(320, 200))));
287 ///
288 /// assert!(cache.get_as::<RootWidget>(0).is_some());
289 /// ```
290 pub fn get_as<T: Widget>(&self, id: WidgetId) -> Option<&T> {
291 let widget: &dyn Any = self.cache.get(id as usize)?.as_ref();
292
293 widget.downcast_ref::<T>()
294 }
295
296 /// Retrieves a `Widget` by ID as its concrete type, for modification.
297 ///
298 /// # Arguments
299 ///
300 /// * `id` - The ID of the `Widget`.
301 ///
302 /// # Returns
303 ///
304 /// The `Widget` as a mutable `T`, or `None` if the ID does not exist or the `Widget` is not a `T`.
305 pub fn get_as_mut<T: Widget>(&mut self, id: WidgetId) -> Option<&mut T> {
306 let widget: &mut dyn Any = self.cache.get_mut(id as usize)?.as_mut();
307
308 widget.downcast_mut::<T>()
309 }
310
311 /// Returns the children of a `Widget`.
312 ///
313 /// # Arguments
314 ///
315 /// * `id` - The ID of the parent `Widget`.
316 ///
317 /// # Returns
318 ///
319 /// The IDs of the `Widget`'s direct children in drawing order (the last is drawn on top), or an
320 /// empty slice if the `Widget` has no children or does not exist.
321 pub fn children_of(&self, id: WidgetId) -> &[WidgetId] {
322 self.children
323 .get(id as usize)
324 .map(|children| children.as_slice())
325 .unwrap_or(&[])
326 }
327
328 /// Returns the `Widget` currently under the mouse pointer.
329 ///
330 /// # Returns
331 ///
332 /// The ID of the top-most visible `Widget` under the pointer, as of the last mouse event.
333 pub fn get_current_widget(&self) -> WidgetId {
334 self.current_widget_id
335 }
336
337 /// Forces the whole window to be redrawn on the next frame.
338 ///
339 /// Every visible `Widget`'s texture is copied to the screen again (textures are not repainted
340 /// unless the `Widget` itself is invalidated). Used after the window is exposed or resized.
341 pub fn invalidate_all(&mut self) {
342 self.needs_full_redraw = true;
343 }
344
345 /// Returns the origin of a `Widget` in window coordinates.
346 ///
347 /// # Arguments
348 ///
349 /// * `id` - The ID of the `Widget`.
350 ///
351 /// # Returns
352 ///
353 /// The `Widget`'s upper left-hand corner in window coordinates: its origin plus the origins of
354 /// all of its ancestors. Returns `(0, 0)` if the ID does not exist.
355 pub fn absolute_origin(&self, id: WidgetId) -> Point {
356 let mut origin = Point::new(0, 0);
357 let mut current = id;
358
359 while let Some(widget) = self.get(current) {
360 let widget_origin = widget.get_origin();
361
362 origin.x += widget_origin.x;
363 origin.y += widget_origin.y;
364
365 if widget.get_parent() == current {
366 break;
367 }
368
369 current = widget.get_parent();
370 }
371
372 origin
373 }
374
375 /// Returns the IDs of all visible `Widget`s in drawing order: parents before children, and
376 /// siblings in the order in which they were added. Hidden `Widget`s and their children are
377 /// skipped.
378 fn draw_order(&self) -> Vec<WidgetId> {
379 let mut order = Vec::with_capacity(self.cache.len());
380 let mut stack = Vec::new();
381
382 if !self.cache.is_empty() {
383 stack.push(ROOT_WIDGET_ID);
384 }
385
386 while let Some(id) = stack.pop() {
387 if self.cache[id as usize].is_hidden() {
388 continue;
389 }
390
391 order.push(id);
392
393 for child in self.children[id as usize].iter().rev() {
394 stack.push(*child);
395 }
396 }
397
398 order
399 }
400
401 /// Finds the top-most visible `Widget` at a point in the window.
402 ///
403 /// Hidden `Widget`s and their children are skipped.
404 ///
405 /// # Arguments
406 ///
407 /// * `x` - The horizontal window coordinate, in pixels.
408 /// * `y` - The vertical window coordinate, in pixels.
409 ///
410 /// # Returns
411 ///
412 /// The ID of the top-most visible `Widget` containing the point, or `0` (the root `Widget`) if no
413 /// other `Widget` contains it.
414 pub fn widget_at(&self, x: i32, y: i32) -> WidgetId {
415 for id in self.draw_order().into_iter().rev() {
416 let origin = self.absolute_origin(id);
417 let size = self.cache[id as usize].get_size();
418
419 if x >= origin.x
420 && x < origin.x + size.w as i32
421 && y >= origin.y
422 && y < origin.y + size.h as i32
423 {
424 return id;
425 }
426 }
427
428 ROOT_WIDGET_ID
429 }
430
431 /// Sets a `Widget`'s event mask and queues [`EngineEvent::EventMaskChanged`] when it changed.
432 ///
433 /// Queued events are returned by [`WidgetCache::take_pending_events`]; the `Engine` delivers
434 /// them to the callbacks.
435 ///
436 /// # Arguments
437 ///
438 /// * `id` - The ID of the `Widget`.
439 /// * `mask` - The new mask.
440 ///
441 /// # Returns
442 ///
443 /// `true` if the `Widget` exists and its mask changed.
444 pub fn set_event_mask(&mut self, id: WidgetId, mask: EventMask) -> bool {
445 let Some(widget) = self.get_mut(id) else {
446 return false;
447 };
448 let old = widget.event_mask();
449
450 if old == mask {
451 return false;
452 }
453
454 widget.core_mut().set_event_mask(mask);
455 self.pending_events
456 .push(Event::Engine(EngineEvent::EventMaskChanged {
457 scope: MaskScope::Widget(id),
458 old,
459 new: mask,
460 }));
461
462 true
463 }
464
465 /// Limits the engine events a `Widget` receives to the listed kinds.
466 ///
467 /// The `Widget` still needs [`EventMask::ENGINE`] in its mask. Without a filter it receives
468 /// every kind.
469 ///
470 /// # Arguments
471 ///
472 /// * `id` - The ID of the `Widget`.
473 /// * `kinds` - The accepted kinds, or `None` to remove the filter.
474 pub fn set_engine_filter(&mut self, id: WidgetId, kinds: Option<Vec<EngineEventKind>>) {
475 match kinds {
476 Some(kinds) => {
477 self.engine_filters.insert(id, kinds);
478 }
479 None => {
480 self.engine_filters.remove(&id);
481 }
482 }
483 }
484
485 /// Broadcasts a completed engine event to the `Widget`s that want it.
486 ///
487 /// A `Widget` receives it when it is enabled, the run loop's mask and its own mask include
488 /// [`EventMask::ENGINE`], and its kind filter (if any) accepts the event. Anything the
489 /// `Widget`s generate in response is returned and is never broadcast again, so engine events
490 /// cannot loop.
491 ///
492 /// # Arguments
493 ///
494 /// * `event` - The engine event.
495 ///
496 /// # Returns
497 ///
498 /// The events the `Widget`s generated while handling it.
499 pub fn broadcast_engine_event(&mut self, event: &EngineEvent) -> Vec<Event> {
500 let mut ctx = EventCtx::default();
501 let wrapped = Event::Engine(event.clone());
502
503 if self.loop_mask.intersects(EventMask::ENGINE) {
504 for (index, widget) in self.cache.iter_mut().enumerate() {
505 let filter = self.engine_filters.get(&(index as WidgetId));
506
507 if widget.is_enabled()
508 && widget.event_mask().intersects(EventMask::ENGINE)
509 && engine_filter_accepts(filter.map(|k| k.as_slice()), event)
510 {
511 ctx.set_source(Some(index as WidgetId));
512 widget.handle_event(&wrapped, &mut ctx);
513 }
514 }
515 }
516
517 self.finish(ctx)
518 }
519
520 /// Broadcasts an event to every `Widget` that wants it, in drawing order.
521 ///
522 /// A `Widget` receives the event when it is visible (neither it nor an ancestor is hidden),
523 /// enabled, and both the run loop's mask and its own mask include the event's class. Events
524 /// that are never filtered (see [`EventKind::mask_class`](crate::event::EventKind::mask_class)) reach every visible, enabled
525 /// `Widget`. Delivery order is deterministic: parents before children, siblings in the order
526 /// they were added. Events the `Widget`s generate in response are returned, never
527 /// broadcast again.
528 ///
529 /// Keyboard events are not broadcast; they belong to the focused `Widget`. Queues
530 /// [`EngineEvent::EventBroadcast`] describing the delivery.
531 ///
532 /// # Arguments
533 ///
534 /// * `event` - The event to broadcast.
535 ///
536 /// # Returns
537 ///
538 /// The events the `Widget`s generated while handling it, in the order emitted.
539 pub fn broadcast(&mut self, event: &Event) -> Vec<Event> {
540 let mut ctx = EventCtx::default();
541 let class = event.kind().mask_class();
542 let loop_mask = self.loop_mask;
543 let mut recipients = 0;
544
545 if class.is_none_or(|class| loop_mask.intersects(class)) {
546 for id in self.draw_order() {
547 let widget = &mut self.cache[id as usize];
548
549 if widget.is_enabled()
550 && class.is_none_or(|class| widget.event_mask().intersects(class))
551 {
552 ctx.set_source(Some(id));
553 widget.handle_event(event, &mut ctx);
554 recipients += 1;
555 }
556 }
557 }
558
559 self.pending_events
560 .push(Event::Engine(EngineEvent::EventBroadcast {
561 kind: event.kind(),
562 recipients,
563 }));
564
565 self.finish(ctx)
566 }
567
568 /// Sets the run loop's event mask, which `Widget`s must also pass. The `Engine` calls this
569 /// whenever its own mask changes.
570 ///
571 /// # Arguments
572 ///
573 /// * `mask` - The run loop's mask.
574 pub(crate) fn set_loop_mask(&mut self, mask: EventMask) {
575 self.loop_mask = mask;
576 }
577
578 /// Queues an engine event for [`WidgetCache::take_pending_events`].
579 ///
580 /// # Arguments
581 ///
582 /// * `event` - The event to queue.
583 pub(crate) fn queue_event(&mut self, event: Event) {
584 self.pending_events.push(event);
585 }
586
587 /// Ends a round of event handling: records the animation requests the `Widget`s made and
588 /// returns the events they generated.
589 ///
590 /// # Arguments
591 ///
592 /// * `ctx` - The context the `Widget`s handled events with.
593 ///
594 /// # Returns
595 ///
596 /// The events the `Widget`s generated, in the order emitted.
597 pub(crate) fn finish(&mut self, mut ctx: EventCtx) -> Vec<Event> {
598 self.animating.extend(ctx.take_animation_requests());
599
600 ctx.into_events()
601 }
602
603 /// Asks for an [`Event::Tick`] for a `Widget` on the next frame, from outside event handling,
604 /// for example to start an animation from a callback. Inside `handle_event`, use
605 /// [`EventCtx::request_animation`].
606 ///
607 /// # Arguments
608 ///
609 /// * `id` - The `Widget` to tick. Unknown IDs are ignored.
610 pub fn request_animation(&mut self, id: WidgetId) {
611 if (id as usize) < self.cache.len() {
612 self.animating.push(id);
613 }
614 }
615
616 /// Returns whether any `Widget` has asked for a tick on the next frame.
617 ///
618 /// # Returns
619 ///
620 /// `true` while an animation request is waiting.
621 pub fn animation_requested(&self) -> bool {
622 !self.animating.is_empty()
623 }
624
625 /// Delivers [`Event::Tick`] to the `Widget`s that requested animation since the last tick,
626 /// and only to those. The requests are consumed: a `Widget` that keeps animating requests
627 /// again while handling the tick. A `Widget` also needs [`EventMask::TIMER`] in its mask (and
628 /// the run loop's), and must be enabled and visible. Queues [`EngineEvent::AnimationTicked`]
629 /// when at least one `Widget` received the tick.
630 ///
631 /// # Arguments
632 ///
633 /// * `elapsed` - The time since the previous frame, carried by the tick.
634 ///
635 /// # Returns
636 ///
637 /// The events the `Widget`s generated while handling the tick, in order.
638 pub fn tick(&mut self, elapsed: Duration) -> Vec<Event> {
639 let requested = std::mem::take(&mut self.animating);
640 let mut ctx = EventCtx::default();
641 let mut recipients = 0;
642
643 if !requested.is_empty() && self.loop_mask.intersects(EventMask::TIMER) {
644 let event = Event::Tick { elapsed };
645
646 for id in self.draw_order() {
647 let widget = &mut self.cache[id as usize];
648
649 if requested.contains(&id)
650 && widget.is_enabled()
651 && widget.event_mask().intersects(EventMask::TIMER)
652 {
653 ctx.set_source(Some(id));
654 widget.handle_event(&event, &mut ctx);
655 recipients += 1;
656 }
657 }
658 }
659
660 if recipients > 0 {
661 self.pending_events
662 .push(Event::Engine(EngineEvent::AnimationTicked {
663 recipients,
664 elapsed,
665 }));
666 }
667
668 self.finish(ctx)
669 }
670
671 /// Removes and returns the engine events queued by the cache itself, in order.
672 ///
673 /// # Returns
674 ///
675 /// The queued events; empty if there are none.
676 pub fn take_pending_events(&mut self) -> Vec<Event> {
677 std::mem::take(&mut self.pending_events)
678 }
679
680 /// Returns whether engine events are waiting for [`WidgetCache::take_pending_events`].
681 ///
682 /// # Returns
683 ///
684 /// `true` if at least one event is queued.
685 pub(crate) fn has_pending_events(&self) -> bool {
686 !self.pending_events.is_empty()
687 }
688
689 /// Returns whether the next [`draw_loop`](WidgetCache::draw_loop) has anything to do.
690 ///
691 /// # Returns
692 ///
693 /// `true` if a full redraw is pending or any `Widget` is invalidated.
694 pub fn needs_draw(&self) -> bool {
695 self.needs_full_redraw || self.cache.iter().any(|w| w.is_invalidated())
696 }
697
698 /// Sends an event to a `Widget`. Disabled and hidden `Widget`s, and `Widget`s whose event mask
699 /// excludes the event's class, receive nothing.
700 ///
701 /// # Arguments
702 ///
703 /// * `id` - The receiving `Widget`.
704 /// * `event` - The event.
705 /// * `phase` - The phase of delivery, readable through [`EventCtx::phase`].
706 /// * `ctx` - The context collecting generated events.
707 ///
708 /// # Returns
709 ///
710 /// What the `Widget` returned, or [`Propagation::Continue`] if it received nothing.
711 fn send(
712 &mut self,
713 id: WidgetId,
714 event: &Event,
715 phase: EventPhase,
716 ctx: &mut EventCtx,
717 ) -> Propagation {
718 let loop_mask = self.loop_mask;
719
720 if let Some(widget) = self.get_mut(id)
721 && widget.is_enabled()
722 && !widget.is_hidden()
723 && event.kind().mask_class().is_none_or(|class| {
724 loop_mask.intersects(class) && widget.event_mask().intersects(class)
725 })
726 {
727 ctx.set_source(Some(id));
728 ctx.set_phase(phase);
729
730 let result = widget.handle_event(event, ctx);
731
732 ctx.set_phase(EventPhase::Target);
733
734 return result;
735 }
736
737 Propagation::Continue
738 }
739
740 /// Returns the ancestors of a `Widget`, nearest parent first, ending at the root.
741 fn ancestors(&self, id: WidgetId) -> Vec<WidgetId> {
742 let mut path = Vec::new();
743 let mut current = id;
744
745 while let Some(widget) = self.get(current) {
746 let parent = widget.get_parent();
747
748 if parent == current || path.contains(&parent) {
749 break;
750 }
751
752 path.push(parent);
753 current = parent;
754 }
755
756 path
757 }
758
759 /// Delivers an input event to `target` through the capture, target, and bubble phases.
760 ///
761 /// 1. **Capture:** from the root down to the target's parent, only `Widget`s whose
762 /// [`handles_capture`](Widget::handles_capture) is `true`.
763 /// 2. **Target:** the `Widget` itself.
764 /// 3. **Bubble:** from the target's parent up to the root.
765 ///
766 /// [`Propagation::Stop`] from any `Widget` ends delivery. Disabled and hidden `Widget`s, and
767 /// those whose mask excludes the event, are skipped. Events that do not propagate (see
768 /// [`EventKind::propagates`](crate::event::EventKind::propagates)) go to the target only.
769 ///
770 /// # Arguments
771 ///
772 /// * `target` - The `Widget` the event is for: under the pointer, capturing the mouse, or
773 /// focused.
774 /// * `event` - The event.
775 /// * `ctx` - The context collecting generated events.
776 ///
777 /// # Returns
778 ///
779 /// [`Propagation::Stop`] if a `Widget` stopped delivery, otherwise [`Propagation::Continue`].
780 pub fn propagate_with(
781 &mut self,
782 target: WidgetId,
783 event: &Event,
784 ctx: &mut EventCtx,
785 ) -> Propagation {
786 if !event.kind().propagates() {
787 return self.send(target, event, EventPhase::Target, ctx);
788 }
789
790 let ancestors = self.ancestors(target);
791
792 for &id in ancestors.iter().rev() {
793 if self.get(id).is_some_and(|w| w.handles_capture())
794 && self.send(id, event, EventPhase::Capture, ctx) == Propagation::Stop
795 {
796 return Propagation::Stop;
797 }
798 }
799
800 if self.send(target, event, EventPhase::Target, ctx) == Propagation::Stop {
801 return Propagation::Stop;
802 }
803
804 for &id in &ancestors {
805 if self.send(id, event, EventPhase::Bubble, ctx) == Propagation::Stop {
806 return Propagation::Stop;
807 }
808 }
809
810 Propagation::Continue
811 }
812
813 /// Delivers an input event, such as a key press for the focused `Widget`, through the
814 /// capture, target, and bubble phases. See [`WidgetCache::propagate_with`].
815 ///
816 /// # Arguments
817 ///
818 /// * `target` - The `Widget` the event is for.
819 /// * `event` - The event.
820 ///
821 /// # Returns
822 ///
823 /// The events the `Widget`s generated while handling it, in the order emitted.
824 pub fn propagate(&mut self, target: WidgetId, event: &Event) -> Vec<Event> {
825 let mut ctx = EventCtx::default();
826
827 self.propagate_with(target, event, &mut ctx);
828 self.finish(ctx)
829 }
830
831 /// Delivers a custom event to the `Widget`s its target names.
832 ///
833 /// A `Widget` receives it when [`EventMask::CUSTOM`] is in both the run loop's mask and its
834 /// own mask. Custom events are not input, so disabled `Widget`s still receive them; a
835 /// [`Broadcast`](EventTarget::Broadcast) reaches only visible `Widget`s. Delivery is in
836 /// drawing order, parents before children. The core takes no other action: no focus, mouse
837 /// capture, selection, or redraw changes.
838 ///
839 /// # Arguments
840 ///
841 /// * `custom` - The custom event.
842 ///
843 /// # Returns
844 ///
845 /// The events the `Widget`s generated while handling it, in the order emitted (including any
846 /// custom events they posted, which the caller queues).
847 pub fn deliver_custom(&mut self, custom: &CustomEvent) -> Vec<Event> {
848 let mut ctx = EventCtx::default();
849
850 if !self.loop_mask.intersects(EventMask::CUSTOM) {
851 return self.finish(ctx);
852 }
853
854 let recipients = match custom.target {
855 EventTarget::ApplicationOnly => Vec::new(),
856 EventTarget::Widget(id) => vec![id],
857 EventTarget::Broadcast => self.draw_order(),
858 EventTarget::Subtree(root) => {
859 let mut ids = Vec::new();
860 let mut stack = vec![root];
861
862 while let Some(id) = stack.pop() {
863 if (id as usize) < self.cache.len() {
864 ids.push(id);
865 stack.extend(self.children[id as usize].iter().rev());
866 }
867 }
868
869 ids
870 }
871 };
872 let event = Event::Custom(custom.clone());
873
874 for id in recipients {
875 if let Some(widget) = self.cache.get_mut(id as usize)
876 && widget.event_mask().intersects(EventMask::CUSTOM)
877 {
878 ctx.set_source(Some(id));
879 widget.handle_event(&event, &mut ctx);
880 }
881 }
882
883 self.finish(ctx)
884 }
885
886 /// Routes a raw input event to the `Widget`s.
887 ///
888 /// - A mouse button press sends `PointerPressed` to the top-most `Widget` under the pointer,
889 /// which captures the mouse until the button is released.
890 /// - Mouse motion sends `PointerExited` to the `Widget` that was left and `PointerEntered` to
891 /// the `Widget` that was entered (when they differ), then `PointerMoved` to the capturing
892 /// `Widget`, or the `Widget` under the pointer.
893 /// - A mouse button release sends `PointerReleased` to the capturing `Widget`, then ends the
894 /// capture.
895 /// - Presses, releases, and motion travel through the capture, target, and bubble phases (see
896 /// [`WidgetCache::propagate_with`]); hover events go to one `Widget`.
897 /// - A mouse button press first focuses the nearest focusable `Widget` at or above the one
898 /// pressed.
899 /// - Key presses and releases go to the focused `Widget` (or the root with no focus), then
900 /// Tab, the arrow keys, Return, and Escape act as described in [`WidgetCache::focus_next`],
901 /// [`WidgetCache::focus_in_group`], and [`WidgetCache::set_focus`]. Typed text goes to the
902 /// focused `Widget`.
903 /// - Other events are ignored.
904 /// - Disabled `Widget`s receive none of these events, but still block the `Widget`s beneath them.
905 ///
906 /// # Arguments
907 ///
908 /// * `event` - The input event from the backend.
909 ///
910 /// # Returns
911 ///
912 /// The `Event`s the `Widget`s generated while handling the event, in the order emitted.
913 pub fn handle_event(&mut self, event: InputEvent) -> Vec<Event> {
914 let mut ctx = EventCtx::default();
915
916 if self.cache.is_empty() {
917 return self.finish(ctx);
918 }
919
920 match event {
921 InputEvent::MouseDown {
922 position: Point { x, y },
923 button: mouse_btn,
924 clicks,
925 } => {
926 self.current_widget_id = self.widget_at(x, y);
927
928 let target = self.current_widget_id;
929
930 self.captured_widget_id = Some(target);
931 self.set_state_flag(target, VisualState::PRESSED, true);
932 self.focus_for_click(target);
933 self.propagate_with(
934 target,
935 &Event::PointerPressed {
936 id: target,
937 button: mouse_btn,
938 position: point(x, y),
939 count: clicks,
940 },
941 &mut ctx,
942 );
943 }
944
945 InputEvent::MouseUp {
946 position: Point { x, y },
947 button: mouse_btn,
948 clicks,
949 } => {
950 self.current_widget_id = self.widget_at(x, y);
951
952 let target = self
953 .captured_widget_id
954 .take()
955 .unwrap_or(self.current_widget_id);
956
957 self.set_state_flag(target, VisualState::PRESSED, false);
958 self.propagate_with(
959 target,
960 &Event::PointerReleased {
961 id: target,
962 button: mouse_btn,
963 position: point(x, y),
964 count: clicks,
965 },
966 &mut ctx,
967 );
968 }
969
970 InputEvent::MouseMove {
971 position: Point { x, y },
972 } => {
973 let previous_widget_id = self.current_widget_id;
974
975 self.current_widget_id = self.widget_at(x, y);
976
977 if self.current_widget_id != previous_widget_id {
978 self.set_state_flag(previous_widget_id, VisualState::HOVERED, false);
979 self.set_state_flag(self.current_widget_id, VisualState::HOVERED, true);
980 self.send(
981 previous_widget_id,
982 &Event::PointerExited {
983 id: previous_widget_id,
984 },
985 EventPhase::Target,
986 &mut ctx,
987 );
988 self.send(
989 self.current_widget_id,
990 &Event::PointerEntered {
991 id: self.current_widget_id,
992 },
993 EventPhase::Target,
994 &mut ctx,
995 );
996 }
997
998 if let Some(captured) = self.captured_widget_id {
999 // A held button stays pressed only while the pointer is over the widget.
1000 self.set_state_flag(
1001 captured,
1002 VisualState::PRESSED,
1003 captured == self.current_widget_id,
1004 );
1005 }
1006
1007 let target = self.captured_widget_id.unwrap_or(self.current_widget_id);
1008
1009 self.propagate_with(
1010 target,
1011 &Event::PointerMoved {
1012 id: target,
1013 position: point(x, y),
1014 },
1015 &mut ctx,
1016 );
1017 }
1018
1019 InputEvent::KeyDown {
1020 key,
1021 modifiers: keymod,
1022 repeat,
1023 } => self.handle_key_down(key, keymod, repeat, &mut ctx),
1024
1025 InputEvent::KeyUp {
1026 key,
1027 modifiers: keymod,
1028 } => {
1029 let target = self.key_target();
1030
1031 self.propagate_with(
1032 target,
1033 &Event::KeyReleased {
1034 id: target,
1035 key,
1036 modifiers: keymod,
1037 },
1038 &mut ctx,
1039 );
1040 }
1041
1042 InputEvent::Text(text) => {
1043 if let Some(target) = self.focused_widget_id {
1044 self.propagate_with(target, &Event::TextEntered { id: target, text }, &mut ctx);
1045 }
1046 }
1047
1048 _ => {}
1049 }
1050
1051 self.finish(ctx)
1052 }
1053
1054 /// Sets or clears one [`VisualState`] flag on a `Widget`, repainting it only if its look
1055 /// changes (see [`Widget::set_state`]).
1056 ///
1057 /// # Arguments
1058 ///
1059 /// * `id` - The `Widget`; an unknown ID is ignored.
1060 /// * `flag` - The flag to change.
1061 /// * `on` - `true` to set the flag, `false` to clear it.
1062 pub(crate) fn set_state_flag(&mut self, id: WidgetId, flag: VisualState, on: bool) {
1063 if let Some(widget) = self.get_mut(id) {
1064 let mut state = widget.state();
1065
1066 state.set(flag, on);
1067 widget.set_state(state);
1068 }
1069 }
1070
1071 /// Paints a single `Widget` into its texture through the backend.
1072 fn paint(&mut self, id: WidgetId, backend: &mut dyn Backend) {
1073 let widget = &mut self.cache[id as usize];
1074 let size = widget.get_size();
1075
1076 if size.w == 0 || size.h == 0 {
1077 return;
1078 }
1079
1080 let painter: &dyn Widget = widget.as_ref();
1081
1082 backend.paint_widget(id, size, &mut |p| {
1083 painter.paint(p);
1084 paint::state_overlay(p, size, painter.state());
1085 });
1086 }
1087
1088 /// Queues the engine events the backend produced while painting (fonts loaded, glyph atlas
1089 /// pages added).
1090 fn queue_backend_notices(&mut self, backend: &mut dyn Backend) {
1091 for event in backend.take_notices() {
1092 self.queue_event(Event::Engine(event));
1093 }
1094 }
1095
1096 /// Repaints changed `Widget`s and redraws the window if anything changed.
1097 ///
1098 /// Every invalidated, visible `Widget` is repainted into its texture. If any `Widget` changed (or
1099 /// a full redraw was requested), the window is cleared and every visible `Widget`'s texture is
1100 /// copied to the screen in drawing order. Copying cached textures is cheap; repainting only
1101 /// happens for `Widget`s that changed.
1102 ///
1103 /// # Arguments
1104 ///
1105 /// * `backend` - The backend that owns the window and the `Widget` textures.
1106 ///
1107 /// # Returns
1108 ///
1109 /// `true` if a frame was drawn and the backend should present it, `false` if nothing
1110 /// changed.
1111 pub fn draw_loop(&mut self, backend: &mut dyn Backend) -> bool {
1112 let order = self.draw_order();
1113 let mut visible = vec![false; self.cache.len()];
1114 let mut redraw = self.needs_full_redraw;
1115
1116 for id in &order {
1117 visible[*id as usize] = true;
1118 }
1119
1120 for (id, is_visible) in visible.into_iter().enumerate() {
1121 if self.cache[id].is_invalidated() {
1122 if is_visible {
1123 self.paint(id as WidgetId, backend);
1124 }
1125
1126 self.cache[id].set_invalidated(false);
1127 redraw = true;
1128 }
1129 }
1130
1131 self.queue_backend_notices(backend);
1132
1133 if !redraw {
1134 return false;
1135 }
1136
1137 backend.begin_frame(Color::WHITE);
1138
1139 for id in order {
1140 let origin = self.absolute_origin(id);
1141 let size = self.cache[id as usize].get_size();
1142
1143 backend.draw_widget(id, make_rect(origin, size));
1144 }
1145
1146 self.needs_full_redraw = false;
1147
1148 true
1149 }
1150}
1151
1152impl Default for WidgetCache {
1153 /// Creates an empty `WidgetCache`; the same as [`WidgetCache::new`].
1154 ///
1155 /// # Returns
1156 ///
1157 /// A new, empty `WidgetCache`.
1158 fn default() -> Self {
1159 Self::new()
1160 }
1161}
1162
1163#[cfg(test)]
1164mod broadcast_tests {
1165 use super::*;
1166 use crate::event::EngineEvent;
1167 use crate::geometry::{Size, size};
1168 use crate::root_widget::RootWidget;
1169 use crate::widget::WidgetCore;
1170 use std::cell::RefCell;
1171 use std::rc::Rc;
1172
1173 /// A `Widget` that records its ID whenever it receives an event.
1174 struct Recorder {
1175 core: WidgetCore,
1176 log: Rc<RefCell<Vec<WidgetId>>>,
1177 }
1178
1179 impl Widget for Recorder {
1180 /// Returns the shared state.
1181 ///
1182 /// # Returns
1183 ///
1184 /// The `WidgetCore`.
1185 fn core(&self) -> &WidgetCore {
1186 &self.core
1187 }
1188
1189 /// Returns the shared state for modification.
1190 ///
1191 /// # Returns
1192 ///
1193 /// The `WidgetCore`.
1194 fn core_mut(&mut self) -> &mut WidgetCore {
1195 &mut self.core
1196 }
1197
1198 /// Draws nothing.
1199 ///
1200 /// # Arguments
1201 ///
1202 /// * `_p` - The painter.
1203 fn paint(&self, _p: &mut dyn crate::paint::Painter) {}
1204
1205 /// Records the widget's ID.
1206 ///
1207 /// # Arguments
1208 ///
1209 /// * `_event` - The event.
1210 /// * `_ctx` - The context.
1211 ///
1212 /// # Returns
1213 ///
1214 /// [`Propagation::Continue`].
1215 fn handle_event(&mut self, _event: &Event, _ctx: &mut EventCtx) -> Propagation {
1216 self.log.borrow_mut().push(self.get_id());
1217 Propagation::Continue
1218 }
1219 }
1220
1221 /// Creates a recording `Widget` with a mask.
1222 fn recorder(log: &Rc<RefCell<Vec<WidgetId>>>, mask: EventMask) -> Box<Recorder> {
1223 let mut core = WidgetCore::new(point(0, 0), size(10, 10));
1224
1225 core.set_event_mask(mask);
1226
1227 Box::new(Recorder {
1228 core,
1229 log: log.clone(),
1230 })
1231 }
1232
1233 /// Creates a cache holding a root `Widget`, with every class enabled in the run loop.
1234 fn cache() -> WidgetCache {
1235 let mut cache = WidgetCache::new();
1236
1237 cache.add(Box::new(RootWidget::new(Size::new(100, 100))));
1238 cache.set_loop_mask(EventMask::ALL);
1239 cache
1240 }
1241
1242 fn focus() -> Event {
1243 Event::WindowFocusChanged { focused: true }
1244 }
1245
1246 #[test]
1247 fn delivery_is_in_draw_order_parents_before_children() {
1248 let log = Rc::new(RefCell::new(Vec::new()));
1249 let mut cache = cache();
1250 let a = cache.add(recorder(&log, EventMask::WINDOW));
1251 let b = cache.add(recorder(&log, EventMask::WINDOW));
1252 let a_child = cache.add_child(a, recorder(&log, EventMask::WINDOW));
1253
1254 cache.broadcast(&focus());
1255
1256 assert_eq!(*log.borrow(), vec![a, a_child, b]);
1257 }
1258
1259 #[test]
1260 fn an_unknown_parent_is_an_error_not_a_panic() {
1261 let log = Rc::new(RefCell::new(Vec::new()));
1262 let mut cache = cache();
1263 let before = cache.len();
1264
1265 let result = cache.try_add_child(99, recorder(&log, EventMask::WINDOW));
1266
1267 assert_eq!(result, Err(Error::UnknownWidget { id: 99 }));
1268 assert_eq!(cache.len(), before);
1269 assert!(
1270 cache
1271 .try_add_child(0, recorder(&log, EventMask::WINDOW))
1272 .is_ok()
1273 );
1274 }
1275
1276 #[test]
1277 fn only_widgets_with_the_class_in_their_mask_receive_it() {
1278 let log = Rc::new(RefCell::new(Vec::new()));
1279 let mut cache = cache();
1280 let wants = cache.add(recorder(&log, EventMask::WINDOW));
1281
1282 cache.add(recorder(&log, EventMask::POINTER_BUTTONS));
1283 cache.add(recorder(&log, EventMask::NONE));
1284 cache.broadcast(&Event::WindowResized { size: size(5, 5) });
1285
1286 assert_eq!(*log.borrow(), vec![wants]);
1287 }
1288
1289 #[test]
1290 fn hidden_and_disabled_widgets_and_hidden_subtrees_are_skipped() {
1291 let log = Rc::new(RefCell::new(Vec::new()));
1292 let mut cache = cache();
1293 let hidden = cache.add(recorder(&log, EventMask::WINDOW));
1294 let under_hidden = cache.add_child(hidden, recorder(&log, EventMask::WINDOW));
1295 let disabled = cache.add(recorder(&log, EventMask::WINDOW));
1296 let ok = cache.add(recorder(&log, EventMask::WINDOW));
1297
1298 cache.get_mut(hidden).unwrap().set_hidden(true);
1299 cache.get_mut(disabled).unwrap().set_enabled(false);
1300 cache.broadcast(&focus());
1301
1302 assert_eq!(*log.borrow(), vec![ok]);
1303 assert_ne!(under_hidden, ok);
1304 }
1305
1306 #[test]
1307 fn the_run_loop_mask_can_silence_a_class() {
1308 let log = Rc::new(RefCell::new(Vec::new()));
1309 let mut cache = cache();
1310
1311 cache.add(recorder(&log, EventMask::WINDOW));
1312 cache.set_loop_mask(EventMask::ALL & !EventMask::WINDOW);
1313 cache.broadcast(&focus());
1314
1315 assert!(log.borrow().is_empty());
1316 }
1317
1318 #[test]
1319 fn a_broadcast_queues_an_engine_event_with_the_recipient_count() {
1320 let log = Rc::new(RefCell::new(Vec::new()));
1321 let mut cache = cache();
1322
1323 cache.add(recorder(&log, EventMask::WINDOW));
1324 cache.add(recorder(&log, EventMask::WINDOW));
1325 cache.take_pending_events();
1326 cache.broadcast(&focus());
1327
1328 match cache.take_pending_events().as_slice() {
1329 [Event::Engine(EngineEvent::EventBroadcast { kind, recipients })] => {
1330 assert_eq!(*kind, crate::event::EventKind::WindowFocusChanged);
1331 assert_eq!(*recipients, 2);
1332 }
1333 other => panic!("unexpected pending events: {other:?}"),
1334 }
1335 }
1336 /// A `Widget` that logs `(name, phase)` for every input event, and can capture or stop.
1337 struct Probe {
1338 core: WidgetCore,
1339 name: &'static str,
1340 capture: bool,
1341 stops_in: Option<EventPhase>,
1342 log: Rc<RefCell<Vec<(&'static str, EventPhase)>>>,
1343 }
1344
1345 impl Widget for Probe {
1346 /// Returns the shared state.
1347 ///
1348 /// # Returns
1349 ///
1350 /// The `WidgetCore`.
1351 fn core(&self) -> &WidgetCore {
1352 &self.core
1353 }
1354
1355 /// Returns the shared state for modification.
1356 ///
1357 /// # Returns
1358 ///
1359 /// The `WidgetCore`.
1360 fn core_mut(&mut self) -> &mut WidgetCore {
1361 &mut self.core
1362 }
1363
1364 /// Draws nothing.
1365 ///
1366 /// # Arguments
1367 ///
1368 /// * `_p` - The painter.
1369 fn paint(&self, _p: &mut dyn crate::paint::Painter) {}
1370
1371 /// Whether this probe captures.
1372 ///
1373 /// # Returns
1374 ///
1375 /// The configured flag.
1376 fn handles_capture(&self) -> bool {
1377 self.capture
1378 }
1379
1380 /// Logs the phase; stops in the configured phase.
1381 ///
1382 /// # Arguments
1383 ///
1384 /// * `_event` - The event.
1385 /// * `ctx` - The context.
1386 ///
1387 /// # Returns
1388 ///
1389 /// [`Propagation::Stop`] in the configured phase, otherwise [`Propagation::Continue`].
1390 fn handle_event(&mut self, _event: &Event, ctx: &mut EventCtx) -> Propagation {
1391 self.log.borrow_mut().push((self.name, ctx.phase()));
1392
1393 if self.stops_in == Some(ctx.phase()) {
1394 Propagation::Stop
1395 } else {
1396 Propagation::Continue
1397 }
1398 }
1399 }
1400
1401 type PhaseLog = Rc<RefCell<Vec<(&'static str, EventPhase)>>>;
1402
1403 /// Adds a probe with every event class enabled under `parent`.
1404 fn probe(
1405 cache: &mut WidgetCache,
1406 parent: WidgetId,
1407 name: &'static str,
1408 capture: bool,
1409 stops_in: Option<EventPhase>,
1410 log: &PhaseLog,
1411 ) -> WidgetId {
1412 let mut core = WidgetCore::new(point(0, 0), size(50, 50));
1413
1414 core.set_event_mask(EventMask::ALL);
1415 cache.add_child(
1416 parent,
1417 Box::new(Probe {
1418 core,
1419 name,
1420 capture,
1421 stops_in,
1422 log: log.clone(),
1423 }),
1424 )
1425 }
1426
1427 fn key_press(id: WidgetId) -> Event {
1428 Event::KeyPressed {
1429 id,
1430 key: crate::input::Key::Return,
1431 modifiers: crate::input::Modifiers::empty(),
1432 repeat: false,
1433 }
1434 }
1435
1436 #[test]
1437 fn delivery_is_capture_then_target_then_bubble() {
1438 use EventPhase::{Bubble, Capture, Target};
1439
1440 let log: PhaseLog = Rc::default();
1441 let mut cache = cache();
1442 let dialog = probe(&mut cache, 0, "dialog", true, None, &log);
1443 let group = probe(&mut cache, dialog, "group", false, None, &log);
1444 let field = probe(&mut cache, group, "field", true, None, &log);
1445
1446 cache.propagate(field, &key_press(field));
1447
1448 assert_eq!(
1449 *log.borrow(),
1450 vec![
1451 ("dialog", Capture),
1452 ("field", Target),
1453 ("group", Bubble),
1454 ("dialog", Bubble),
1455 ]
1456 );
1457 }
1458
1459 #[test]
1460 fn stop_in_each_phase_ends_delivery() {
1461 use EventPhase::{Bubble, Capture, Target};
1462
1463 for (phase, expected) in [
1464 (Capture, vec![("outer", Capture)]),
1465 (Target, vec![("outer", Capture), ("field", Target)]),
1466 (
1467 Bubble,
1468 vec![("outer", Capture), ("field", Target), ("inner", Bubble)],
1469 ),
1470 ] {
1471 let log: PhaseLog = Rc::default();
1472 let mut cache = cache();
1473 let stopper = |name| {
1474 if name == "outer" && phase == Capture {
1475 Some(Capture)
1476 } else {
1477 None
1478 }
1479 };
1480 let outer = probe(&mut cache, 0, "outer", true, stopper("outer"), &log);
1481 let inner_stop = if phase == Bubble { Some(Bubble) } else { None };
1482 let inner = probe(&mut cache, outer, "inner", false, inner_stop, &log);
1483 let field_stop = if phase == Target { Some(Target) } else { None };
1484 let field = probe(&mut cache, inner, "field", false, field_stop, &log);
1485
1486 let mut ctx = EventCtx::default();
1487 let result = cache.propagate_with(field, &key_press(field), &mut ctx);
1488
1489 assert_eq!(result, Propagation::Stop);
1490 assert_eq!(*log.borrow(), expected, "stop in {phase:?}");
1491 }
1492 }
1493
1494 #[test]
1495 fn a_default_button_sees_the_key_a_text_field_ignored() {
1496 use EventPhase::{Bubble, Target};
1497
1498 let log: PhaseLog = Rc::default();
1499 let mut cache = cache();
1500 let dialog = probe(&mut cache, 0, "dialog", false, Some(Bubble), &log);
1501 let field = probe(&mut cache, dialog, "field", false, None, &log);
1502
1503 let mut ctx = EventCtx::default();
1504 let result = cache.propagate_with(field, &key_press(field), &mut ctx);
1505
1506 assert_eq!(result, Propagation::Stop);
1507 assert_eq!(*log.borrow(), vec![("field", Target), ("dialog", Bubble)]);
1508 }
1509
1510 #[test]
1511 fn disabled_hidden_and_masked_widgets_are_skipped() {
1512 use EventPhase::Target;
1513
1514 let log: PhaseLog = Rc::default();
1515 let mut cache = cache();
1516 let disabled = probe(&mut cache, 0, "disabled", false, None, &log);
1517 let hidden = probe(&mut cache, disabled, "hidden", false, None, &log);
1518 let masked = probe(&mut cache, hidden, "masked", false, None, &log);
1519 let target = probe(&mut cache, masked, "target", false, None, &log);
1520
1521 cache.get_mut(disabled).unwrap().set_enabled(false);
1522 cache.get_mut(hidden).unwrap().set_hidden(true);
1523 cache.set_event_mask(masked, EventMask::POINTER_BUTTONS);
1524 cache.propagate(target, &key_press(target));
1525
1526 assert_eq!(*log.borrow(), vec![("target", Target)]);
1527 }
1528
1529 #[test]
1530 fn semantic_and_hover_events_do_not_propagate() {
1531 let log: PhaseLog = Rc::default();
1532 let mut cache = cache();
1533 let parent = probe(&mut cache, 0, "parent", true, None, &log);
1534 let child = probe(&mut cache, parent, "child", false, None, &log);
1535
1536 cache.propagate(child, &Event::PointerEntered { id: child });
1537 cache.propagate(
1538 child,
1539 &Event::Clicked {
1540 id: child,
1541 button: crate::input::MouseButton::Left,
1542 count: 1,
1543 },
1544 );
1545
1546 assert_eq!(
1547 *log.borrow(),
1548 vec![("child", EventPhase::Target), ("child", EventPhase::Target)],
1549 "each event reaches the target once, and never the capturing parent"
1550 );
1551 }
1552
1553 #[test]
1554 fn a_pointer_press_bubbles_to_parents_through_the_cache() {
1555 let log: PhaseLog = Rc::default();
1556 let mut cache = cache();
1557 let parent = probe(&mut cache, 0, "parent", false, None, &log);
1558 probe(&mut cache, parent, "child", false, None, &log);
1559
1560 cache.handle_event(InputEvent::MouseDown {
1561 position: point(5, 5),
1562 button: crate::input::MouseButton::Left,
1563 clicks: 1,
1564 });
1565
1566 let names: Vec<_> = log.borrow().iter().map(|(n, _)| *n).collect();
1567
1568 assert_eq!(names, vec!["child", "parent"]);
1569 }
1570}