Skip to main content

vizia_core/events/
event_manager.rs

1use crate::context::{InternalEvent, ResourceContext};
2use crate::events::EventMeta;
3use crate::prelude::*;
4#[cfg(debug_assertions)]
5use crate::systems::compute_matched_rules;
6use crate::systems::{binding_system, hover_system};
7use crate::tree::{focus_backward, focus_forward, is_navigatable};
8#[cfg(debug_assertions)]
9use log::debug;
10use std::any::Any;
11use vizia_storage::LayoutParentIterator;
12#[cfg(debug_assertions)]
13use vizia_storage::ParentIterator;
14use vizia_storage::TreeIterator;
15
16/// Dispatches events to views and models.
17///
18/// The [EventManager] is responsible for taking the events in the event queue in cx
19/// and dispatching them to views and models based on the target and propagation metadata of the event.
20#[doc(hidden)]
21pub struct EventManager {
22    // Queue of events to be processed.
23    event_queue: Vec<Event>,
24}
25
26impl Default for EventManager {
27    fn default() -> Self {
28        Self::new()
29    }
30}
31
32impl EventManager {
33    pub fn new() -> Self {
34        EventManager { event_queue: Vec::with_capacity(10) }
35    }
36
37    /// Flush the event queue, dispatching events to their targets.
38    /// Returns whether there are still more events to process, i.e. the event handlers sent events.
39    pub fn flush_events(
40        &mut self,
41        cx: &mut Context,
42        mut window_event_callback: impl FnMut(&WindowEvent),
43    ) {
44        let _scope = crate::profiling::scope("flush_events");
45        while {
46            // Clear the event queue in the event manager.
47            self.event_queue.clear();
48
49            // Move events from cx to event manager. This is so the cx can be passed
50            // mutably to the view when handling events.
51            self.event_queue.extend(cx.drain_events());
52
53            // Loop over the events in the event queue.
54            'events: for event in self.event_queue.iter_mut() {
55                let mut modifier_scope = ModifierScope::new(cx, event.meta.modifiers);
56                let cx = modifier_scope.context();
57                let keyboard_lock_root = keyboard_event_lock_root(cx, event);
58                let mut is_drop_event = false;
59                event.map(|window_event: &WindowEvent, _| {
60                    is_drop_event = matches!(window_event, WindowEvent::Drop(_));
61                });
62
63                // Handle internal events.
64                event.take(|internal_event, meta| match internal_event {
65                    InternalEvent::Redraw => cx.needs_redraw(Entity::root()),
66                    InternalEvent::RefreshHover => {
67                        hover_system(cx, meta.origin);
68                        meta.consume();
69                    }
70                    InternalEvent::LoadImage { path, image, policy } => {
71                        if let Some(image) = image.lock().unwrap().take() {
72                            ResourceContext::new(cx).load_image(path, image, policy);
73                        }
74                    }
75                    InternalEvent::LoadSvg { path, data, policy } => {
76                        cx.load_svg(&path, &data, policy);
77                    }
78                    InternalEvent::LoadFont { path, data } => {
79                        ResourceContext::new(cx).load_font(path, &data);
80                    }
81                    InternalEvent::LoadTranslation { lang, path, ftl } => {
82                        ResourceContext::new(cx).load_translation(lang, path, &ftl);
83                    }
84                    InternalEvent::UpdateResourceStatus { path, status } => {
85                        cx.resource_manager.set_resource_status(path, status);
86                    }
87                });
88
89                // Send events to any global listeners.
90                let mut global_listeners = vec![];
91                std::mem::swap(&mut cx.global_listeners, &mut global_listeners);
92                for listener in &global_listeners {
93                    cx.with_current(Entity::root(), |cx| {
94                        listener(&mut EventContext::new(cx), event)
95                    });
96                }
97                std::mem::swap(&mut cx.global_listeners, &mut global_listeners);
98
99                // Send events to any local listeners.
100                let listeners = cx.listeners.keys().copied().collect::<Vec<Entity>>();
101                for entity in listeners {
102                    if let Some(lock_root) = keyboard_lock_root
103                        && !entity.is_descendant_of(&cx.tree, lock_root)
104                    {
105                        continue;
106                    }
107
108                    if let Some(listener) = cx.listeners.remove(&entity) {
109                        if let Some(mut event_handler) = cx.views.remove(&entity) {
110                            cx.with_current(entity, |cx| {
111                                (listener)(
112                                    event_handler.as_mut(),
113                                    &mut EventContext::new(cx),
114                                    event,
115                                );
116                            });
117
118                            cx.views.insert(entity, event_handler);
119                        }
120
121                        cx.listeners.insert(entity, listener);
122                    }
123
124                    if event.meta.consumed {
125                        clear_drop_state_for_drop_event(is_drop_event, &mut cx.drop_data);
126                        continue 'events;
127                    }
128                }
129
130                // Handle state updates for window events.
131                event.map(|window_event, meta| {
132                    if cx.windows.contains_key(&meta.origin) {
133                        internal_state_updates(cx, window_event, meta);
134                    }
135                });
136
137                // Skip to next event if the current event was consumed when handling internal state updates.
138                if event.meta.consumed {
139                    clear_drop_state_for_drop_event(is_drop_event, &mut cx.drop_data);
140                    continue 'events;
141                }
142
143                let cx = &mut EventContext::new(cx);
144
145                // Copy the target to prevent multiple mutable borrows error.
146                let target = event.meta.target;
147
148                // Send event to target.
149                if keyboard_lock_root
150                    .map(|lock_root| target.is_descendant_of(cx.tree, lock_root))
151                    .unwrap_or(true)
152                {
153                    visit_entity(cx, target, event);
154                }
155
156                // Skip to next event if the current event was consumed.
157                if event.meta.consumed {
158                    clear_drop_state_for_drop_event(is_drop_event, &mut *cx.drop_data);
159                    continue 'events;
160                }
161
162                // Propagate up from target to root (not including the target).
163                if event.meta.propagation == Propagation::Up {
164                    // Create a parent iterator and skip the first element which is the target.
165                    let iter = target.parent_iter(cx.tree).skip(1);
166
167                    for entity in iter {
168                        if let Some(lock_root) = keyboard_lock_root
169                            && !entity.is_descendant_of(cx.tree, lock_root)
170                        {
171                            break;
172                        }
173
174                        // Send event to all ancestors of the target.
175                        visit_entity(cx, entity, event);
176
177                        // Skip to the next event if the current event was consumed.
178                        if event.meta.consumed {
179                            clear_drop_state_for_drop_event(is_drop_event, &mut *cx.drop_data);
180                            continue 'events;
181                        }
182                    }
183                }
184
185                // Propagate the event down the subtree from the target (not including the target).
186                if event.meta.propagation == Propagation::Subtree {
187                    // Create a branch (subtree) iterator and skip the first element which is the target.
188                    let iter = target.branch_iter(cx.tree).skip(1);
189
190                    for entity in iter {
191                        if keyboard_lock_root
192                            .map(|lock_root| entity.is_descendant_of(cx.tree, lock_root))
193                            .unwrap_or(true)
194                        {
195                            // Send event to all entities in the subtree after the target.
196                            visit_entity(cx, entity, event);
197                        }
198
199                        // Skip to the next event if the current event was consumed.
200                        if event.meta.consumed {
201                            clear_drop_state_for_drop_event(is_drop_event, &mut *cx.drop_data);
202                            continue 'events;
203                        }
204                    }
205                }
206
207                event.map(|window_event: &WindowEvent, _| {
208                    (window_event_callback)(window_event);
209                });
210
211                clear_drop_state_for_drop_event(is_drop_event, &mut *cx.drop_data);
212            }
213
214            binding_system(cx);
215
216            // Return true if there are new events in the queue.
217            cx.has_queued_events()
218        } {}
219    }
220}
221
222/// One dispatch borrows the application and restores its ambient native flags on every exit.
223struct ModifierScope<'a> {
224    cx: &'a mut Context,
225    previous: Modifiers,
226}
227
228impl<'a> ModifierScope<'a> {
229    fn new(cx: &'a mut Context, snapshot: Option<Modifiers>) -> Self {
230        let previous = cx.modifiers;
231        cx.modifiers = snapshot.unwrap_or(previous);
232        Self { cx, previous }
233    }
234
235    fn context(&mut self) -> &mut Context {
236        self.cx
237    }
238}
239
240impl Drop for ModifierScope<'_> {
241    fn drop(&mut self) {
242        self.cx.modifiers = self.previous;
243    }
244}
245
246fn clear_drop_state_for_drop_event(is_drop_event: bool, drop_data: &mut Option<DropData>) {
247    if is_drop_event && drop_data.is_some() {
248        *drop_data = None;
249    }
250}
251
252fn is_keyboard_window_event(window_event: &WindowEvent) -> bool {
253    matches!(
254        window_event,
255        WindowEvent::KeyDown(_, _)
256            | WindowEvent::KeyUp(_, _)
257            | WindowEvent::CharInput(_)
258            | WindowEvent::ImeActivate(_)
259            | WindowEvent::ImeCommit(_)
260            | WindowEvent::ImePreedit(_, _)
261            | WindowEvent::SetImeCursorArea(_, _)
262    )
263}
264
265fn keyboard_event_lock_root(cx: &Context, event: &mut Event) -> Option<Entity> {
266    let mut lock_root = None;
267
268    event.map(|window_event: &WindowEvent, _| {
269        if is_keyboard_window_event(window_event) {
270            let candidate = cx.tree.lock_focus_within(cx.focused);
271            if candidate != Entity::root() {
272                lock_root = Some(candidate);
273            }
274        }
275    });
276
277    lock_root
278}
279
280fn visit_entity(cx: &mut EventContext, entity: Entity, event: &mut Event) {
281    // Send event to models attached to the entity
282    if let Some(ids) =
283        cx.models.get(&entity).map(|models| models.keys().cloned().collect::<Vec<_>>())
284    {
285        for id in ids {
286            if let Some(mut model) =
287                cx.models.get_mut(&entity).and_then(|models| models.remove(&id))
288            {
289                cx.current = entity;
290
291                model.event(cx, event);
292
293                cx.models.get_mut(&entity).and_then(|models| models.insert(id, model));
294            }
295        }
296    }
297
298    // Return early if the event was consumed by a model
299    if event.meta.consumed {
300        return;
301    }
302
303    // Send event to the view attached to the entity
304    if let Some(mut view) = cx.views.remove(&entity) {
305        cx.current = entity;
306        view.event(cx, event);
307
308        cx.views.insert(entity, view);
309    }
310}
311
312/// Update the internal state of the cx based on received window event and emit window event to relevant target.
313fn internal_state_updates(cx: &mut Context, window_event: &WindowEvent, meta: &mut EventMeta) {
314    cx.current = meta.target;
315
316    match window_event {
317        WindowEvent::Drop(drop_data) => {
318            cx.drop_data = Some(drop_data.clone());
319        }
320
321        WindowEvent::MouseMove(x, y) => {
322            if !x.is_nan() && !y.is_nan() {
323                cx.mouse.previous_cursor_x = cx.mouse.cursor_x;
324                cx.mouse.previous_cursor_y = cx.mouse.cursor_y;
325                cx.mouse.cursor_x = *x;
326                cx.mouse.cursor_y = *y;
327
328                hover_system(cx, meta.origin);
329                if cx.drop_data.is_some() || cx.drag_hovered != Entity::null() {
330                    dispatch_drag_events(cx, *x, *y);
331                }
332
333                if let Some(drag_view) = cx.active_drag_view {
334                    if cx.drop_data.is_some() {
335                        position_drag_view(cx, drag_view, *x, *y);
336                    } else {
337                        hide_drag_view(cx, drag_view);
338                        cx.active_drag_view = None;
339                    }
340                }
341
342                mutate_direct_or_up(meta, cx.captured, cx.hovered, false);
343            }
344
345            // if cx.mouse.cursor_x != cx.mouse.previous_cursor_x
346            //     || cx.mouse.cursor_y != cx.mouse.previous_cursor_y
347            // {
348            // }
349
350            // if let Some(dropped_file) = cx.dropped_file.take() {
351            //     emit_direct_or_up(
352            //         cx,
353            //         WindowEvent::DroppedFile(dropped_file),
354            //         cx.captured,
355            //         cx.hovered,
356            //         true,
357            //     );
358            // }
359        }
360        WindowEvent::MouseDown(button) => {
361            // do direct state-updates
362            match button {
363                MouseButton::Left => {
364                    cx.mouse.left.state = MouseButtonState::Pressed;
365
366                    cx.mouse.left.pos_down = (cx.mouse.cursor_x, cx.mouse.cursor_y);
367                    cx.mouse.left.pressed = cx.hovered;
368                    cx.triggered = cx.hovered;
369
370                    let disabled = cx.style.disabled.get(cx.hovered).copied().unwrap_or_default();
371
372                    if let Some(pseudo_classes) = cx.style.pseudo_classes.get_mut(cx.triggered)
373                        && !disabled
374                    {
375                        pseudo_classes.set(PseudoClassFlags::ACTIVE, true);
376                        cx.needs_restyle(cx.triggered);
377                    }
378                    let focusable = cx
379                        .style
380                        .abilities
381                        .get(cx.hovered)
382                        .filter(|abilities| abilities.contains(Abilities::FOCUSABLE))
383                        .is_some();
384
385                    // Reset drag data
386                    cx.drop_data = None;
387                    cx.drag_hovered = Entity::null();
388                    if let Some(drag_view) = cx.active_drag_view.take() {
389                        hide_drag_view(cx, drag_view);
390                    }
391
392                    cx.with_current(if focusable { cx.hovered } else { cx.focused }, |cx| {
393                        cx.focus_with_visibility(false)
394                    });
395                }
396                MouseButton::Right => {
397                    cx.mouse.right.state = MouseButtonState::Pressed;
398                    cx.mouse.right.pos_down = (cx.mouse.cursor_x, cx.mouse.cursor_y);
399                    cx.mouse.right.pressed = cx.hovered;
400                }
401                MouseButton::Middle => {
402                    cx.mouse.middle.state = MouseButtonState::Pressed;
403                    cx.mouse.middle.pos_down = (cx.mouse.cursor_x, cx.mouse.cursor_y);
404                    cx.mouse.middle.pressed = cx.hovered;
405                }
406                _ => {}
407            }
408
409            // emit trigger events
410            if matches!(button, MouseButton::Left) {
411                emit_direct_or_up(
412                    cx,
413                    WindowEvent::PressDown { mouse: true },
414                    cx.captured,
415                    cx.triggered,
416                    true,
417                );
418            }
419
420            // track double/triple -click
421            let new_click_time = Instant::now();
422            let click_duration = new_click_time - cx.click_time;
423            let new_click_pos = (cx.mouse.cursor_x, cx.mouse.cursor_y);
424            let double_click_interval = cx.environment().double_click_interval;
425            if click_duration <= double_click_interval
426                && new_click_pos == cx.click_pos
427                && *button == cx.click_button
428            {
429                if cx.clicks <= 2 {
430                    cx.clicks += 1;
431                    let event = if cx.clicks == 3 {
432                        WindowEvent::MouseTripleClick(*button)
433                    } else {
434                        WindowEvent::MouseDoubleClick(*button)
435                    };
436                    meta.consume();
437                    emit_direct_or_up(cx, event, cx.captured, cx.hovered, true);
438                }
439            } else {
440                cx.clicks = 1;
441            }
442            cx.click_time = new_click_time;
443            cx.click_pos = new_click_pos;
444            cx.click_button = *button;
445            mutate_direct_or_up(meta, cx.captured, cx.hovered, true);
446        }
447        WindowEvent::MouseUp(button) => {
448            let had_drop_data = cx.drop_data.is_some();
449
450            if let Some(drag_view) = cx.active_drag_view.take() {
451                hide_drag_view(cx, drag_view);
452            }
453
454            match button {
455                MouseButton::Left => {
456                    cx.mouse.left.pos_up = (cx.mouse.cursor_x, cx.mouse.cursor_y);
457                    cx.mouse.left.released = cx.hovered;
458                    cx.mouse.left.state = MouseButtonState::Released;
459                }
460                MouseButton::Right => {
461                    cx.mouse.right.pos_up = (cx.mouse.cursor_x, cx.mouse.cursor_y);
462                    cx.mouse.right.released = cx.hovered;
463                    cx.mouse.right.state = MouseButtonState::Released;
464                }
465                MouseButton::Middle => {
466                    cx.mouse.middle.pos_up = (cx.mouse.cursor_x, cx.mouse.cursor_y);
467                    cx.mouse.middle.released = cx.hovered;
468                    cx.mouse.middle.state = MouseButtonState::Released;
469                }
470                _ => {}
471            }
472
473            if matches!(button, MouseButton::Left) {
474                if cx.hovered == cx.triggered {
475                    let disabled = cx.style.disabled.get(cx.hovered).copied().unwrap_or_default();
476
477                    if !disabled {
478                        emit_direct_or_up(
479                            cx,
480                            WindowEvent::Press { mouse: true },
481                            cx.captured,
482                            cx.triggered,
483                            true,
484                        );
485                    }
486                }
487
488                if let Some(pseudo_classes) = cx.style.pseudo_classes.get_mut(cx.triggered) {
489                    pseudo_classes.set(PseudoClassFlags::ACTIVE, false);
490                }
491
492                cx.needs_restyle(cx.triggered);
493
494                cx.triggered = Entity::null();
495            }
496
497            if had_drop_data {
498                let drop_data = cx.drop_data.take();
499
500                // Dispatch Drop to the hovered drop target.
501                if cx.drag_hovered != Entity::null() {
502                    if let Some(data) = drop_data {
503                        cx.send_event(Event::new(WindowEvent::Drop(data)).target(cx.drag_hovered));
504                    }
505
506                    // Drag is ending, so notify the last hovered drop target that the pointer left.
507                    cx.send_event(Event::new(WindowEvent::DragLeave).target(cx.drag_hovered));
508                }
509                cx.drag_hovered = Entity::null();
510            }
511            // Always route MouseUp through the captured entity (the drag source) so it
512            // receives the release and can reset its dragging state via DragModel::MouseUp.
513            // Capture is cleared by DragModel calling cx.release(). Drop and DragLeave are
514            // already queued to drag_hovered and will fire on the next event cycle.
515            mutate_direct_or_up(meta, cx.captured, cx.hovered, true);
516        }
517        WindowEvent::MouseScroll(_, _) => {
518            meta.target = cx.hovered;
519        }
520        WindowEvent::KeyDown(code, _) => {
521            meta.target = cx.focused;
522
523            #[cfg(debug_assertions)]
524            if *code == Code::KeyP && cx.modifiers.ctrl() {
525                for entity in TreeIterator::full(&cx.tree) {
526                    if let Some(models) = cx.models.get(&entity)
527                        && !models.is_empty()
528                    {
529                        debug!("Models for {}", entity);
530                        for (_, model) in models.iter() {
531                            debug!("M: {:?}", model.name())
532                        }
533                    }
534                }
535            }
536
537            #[cfg(debug_assertions)]
538            if *code == Code::KeyI {
539                debug!("Entity tree");
540                let (tree, views, cache) = (&cx.tree, &cx.views, &cx.cache);
541                let has_next_sibling = |entity| tree.get_next_sibling(entity).is_some();
542                let root_indents = |entity: Entity| {
543                    let parent_iter = ParentIterator::new(tree, Some(entity));
544                    parent_iter
545                        .skip(1)
546                        .collect::<Vec<_>>()
547                        .into_iter()
548                        .rev()
549                        .skip(1)
550                        .map(|entity| if has_next_sibling(entity) { "│   " } else { "    " })
551                        .collect::<String>()
552                };
553                let local_idents =
554                    |entity| if has_next_sibling(entity) { "├── " } else { "└── " };
555                let indents = |entity| root_indents(entity) + local_idents(entity);
556
557                for entity in TreeIterator::full(tree).skip(1) {
558                    if let Some(element_name) = views.get(&entity).and_then(|view| view.element()) {
559                        let w = cache.get_bounds(entity).w;
560                        let h = cache.get_bounds(entity).h;
561                        let classes = cx.style.classes.get(entity);
562                        let mut class_names = String::new();
563                        if let Some(classes) = classes {
564                            for class in classes.iter() {
565                                class_names += &format!(".{}", class);
566                            }
567                        }
568                        println!(
569                            "{}{} {}{} [x: {} y: {} w: {} h: {}]",
570                            indents(entity),
571                            entity,
572                            element_name,
573                            class_names,
574                            cache.get_bounds(entity).x,
575                            cache.get_bounds(entity).y,
576                            if w == f32::MAX { "inf".to_string() } else { w.to_string() },
577                            if h == f32::MAX { "inf".to_string() } else { h.to_string() },
578                        );
579                    }
580                }
581            }
582
583            #[cfg(debug_assertions)]
584            if *code == Code::KeyS
585                && cx.modifiers == Modifiers::CTRL | Modifiers::SHIFT | Modifiers::ALT
586            {
587                use crate::systems::compute_element_hash;
588                use vizia_style::selectors::bloom::BloomFilter;
589
590                let mut filter = BloomFilter::default();
591                compute_element_hash(cx.hovered, &cx.tree, &cx.style, &mut filter);
592                let result = compute_matched_rules(cx.hovered, &cx.style, &cx.tree, &filter);
593
594                let entity = cx.hovered;
595                debug!(
596                    "/* Matched rules for Entity: {} Parent: {:?} View: {} posx: {} posy: {} width: {} height: {}",
597                    entity,
598                    entity.parent(&cx.tree),
599                    cx.views
600                        .get(&entity)
601                        .map_or("<None>", |view| view.element().unwrap_or("<Unnamed>")),
602                    cx.cache.get_posx(entity),
603                    cx.cache.get_posy(entity),
604                    cx.cache.get_width(entity),
605                    cx.cache.get_height(entity)
606                );
607                for rule in result.into_iter() {
608                    for selectors in cx.style.rules.iter() {
609                        if *selectors.0 == rule.0 {
610                            debug!("{:?}", selectors.1.selector);
611                        }
612                    }
613                }
614            }
615
616            #[cfg(debug_assertions)]
617            if *code == Code::KeyT
618                && cx.modifiers == Modifiers::CTRL | Modifiers::SHIFT | Modifiers::ALT
619            {
620                // debug!("Loaded font face info:");
621                // for face in cx.text_context.font_system().db().faces() {
622                //     debug!(
623                //         "family: {:?}\npost_script_name: {:?}\nstyle: {:?}\nweight: {:?}\nstretch: {:?}\nmonospaced: {:?}\n",
624                //         face.families,
625                //         face.post_script_name,
626                //         face.style,
627                //         face.weight,
628                //         face.stretch,
629                //         face.monospaced,
630                //     );
631                // }
632            }
633
634            if *code == Code::F5 {
635                EventContext::new(cx).reload_styles().unwrap();
636            }
637
638            if *code == Code::Tab {
639                if cx.ime_state.is_composing() {
640                    return;
641                }
642
643                let lock_focus_to = cx.tree.lock_focus_within(cx.focused);
644
645                // If the locked subtree contains no navigatable items (e.g. a menu popup
646                // where items are focusable but not navigatable), fall back to global
647                // navigation so Tab can escape the lock. Dialog boxes with navigatable
648                // items inside are unaffected.
649                let effective_lock = if lock_focus_to != Entity::root()
650                    && !TreeIterator::full(&cx.tree)
651                        .any(|node| is_navigatable(&cx.tree, &cx.style, node, lock_focus_to))
652                {
653                    Entity::root()
654                } else {
655                    lock_focus_to
656                };
657
658                if cx.modifiers.shift() {
659                    let prev_focused = if let Some(prev_focused) =
660                        focus_backward(&cx.tree, &cx.style, cx.focused, effective_lock)
661                    {
662                        prev_focused
663                    } else {
664                        TreeIterator::full(&cx.tree)
665                            .rfind(|node| {
666                                is_navigatable(&cx.tree, &cx.style, *node, effective_lock)
667                            })
668                            .unwrap_or(Entity::root())
669                    };
670
671                    if prev_focused != cx.focused {
672                        cx.set_focus_pseudo_classes(cx.focused, false, true);
673                        cx.set_focus_pseudo_classes(prev_focused, true, true);
674                        cx.send_event(
675                            Event::new(WindowEvent::FocusOut)
676                                .target(cx.focused)
677                                .origin(Entity::root()),
678                        );
679                        cx.send_event(
680                            Event::new(WindowEvent::FocusIn)
681                                .target(prev_focused)
682                                .origin(Entity::root()),
683                        );
684                        cx.send_event(
685                            Event::new(ScrollEvent::ScrollToView(prev_focused))
686                                .target(prev_focused)
687                                .origin(Entity::root()),
688                        );
689
690                        cx.focused = prev_focused;
691
692                        if let Some(pseudo_classes) = cx.style.pseudo_classes.get_mut(cx.triggered)
693                        {
694                            pseudo_classes.set(PseudoClassFlags::ACTIVE, false);
695                            cx.needs_restyle(cx.triggered);
696                        }
697                        cx.triggered = Entity::null();
698                    }
699                } else {
700                    let next_focused = if let Some(next_focused) =
701                        focus_forward(&cx.tree, &cx.style, cx.focused, effective_lock)
702                    {
703                        next_focused
704                    } else {
705                        TreeIterator::full(&cx.tree)
706                            .find(|node| is_navigatable(&cx.tree, &cx.style, *node, effective_lock))
707                            .unwrap_or(Entity::root())
708                    };
709
710                    if next_focused != cx.focused {
711                        cx.set_focus_pseudo_classes(cx.focused, false, true);
712                        cx.set_focus_pseudo_classes(next_focused, true, true);
713                        cx.send_event(
714                            Event::new(WindowEvent::FocusOut)
715                                .target(cx.focused)
716                                .origin(Entity::root()),
717                        );
718                        cx.send_event(
719                            Event::new(WindowEvent::FocusIn)
720                                .target(next_focused)
721                                .origin(Entity::root()),
722                        );
723                        cx.send_event(
724                            Event::new(ScrollEvent::ScrollToView(next_focused))
725                                .target(next_focused)
726                                .origin(Entity::root()),
727                        );
728
729                        cx.focused = next_focused;
730
731                        if let Some(pseudo_classes) = cx.style.pseudo_classes.get_mut(cx.triggered)
732                        {
733                            pseudo_classes.set(PseudoClassFlags::ACTIVE, false);
734                            cx.needs_restyle(cx.triggered);
735                        }
736                        cx.triggered = Entity::null();
737                    }
738                }
739            }
740
741            if matches!(*code, Code::Enter | Code::NumpadEnter | Code::Space) {
742                cx.triggered = cx.focused;
743                if let Some(pseudo_classes) = cx.style.pseudo_classes.get_mut(cx.triggered) {
744                    pseudo_classes.set(PseudoClassFlags::ACTIVE, true);
745                }
746                cx.with_current(cx.focused, |cx| cx.emit(WindowEvent::PressDown { mouse: false }));
747            }
748        }
749        WindowEvent::KeyUp(code, _) => {
750            meta.target = cx.focused;
751            if matches!(code, Code::Enter | Code::NumpadEnter | Code::Space) {
752                if cx.focused == cx.triggered {
753                    cx.with_current(cx.triggered, |cx| {
754                        cx.emit(WindowEvent::Press { mouse: false })
755                    });
756                }
757                if let Some(pseudo_classes) = cx.style.pseudo_classes.get_mut(cx.triggered) {
758                    pseudo_classes.set(PseudoClassFlags::ACTIVE, false);
759                }
760                cx.needs_restyle(cx.triggered);
761                cx.triggered = Entity::null();
762            }
763        }
764        WindowEvent::CharInput(_) => {
765            meta.target = cx.focused;
766        }
767        WindowEvent::ImeActivate(_) => {
768            meta.target = cx.focused;
769        }
770        WindowEvent::ImeCommit(_) => {
771            meta.target = cx.focused;
772        }
773        WindowEvent::ImePreedit(_, _) => {
774            meta.target = cx.focused;
775        }
776        WindowEvent::SetImeCursorArea(_, _) => {
777            meta.target = cx.focused;
778        }
779        WindowEvent::WindowFocused(is_focused) => {
780            if *is_focused {
781                cx.set_focus_pseudo_classes(cx.focused, true, true);
782                cx.needs_restyle(cx.focused);
783                cx.needs_redraw(cx.focused);
784            } else {
785                cx.set_focus_pseudo_classes(cx.focused, false, true);
786                cx.needs_restyle(cx.focused);
787
788                cx.send_event(
789                    Event::new(WindowEvent::FocusVisibility(false))
790                        .target(cx.focused)
791                        .origin(Entity::root()), //.propagate(Propagation::Direct),
792                );
793
794                cx.send_event(
795                    Event::new(WindowEvent::MouseOut).target(cx.hovered).origin(Entity::root()), // .propagate(Propagation::Direct),
796                );
797            }
798        }
799        WindowEvent::MouseEnter => {
800            cx.set_pseudo_class(meta.origin, PseudoClassFlags::OVER, true);
801        }
802        WindowEvent::MouseLeave => {
803            cx.set_pseudo_class(meta.origin, PseudoClassFlags::OVER, false);
804
805            let ancestors = LayoutParentIterator::new(&cx.tree, cx.hovered).collect::<Vec<_>>();
806            for ancestor in ancestors {
807                cx.set_pseudo_class(ancestor, PseudoClassFlags::HOVER, false);
808            }
809
810            cx.hovered = Entity::null();
811        }
812
813        _ => {}
814    }
815}
816
817fn position_drag_view(cx: &mut Context, drag_view: Entity, x: f32, y: f32) {
818    if !cx.entity_manager.is_alive(drag_view) {
819        cx.active_drag_view = None;
820        return;
821    }
822
823    let left = cx.style.physical_to_logical(x);
824    let top = cx.style.physical_to_logical(y);
825
826    cx.with_current(drag_view, |cx| {
827        let mut ex = EventContext::new(cx);
828        ex.set_display(Display::Flex);
829        ex.set_left(Units::Pixels(left));
830        ex.set_top(Units::Pixels(top));
831    });
832}
833
834fn hide_drag_view(cx: &mut Context, drag_view: Entity) {
835    if !cx.entity_manager.is_alive(drag_view) {
836        return;
837    }
838
839    cx.with_current(drag_view, |cx| {
840        let mut ex = EventContext::new(cx);
841        ex.set_display(Display::None);
842    });
843}
844
845fn dispatch_drag_events(cx: &mut Context, x: f32, y: f32) {
846    if cx.drop_data.is_some() {
847        let hovered = cx.hovered;
848
849        if hovered != cx.drag_hovered {
850            if cx.drag_hovered != Entity::null() {
851                cx.send_event(Event::new(WindowEvent::DragLeave).target(cx.drag_hovered));
852            }
853
854            if hovered != Entity::null() {
855                cx.send_event(Event::new(WindowEvent::DragEnter).target(hovered));
856            }
857
858            cx.drag_hovered = hovered;
859        }
860
861        if hovered != Entity::null() {
862            cx.send_event(Event::new(WindowEvent::DragMove(x, y)).target(hovered));
863        }
864    } else if cx.drag_hovered != Entity::null() {
865        cx.send_event(Event::new(WindowEvent::DragLeave).target(cx.drag_hovered));
866        cx.drag_hovered = Entity::null();
867    }
868}
869
870fn mutate_direct_or_up(meta: &mut EventMeta, direct: Entity, up: Entity, root: bool) {
871    if direct != Entity::null() {
872        meta.target = direct;
873        meta.propagation = Propagation::Direct;
874    } else if up != Entity::root() || root {
875        meta.target = up;
876        meta.propagation = Propagation::Up;
877    } else {
878        meta.consume();
879    }
880}
881
882fn emit_direct_or_up<M: Any>(cx: &mut Context, message: M, direct: Entity, up: Entity, root: bool) {
883    let mut event = Event::new(message);
884    mutate_direct_or_up(&mut event.meta, direct, up, root);
885    cx.emit_custom(event);
886}
887
888#[cfg(test)]
889mod tests {
890    use crate::context::backend::BackendContext;
891    use crate::context::{Context, InternalEvent, WindowState};
892    use crate::events::{Event, EventManager, Propagation};
893    use crate::prelude::*;
894    use std::cell::RefCell;
895    use std::rc::Rc;
896    use vizia_id::GenerationalId;
897
898    #[derive(Clone, Copy, Debug)]
899    struct Derived;
900
901    #[test]
902    fn queued_hover_refresh_preserves_newer_cursor_position() {
903        let mut context = Context::default();
904        context.windows.insert(Entity::root(), WindowState::default());
905        context.mouse.cursor_x = 537.0;
906        context.mouse.cursor_y = 97.0;
907        let refresh = Event::new(InternalEvent::RefreshHover)
908            .target(Entity::root())
909            .origin(Entity::root())
910            .propagate(Propagation::Up);
911        context.send_event(
912            Event::new(WindowEvent::MouseMove(542.0, 433.0))
913                .target(Entity::root())
914                .origin(Entity::root())
915                .propagate(Propagation::Up),
916        );
917        context.send_event(refresh);
918
919        EventManager::new().flush_events(&mut context, |_| {});
920
921        assert_eq!(context.mouse.cursor_x, 542.0);
922        assert_eq!(context.mouse.cursor_y, 433.0);
923        assert_eq!(context.mouse.previous_cursor_x, 537.0);
924        assert_eq!(context.mouse.previous_cursor_y, 97.0);
925    }
926
927    #[test]
928    fn queued_ui_input_and_derived_events_keep_their_modifier_context() {
929        let seen = Rc::new(RefCell::new(Vec::new()));
930        let record = seen.clone();
931        let mut cx = BackendContext::new(Context::new());
932        cx.0.windows.insert(Entity::root(), Default::default());
933        cx.0.add_global_listener(move |cx, event| {
934            event.map(|event: &WindowEvent, _| {
935                let kind = match event {
936                    WindowEvent::KeyDown(_, _) => Some("key"),
937                    WindowEvent::KeyUp(_, _) => Some("release"),
938                    WindowEvent::MouseDown(_) => Some("click"),
939                    WindowEvent::PressDown { .. } => Some("press-down"),
940                    _ => None,
941                };
942                if let Some(kind) = kind {
943                    record.borrow_mut().push((kind, *cx.modifiers()));
944                }
945                if matches!(event, WindowEvent::KeyDown(_, _)) {
946                    cx.emit(Derived);
947                }
948            });
949            event.map(|_: &Derived, _| record.borrow_mut().push(("derived", *cx.modifiers())));
950        });
951        *cx.modifiers() = Modifiers::CTRL | Modifiers::SHIFT;
952        cx.emit_origin(WindowEvent::KeyDown(Code::ArrowLeft, None));
953        cx.emit_window_event(Entity::root(), WindowEvent::MouseDown(MouseButton::Left));
954        *cx.modifiers() = Modifiers::empty();
955        cx.emit_origin(WindowEvent::KeyUp(Code::ShiftLeft, None));
956        EventManager::new().flush_events(&mut cx.0, |_| {});
957        assert_eq!(
958            *seen.borrow(),
959            [
960                ("key", Modifiers::CTRL | Modifiers::SHIFT),
961                ("click", Modifiers::CTRL | Modifiers::SHIFT),
962                ("release", Modifiers::empty()),
963                ("derived", Modifiers::CTRL | Modifiers::SHIFT),
964                ("press-down", Modifiers::CTRL | Modifiers::SHIFT),
965            ]
966        );
967        assert_eq!(*cx.modifiers(), Modifiers::empty());
968    }
969
970    #[test]
971    fn consumed_input_restores_the_ambient_modifier_context() {
972        let seen = Rc::new(RefCell::new(Vec::new()));
973        let record = seen.clone();
974        let mut cx = Context::new();
975        let entity = Element::new(&mut cx).entity();
976        cx.with_current(entity, |cx| {
977            cx.add_listener(move |_: &mut Element, cx, event| {
978                event.map(|_: &Derived, meta| {
979                    record.borrow_mut().push(*cx.modifiers());
980                    meta.consume();
981                });
982            })
983        });
984        cx.modifiers = Modifiers::CTRL;
985        cx.emit_to(entity, Derived);
986        cx.modifiers = Modifiers::ALT;
987        EventManager::new().flush_events(&mut cx, |_| {});
988        assert_eq!(*seen.borrow(), [Modifiers::CTRL]);
989        assert_eq!(cx.modifiers, Modifiers::ALT);
990    }
991
992    #[test]
993    fn panicking_input_callback_restores_the_ambient_modifier_context() {
994        let mut cx = Context::new();
995        cx.add_global_listener(|cx, event| {
996            event.map(|_: &Derived, _| {
997                assert_eq!(*cx.modifiers(), Modifiers::SHIFT);
998                panic!("modifier callback panic");
999            });
1000        });
1001        cx.modifiers = Modifiers::SHIFT;
1002        cx.emit(Derived);
1003        cx.modifiers = Modifiers::ALT;
1004        let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1005            EventManager::new().flush_events(&mut cx, |_| {});
1006        }))
1007        .expect_err("the callback must panic");
1008        assert_eq!(panic.downcast_ref::<&str>(), Some(&"modifier callback panic"));
1009        assert_eq!(cx.modifiers, Modifiers::ALT);
1010    }
1011
1012    #[test]
1013    fn forwarded_ui_event_preserves_its_snapshot_and_proxy_event_uses_ambient() {
1014        let mut source = Context::new();
1015        source.drain_events().for_each(drop);
1016        source.modifiers = Modifiers::SHIFT;
1017        source.emit(Derived);
1018        let forwarded = source.drain_events().next().unwrap();
1019        let mut cx = BackendContext::new(Context::new());
1020        let seen = Rc::new(RefCell::new(Vec::new()));
1021        let record = seen.clone();
1022        cx.0.add_global_listener(move |cx, event| {
1023            event.map(|_: &Derived, _| record.borrow_mut().push(*cx.modifiers()));
1024        });
1025        *cx.modifiers() = Modifiers::CTRL;
1026        cx.0.emit_custom(forwarded);
1027        let forwarded = cx.0.drain_events().next().unwrap();
1028        EventContext::new(&mut cx.0).emit_custom(forwarded);
1029        let forwarded = cx.0.drain_events().next().unwrap();
1030        cx.send_event(forwarded);
1031        // A proxy has no UI emission context, so its payload arrives with no UI snapshot.
1032        cx.send_event(crate::events::ProxyEvent::new(Derived).into_event());
1033        *cx.modifiers() = Modifiers::ALT;
1034        EventManager::new().flush_events(&mut cx.0, |_| {});
1035        assert_eq!(*seen.borrow(), [Modifiers::SHIFT, Modifiers::ALT]);
1036        assert_eq!(*cx.modifiers(), Modifiers::ALT);
1037    }
1038
1039    #[test]
1040    fn queued_mouse_move_preserves_modifiers_for_every_hover_derivative() {
1041        let root = Entity::root();
1042        let mut cx = BackendContext::new(Context::new());
1043        cx.0.windows.insert(root, Default::default());
1044        cx.0.add_built_in_styles();
1045        let child = Element::new(&mut cx.0).width(Pixels(50.0)).height(Pixels(50.0)).entity();
1046        cx.set_window_size(root, 100.0, 100.0);
1047        cx.process_style_updates();
1048        cx.process_visual_updates();
1049        let seen = Rc::new(RefCell::new(Vec::new()));
1050        let record = seen.clone();
1051        cx.0.add_global_listener(move |cx, event| {
1052            event.map(|event: &WindowEvent, meta| {
1053                let kind = match event {
1054                    WindowEvent::MouseEnter => Some("enter"),
1055                    WindowEvent::MouseLeave => Some("leave"),
1056                    WindowEvent::MouseOver => Some("over"),
1057                    WindowEvent::MouseOut => Some("out"),
1058                    _ => None,
1059                };
1060                if let Some(kind) = kind {
1061                    record.borrow_mut().push((kind, meta.target, *cx.modifiers()));
1062                }
1063            });
1064        });
1065        *cx.modifiers() = Modifiers::SHIFT;
1066        cx.emit_origin(WindowEvent::MouseMove(25.0, 25.0));
1067        *cx.modifiers() = Modifiers::empty();
1068        cx.emit_origin(WindowEvent::KeyUp(Code::ShiftLeft, None));
1069        EventManager::new().flush_events(&mut cx.0, |_| {});
1070        assert_eq!(
1071            *seen.borrow(),
1072            [
1073                ("enter", child, Modifiers::SHIFT),
1074                ("leave", root, Modifiers::SHIFT),
1075                ("over", child, Modifiers::SHIFT),
1076                ("out", root, Modifiers::SHIFT),
1077            ]
1078        );
1079        assert_eq!(*cx.modifiers(), Modifiers::empty());
1080    }
1081}