Skip to main content

vizia_core/context/
event.rs

1use std::any::{Any, TypeId};
2use std::collections::{BinaryHeap, VecDeque};
3#[cfg(feature = "clipboard")]
4use std::error::Error;
5use std::rc::Rc;
6
7use hashbrown::hash_map::Entry;
8use hashbrown::{HashMap, HashSet};
9use vizia_storage::{LayoutTreeIterator, TreeIterator};
10
11use crate::animation::AnimId;
12use crate::cache::CachedData;
13use crate::events::{TimedEvent, TimedEventHandle, TimerState, ViewHandler};
14use crate::prelude::*;
15use crate::resource::{ImageOrSvg, ResourceManager, StoredImage};
16use crate::tree::{focus_backward, focus_forward, is_navigatable};
17use vizia_id::IdManager;
18use vizia_input::MouseState;
19
20use skia_safe::{Matrix, Rect};
21
22use crate::text::TextContext;
23#[cfg(feature = "clipboard")]
24use copypasta::ClipboardProvider;
25
26use super::{LocalizationContext, ModelData};
27
28type Views = HashMap<Entity, Box<dyn ViewHandler>>;
29type Models = HashMap<Entity, HashMap<TypeId, Box<dyn ModelData>>>;
30
31/// A context used when handling events.
32///
33/// The [`EventContext`] is provided by the [`event`](crate::prelude::View::event) method in [`View`], or the [`event`](crate::model::Model::event) method in [`Model`], and can be used to mutably access the
34/// desired style and layout properties of the current view.
35///
36/// # Example
37/// ```
38/// # use vizia_core::prelude::*;
39/// # use vizia_core::vg;
40/// # let cx = &mut Context::default();
41///
42/// pub struct CustomView {}
43///
44/// impl CustomView {
45///     pub fn new(cx: &mut Context) -> Handle<Self> {
46///         Self{}.build(cx, |_|{})
47///     }
48/// }
49///
50/// impl View for CustomView {
51///     fn event(&mut self, cx: &mut EventContext, event: &mut Event) {
52///         event.map(|window_event, _| match window_event {
53///             WindowEvent::Press{..} => {
54///                 // Change the view background color to red when pressed.
55///                 cx.set_background_color(Color::red());
56///             }
57///
58///             _=> {}
59///         });
60///     }
61/// }
62/// ```
63pub struct EventContext<'a> {
64    pub(crate) current: Entity,
65    entity_manager: &'a IdManager<Entity>,
66    pub(crate) captured: &'a mut Entity,
67    pub(crate) focused: &'a mut Entity,
68    pub(crate) hovered: &'a Entity,
69    pub(crate) triggered: &'a mut Entity,
70    pub(crate) style: &'a mut Style,
71    pub(crate) entity_identifiers: &'a HashMap<String, Entity>,
72    pub cache: &'a mut CachedData,
73    pub(crate) tree: &'a Tree<Entity>,
74    pub(crate) models: &'a mut Models,
75    pub(crate) views: &'a mut Views,
76    pub(crate) listeners:
77        &'a mut HashMap<Entity, Box<dyn Fn(&mut dyn ViewHandler, &mut EventContext, &mut Event)>>,
78    pub(crate) resource_manager: &'a mut ResourceManager,
79    pub(crate) text_context: &'a mut TextContext,
80    #[cfg(feature = "tokio")]
81    pub(crate) task_runtime: &'a super::TaskRuntime,
82    #[cfg(feature = "tokio")]
83    pub(crate) named_tasks: &'a super::NamedTaskMap,
84    pub(crate) modifiers: &'a Modifiers,
85    pub(crate) mouse: &'a MouseState<Entity>,
86    event_queue: &'a mut VecDeque<Event>,
87    pub(crate) event_schedule: &'a mut BinaryHeap<TimedEvent>,
88    pub(crate) next_event_id: &'a mut usize,
89    pub(crate) timers: &'a mut Vec<TimerState>,
90    pub(crate) running_timers: &'a mut BinaryHeap<TimerState>,
91    cursor_icon_locked_by: &'a mut Option<Entity>,
92    #[cfg(feature = "clipboard")]
93    clipboards: &'a mut HashMap<Entity, Box<dyn ClipboardProvider>>,
94    pub(crate) event_proxy: &'a mut Option<Box<dyn crate::context::EventProxy>>,
95    pub(crate) drop_data: &'a mut Option<DropData>,
96    pub(crate) active_drag_view: &'a mut Option<Entity>,
97    pub windows: &'a mut HashMap<Entity, WindowState>,
98}
99
100impl<'a> EventContext<'a> {
101    /// Queue a same-thread emission with its current UI modifier context.
102    pub(crate) fn send_event(&mut self, event: Event) {
103        self.event_queue.push_back(event.inherit_ui_modifiers(*self.modifiers));
104    }
105
106    /// Creates a new [EventContext].
107    pub fn new(cx: &'a mut Context) -> Self {
108        Self {
109            current: cx.current,
110            entity_manager: &cx.entity_manager,
111            captured: &mut cx.captured,
112            focused: &mut cx.focused,
113            hovered: &cx.hovered,
114            triggered: &mut cx.triggered,
115            entity_identifiers: &cx.entity_identifiers,
116            style: &mut cx.style,
117            cache: &mut cx.cache,
118            tree: &cx.tree,
119            models: &mut cx.models,
120            views: &mut cx.views,
121            listeners: &mut cx.listeners,
122            resource_manager: &mut cx.resource_manager,
123            text_context: &mut cx.text_context,
124            #[cfg(feature = "tokio")]
125            task_runtime: &cx.task_runtime,
126            #[cfg(feature = "tokio")]
127            named_tasks: &cx.named_tasks,
128            modifiers: &cx.modifiers,
129            mouse: &cx.mouse,
130            event_queue: &mut cx.event_queue,
131            event_schedule: &mut cx.event_schedule,
132            next_event_id: &mut cx.next_event_id,
133            timers: &mut cx.timers,
134            running_timers: &mut cx.running_timers,
135            cursor_icon_locked_by: &mut cx.cursor_icon_locked_by,
136            #[cfg(feature = "clipboard")]
137            clipboards: &mut cx.clipboards,
138            event_proxy: &mut cx.event_proxy,
139            drop_data: &mut cx.drop_data,
140            active_drag_view: &mut cx.active_drag_view,
141            windows: &mut cx.windows,
142        }
143    }
144
145    /// Creates a new [EventContext] with the given current [Entity].
146    pub fn new_with_current(cx: &'a mut Context, current: Entity) -> Self {
147        Self {
148            current,
149            entity_manager: &cx.entity_manager,
150            captured: &mut cx.captured,
151            focused: &mut cx.focused,
152            hovered: &cx.hovered,
153            triggered: &mut cx.triggered,
154            entity_identifiers: &cx.entity_identifiers,
155            style: &mut cx.style,
156            cache: &mut cx.cache,
157            tree: &cx.tree,
158            models: &mut cx.models,
159            views: &mut cx.views,
160            listeners: &mut cx.listeners,
161            resource_manager: &mut cx.resource_manager,
162            text_context: &mut cx.text_context,
163            #[cfg(feature = "tokio")]
164            task_runtime: &cx.task_runtime,
165            #[cfg(feature = "tokio")]
166            named_tasks: &cx.named_tasks,
167            modifiers: &cx.modifiers,
168            mouse: &cx.mouse,
169            event_queue: &mut cx.event_queue,
170            event_schedule: &mut cx.event_schedule,
171            next_event_id: &mut cx.next_event_id,
172            timers: &mut cx.timers,
173            running_timers: &mut cx.running_timers,
174            cursor_icon_locked_by: &mut cx.cursor_icon_locked_by,
175            #[cfg(feature = "clipboard")]
176            clipboards: &mut cx.clipboards,
177            event_proxy: &mut cx.event_proxy,
178            drop_data: &mut cx.drop_data,
179            active_drag_view: &mut cx.active_drag_view,
180            windows: &mut cx.windows,
181        }
182    }
183
184    /// Returns a reference to the current view associated with the event context.
185    pub fn get_view<V: View>(&self) -> Option<&V> {
186        self.views.get(&self.current).and_then(|view| view.downcast_ref::<V>())
187    }
188
189    /// Returns a reference to the specified view by entity.
190    pub fn get_view_with<V: View>(&self, entity: Entity) -> Option<&V> {
191        self.views.get(&entity).and_then(|view| view.downcast_ref::<V>())
192    }
193
194    pub fn close_window(&mut self) {
195        if let Some(state) = self.windows.get_mut(&self.current) {
196            state.should_close = true;
197        }
198    }
199
200    /// Returns the [Entity] id associated with the given identifier.
201    pub fn resolve_entity_identifier(&self, id: &str) -> Option<Entity> {
202        self.entity_identifiers.get(id).cloned()
203    }
204
205    /// Returns the descendant [Entity] id, of the current view, with the given element name if it exists.
206    pub fn get_entity_by_element_id(&self, element: &str) -> Option<Entity> {
207        let descendants = LayoutTreeIterator::subtree(self.tree, self.current);
208        for descendant in descendants {
209            if let Some(id) = self.views.get(&descendant).and_then(|view| view.element())
210                && id == element
211            {
212                return Some(descendant);
213            }
214        }
215
216        None
217    }
218
219    /// Returns the descendant [Entity] ids, of the current view, with the given class name.
220    pub fn get_entities_by_class(&self, class: &str) -> Vec<Entity> {
221        let mut entities = Vec::new();
222        let descendants = LayoutTreeIterator::subtree(self.tree, self.current);
223        for descendant in descendants {
224            if let Some(class_list) = self.style.classes.get(descendant)
225                && class_list.contains(class)
226            {
227                entities.push(descendant);
228            }
229        }
230
231        entities
232    }
233
234    /// Returns the [Entity] id of the current view.
235    pub fn current(&self) -> Entity {
236        self.current
237    }
238
239    /// Returns a reference to the keyboard modifiers state.
240    pub fn modifiers(&self) -> &Modifiers {
241        self.modifiers
242    }
243
244    /// Returns a reference to the mouse state.
245    pub fn mouse(&self) -> &MouseState<Entity> {
246        self.mouse
247    }
248
249    pub fn nth_child(&self, n: usize) -> Option<Entity> {
250        self.tree.get_child(self.current, n)
251    }
252
253    pub fn last_child(&self) -> Option<Entity> {
254        self.tree.get_last_child(self.current).copied()
255    }
256
257    pub fn with_current<T>(&mut self, entity: Entity, f: impl FnOnce(&mut Self) -> T) -> T {
258        let prev = self.current();
259        self.current = entity;
260        let ret = (f)(self);
261        self.current = prev;
262        ret
263    }
264
265    /// Returns true if in a drop state.
266    pub fn has_drop_data(&self) -> bool {
267        self.drop_data.is_some()
268    }
269
270    /// Returns the current drop payload, if any.
271    pub fn drop_data(&self) -> Option<&DropData> {
272        self.drop_data.as_ref()
273    }
274
275    /// Returns the active drag preview view entity, if any.
276    pub fn active_drag_view(&self) -> Option<Entity> {
277        *self.active_drag_view
278    }
279
280    /// Sets the active drag preview view entity.
281    pub fn set_active_drag_view(&mut self, drag_view: Option<Entity>) {
282        *self.active_drag_view = drag_view;
283    }
284
285    /// Returns the bounds of the current view.
286    pub fn bounds(&self) -> BoundingBox {
287        self.cache.get_bounds(self.current)
288    }
289
290    /// Returns the transformed bounds of an entity in window coordinates.
291    pub fn transformed_bounds(&self, entity: Entity) -> BoundingBox {
292        let bounds = self.cache.get_bounds(entity);
293
294        let transform = self.cache.absolute_transform(self.tree, entity);
295        // Skip map/rounding work when no effective transform is present.
296        if crate::cache::is_identity(&transform) {
297            return bounds;
298        }
299
300        let (rect, _) = transform.map_rect(Rect::from(bounds));
301        rect.into()
302    }
303
304    /// Returns transformed bounds expanded to pixel-snapped extents.
305    pub fn transformed_bounds_snapped(&self, entity: Entity) -> BoundingBox {
306        let bounds = self.transformed_bounds(entity);
307        BoundingBox::from_min_max(
308            bounds.left().floor(),
309            bounds.top().floor(),
310            bounds.right().ceil(),
311            bounds.bottom().ceil(),
312        )
313    }
314
315    /// Returns the transformed bounds of the current view's parent.
316    pub fn parent_transformed_bounds(&self) -> BoundingBox {
317        self.transformed_bounds(self.parent())
318    }
319
320    // pub fn set_bounds(&mut self, bounds: BoundingBox) {
321    //     self.cache.set_bounds(self.current, bounds);
322    // }
323
324    /// Returns the scale factor.
325    pub fn scale_factor(&self) -> f32 {
326        self.style.dpi_factor as f32
327    }
328
329    /// Converts logical points to physical pixels.
330    pub fn logical_to_physical(&self, logical: f32) -> f32 {
331        self.style.logical_to_physical(logical)
332    }
333
334    /// Convert physical pixels to logical points.
335    pub fn physical_to_logical(&self, physical: f32) -> f32 {
336        self.style.physical_to_logical(physical)
337    }
338
339    /// Returns the clip bounds of the current view.
340    pub fn clip_region(&self) -> BoundingBox {
341        let current_window = if self.tree.is_window(self.current) {
342            self.current
343        } else {
344            self.tree.get_parent_window(self.current).unwrap_or(Entity::root())
345        };
346
347        let window_bounds = self.cache.get_bounds(current_window);
348
349        // A cached entry (including None) is authoritative for this entity.
350        if let Some(clip_path) = self.cache.clip_path.get(self.current) {
351            return clip_path
352                .clone()
353                .map(|clip_path| Into::<BoundingBox>::into(*clip_path.bounds()))
354                .unwrap_or(window_bounds);
355        }
356
357        if self.style.ignore_clipping.get(self.current).copied().unwrap_or(false) {
358            return window_bounds;
359        }
360
361        let mut current = self.current;
362        while let Some(parent) = self.tree.get_parent(current) {
363            // A cached parent entry (including None) is authoritative.
364            if let Some(clip_path) = self.cache.clip_path.get(parent) {
365                return clip_path
366                    .clone()
367                    .map(|clip_path| Into::<BoundingBox>::into(*clip_path.bounds()))
368                    .unwrap_or(window_bounds);
369            }
370
371            if self.style.ignore_clipping.get(parent).copied().unwrap_or(false) {
372                return window_bounds;
373            }
374
375            if parent == current_window {
376                break;
377            }
378
379            current = parent;
380        }
381
382        window_bounds
383    }
384
385    /// Returns the 2D transform of the current view in window coordinates.
386    pub fn transform(&self) -> Matrix {
387        self.cache.absolute_transform(self.tree, self.current)
388    }
389
390    /// Trigger an animation with the given id to play on the current view.
391    pub fn play_animation(&mut self, anim_id: impl AnimId, duration: Duration, delay: Duration) {
392        if let Some(animation_id) = anim_id.get(self) {
393            self.style.enqueue_animation(self.current, animation_id, duration, delay);
394        }
395    }
396
397    /// Trigger an animation with the given id to play on a target view.
398    pub fn play_animation_for(
399        &mut self,
400        anim_id: impl AnimId,
401        target: &str,
402        duration: Duration,
403        delay: Duration,
404    ) {
405        if let Some(target_entity) = self.resolve_entity_identifier(target)
406            && let Some(animation_id) = anim_id.get(self)
407        {
408            self.style.enqueue_animation(target_entity, animation_id, duration, delay)
409        }
410    }
411
412    /// Returns true if the current view is currently animating with the given animation id.
413    pub fn is_animating(&self, anim_id: impl AnimId) -> bool {
414        if let Some(animation_id) = anim_id.get(self) {
415            return self.style.is_animating(self.current, animation_id);
416        }
417
418        false
419    }
420
421    /// Add a listener to an entity.
422    ///
423    /// A listener can be used to handle events which would not normally propagate to the entity.
424    /// For example, mouse events when a different entity has captured them. Useful for things like
425    /// closing a popup when clicking outside of its bounding box.
426    pub fn add_listener<F, W>(&mut self, listener: F)
427    where
428        W: View,
429        F: 'static + Fn(&mut W, &mut EventContext, &mut Event),
430    {
431        self.listeners.insert(
432            self.current,
433            Box::new(move |event_handler, context, event| {
434                if let Some(widget) = event_handler.downcast_mut::<W>() {
435                    (listener)(widget, context, event);
436                }
437            }),
438        );
439    }
440
441    /// Sets the language used by the application for localization.
442    pub fn set_language(&mut self, lang: LanguageIdentifier) {
443        if let Some(mut models) = self.models.remove(&Entity::root()) {
444            if let Some(model) = models.get_mut(&TypeId::of::<Environment>()) {
445                model.event(self, &mut Event::new(EnvironmentEvent::SetLocale(lang)));
446            }
447
448            self.models.insert(Entity::root(), models);
449        }
450    }
451
452    /// Adds a resource loader to the loading chain.
453    ///
454    /// Loaders are tried in list order, and this method inserts at the front so custom
455    /// loaders take priority over built-in loaders. The first loader that returns `true`
456    /// handles the request, and subsequent loaders are skipped.
457    pub fn add_resource_loader<L: crate::resource::ResourceLoader>(&mut self, loader: L) {
458        self.resource_manager.resource_loaders.insert(0, Box::new(loader));
459    }
460
461    pub fn load_image_encoded(&mut self, path: &str, data: &[u8], policy: ImageRetentionPolicy) {
462        let id = if let Some(image_id) = self.resource_manager.image_ids.get(path) {
463            *image_id
464        } else {
465            let id = self.resource_manager.image_id_manager.create();
466            self.resource_manager.image_ids.insert(path.to_owned(), id);
467            id
468        };
469
470        if let Some(image) = skia_safe::Image::from_encoded(skia_safe::Data::new_copy(data)) {
471            match self.resource_manager.images.entry(id) {
472                Entry::Occupied(mut occ) => {
473                    occ.get_mut().image = ImageOrSvg::Image(image);
474                    occ.get_mut().dirty = true;
475                    occ.get_mut().retention_policy = policy;
476                }
477                Entry::Vacant(vac) => {
478                    vac.insert(StoredImage {
479                        image: ImageOrSvg::Image(image),
480                        retention_policy: policy,
481                        used: true,
482                        dirty: false,
483                        observers: HashSet::new(),
484                    });
485                }
486            }
487            // Relayout only the entities that display this image (its observers) plus the current
488            // entity, rather than forcing a full tree relayout.
489            let observers: Vec<Entity> = self
490                .resource_manager
491                .images
492                .get(&id)
493                .map(|img| img.observers.iter().copied().collect())
494                .unwrap_or_default();
495            for observer in observers {
496                self.style.needs_relayout(observer);
497            }
498            self.style.needs_relayout(self.current);
499        }
500    }
501
502    /// Capture mouse input for the current view.
503    pub fn capture(&mut self) {
504        *self.captured = self.current;
505    }
506
507    /// Release mouse input capture for the current view.
508    pub fn release(&mut self) {
509        if self.current == *self.captured {
510            *self.captured = Entity::null();
511        }
512    }
513
514    /// Sets or clears pseudo-class flags of an entity, restyling the entities whose matched rules
515    /// may depend on them if they changed.
516    pub(crate) fn set_pseudo_class(
517        &mut self,
518        entity: Entity,
519        flags: PseudoClassFlags,
520        enabled: bool,
521    ) {
522        if let Some(pseudo_classes) = self.style.pseudo_classes.get_mut(entity) {
523            let previous = *pseudo_classes;
524            pseudo_classes.set(flags, enabled);
525            let changed = previous.symmetric_difference(*pseudo_classes);
526            self.style.needs_restyle_for_state(self.tree, entity, changed);
527        }
528    }
529
530    /// Enables or disables PseudoClassFlags for the focus of an entity
531    fn set_focus_pseudo_classes(&mut self, focused: Entity, enabled: bool, focus_visible: bool) {
532        self.set_pseudo_class(focused, PseudoClassFlags::FOCUS, enabled);
533        if !enabled || focus_visible {
534            self.set_pseudo_class(focused, PseudoClassFlags::FOCUS_VISIBLE, enabled);
535        }
536
537        let ancestors = focused.parent_iter(self.tree).collect::<Vec<_>>();
538        for ancestor in ancestors {
539            self.set_pseudo_class(ancestor, PseudoClassFlags::FOCUS_WITHIN, enabled);
540        }
541    }
542
543    /// Sets application focus to the current view with the specified focus visibility.
544    pub fn focus_with_visibility(&mut self, focus_visible: bool) {
545        let focusable = self.current == Entity::root()
546            || self
547                .style
548                .abilities
549                .get(self.current)
550                .is_some_and(|abilities| abilities.contains(Abilities::FOCUSABLE));
551        if !focusable {
552            return;
553        }
554
555        let old_focus = self.focused();
556        let new_focus = self.current();
557        self.set_focus_pseudo_classes(old_focus, false, focus_visible);
558        if self.current() != self.focused() {
559            self.emit_to(old_focus, WindowEvent::FocusOut);
560            self.emit_to(new_focus, WindowEvent::FocusIn);
561            *self.focused = self.current();
562        }
563        self.set_focus_pseudo_classes(new_focus, true, focus_visible);
564
565        self.emit_custom(Event::new(WindowEvent::FocusVisibility(focus_visible)).target(old_focus));
566        self.emit_custom(Event::new(WindowEvent::FocusVisibility(focus_visible)).target(new_focus));
567
568        self.needs_restyle();
569    }
570
571    /// Sets application focus to the current view using the previous focus visibility.
572    ///
573    /// Focused elements receive keyboard input events and can be selected with the `:focus` CSS pseudo-class selector.
574    pub fn focus(&mut self) {
575        let focused = self.focused();
576        let old_focus_visible = self
577            .style
578            .pseudo_classes
579            .get_mut(focused)
580            .filter(|class| class.contains(PseudoClassFlags::FOCUS_VISIBLE))
581            .is_some();
582        self.focus_with_visibility(old_focus_visible)
583    }
584
585    /// Moves the keyboard focus to the next navigable view.
586    pub fn focus_next(&mut self) {
587        let lock_focus_to = self.tree.lock_focus_within(*self.focused);
588        let next_focused = if let Some(next_focused) =
589            focus_forward(self.tree, self.style, *self.focused, lock_focus_to)
590        {
591            next_focused
592        } else {
593            TreeIterator::full(self.tree)
594                .find(|node| is_navigatable(self.tree, self.style, *node, lock_focus_to))
595                .unwrap_or(Entity::root())
596        };
597
598        if next_focused != *self.focused {
599            self.send_event(
600                Event::new(WindowEvent::FocusOut).target(*self.focused).origin(Entity::root()),
601            );
602            self.send_event(
603                Event::new(WindowEvent::FocusIn).target(next_focused).origin(Entity::root()),
604            );
605
606            if let Some(pseudo_classes) = self.style.pseudo_classes.get_mut(*self.triggered) {
607                pseudo_classes.set(PseudoClassFlags::ACTIVE, false);
608            }
609            self.needs_restyle();
610            *self.triggered = Entity::null();
611        }
612    }
613
614    /// Moves the keyboard focus to the previous navigable view.
615    pub fn focus_prev(&mut self) {
616        let lock_focus_to = self.tree.lock_focus_within(*self.focused);
617        let prev_focused = if let Some(prev_focused) =
618            focus_backward(self.tree, self.style, *self.focused, lock_focus_to)
619        {
620            prev_focused
621        } else {
622            TreeIterator::full(self.tree)
623                .rfind(|node| is_navigatable(self.tree, self.style, *node, lock_focus_to))
624                .unwrap_or(Entity::root())
625        };
626
627        if prev_focused != *self.focused {
628            self.send_event(
629                Event::new(WindowEvent::FocusOut).target(*self.focused).origin(Entity::root()),
630            );
631            self.send_event(
632                Event::new(WindowEvent::FocusIn).target(prev_focused).origin(Entity::root()),
633            );
634
635            if let Some(pseudo_classes) = self.style.pseudo_classes.get_mut(*self.triggered) {
636                pseudo_classes.set(PseudoClassFlags::ACTIVE, false);
637            }
638            self.needs_restyle();
639            *self.triggered = Entity::null();
640        }
641    }
642
643    /// Returns the currently hovered view.
644    pub fn hovered(&self) -> Entity {
645        *self.hovered
646    }
647
648    /// Returns the currently focused view.
649    pub fn focused(&self) -> Entity {
650        *self.focused
651    }
652
653    // PseudoClass Getters
654
655    /// Returns true if the current view is being hovered.
656    pub fn is_hovered(&self) -> bool {
657        self.hovered() == self.current
658    }
659
660    /// Returns true if the current view is active.
661    pub fn is_active(&self) -> bool {
662        if let Some(pseudo_classes) = self.style.pseudo_classes.get(self.current) {
663            pseudo_classes.contains(PseudoClassFlags::ACTIVE)
664        } else {
665            false
666        }
667    }
668
669    /// Returns true if the mouse cursor is over the current view.
670    pub fn is_over(&self) -> bool {
671        if let Some(pseudo_classes) = self.style.pseudo_classes.get(self.current) {
672            pseudo_classes.contains(PseudoClassFlags::OVER)
673        } else {
674            false
675        }
676    }
677
678    /// Returns true if the current view is focused.
679    pub fn is_focused(&self) -> bool {
680        self.focused() == self.current
681    }
682
683    /// Returns true if the current view can be dragged in a drag and drop operation.
684    pub fn is_draggable(&self) -> bool {
685        self.style
686            .abilities
687            .get(self.current)
688            .map(|abilities| abilities.contains(Abilities::DRAGGABLE))
689            .unwrap_or_default()
690    }
691
692    /// Returns true if the current view is disabled.
693    pub fn is_disabled(&self) -> bool {
694        self.style.disabled.get(self.current()).cloned().unwrap_or_default()
695    }
696
697    /// Returns true if the current view is checked.
698    pub fn is_checked(&self) -> bool {
699        if let Some(pseudo_classes) = self.style.pseudo_classes.get(self.current) {
700            pseudo_classes.contains(PseudoClassFlags::CHECKED)
701        } else {
702            false
703        }
704    }
705
706    /// Returns true if the view is in a read-only state.
707    pub fn is_read_only(&self) -> bool {
708        if let Some(pseudo_classes) = self.style.pseudo_classes.get(self.current) {
709            pseudo_classes.contains(PseudoClassFlags::READ_ONLY)
710        } else {
711            false
712        }
713    }
714
715    //
716
717    /// Prevents the cursor icon from changing until the lock is released.
718    ///
719    /// The current view holds the lock until it calls [`unlock_cursor_icon`](Self::unlock_cursor_icon)
720    /// or is removed.
721    pub fn lock_cursor_icon(&mut self) {
722        *self.cursor_icon_locked_by = Some(self.current);
723    }
724
725    /// Releases the cursor icon lock held by the current view, allowing the cursor icon to be changed.
726    ///
727    /// Does nothing while a different view holds the lock.
728    pub fn unlock_cursor_icon(&mut self) {
729        if self.cursor_icon_locked_by.is_some_and(|holder| holder != self.current) {
730            return;
731        }
732        *self.cursor_icon_locked_by = None;
733        let hovered = *self.hovered;
734        let cursor = self.style.cursor.get(hovered).cloned().unwrap_or_default();
735        self.emit(WindowEvent::SetCursor(cursor));
736    }
737
738    /// Returns true if the cursor icon is locked.
739    pub fn is_cursor_icon_locked(&self) -> bool {
740        self.cursor_icon_locked_by.is_some()
741    }
742
743    /// Sets the drop data of the current view.
744    pub fn set_drop_data(&mut self, data: impl Into<DropData>) {
745        *self.drop_data = Some(data.into())
746    }
747
748    /// Get the contents of the system clipboard.
749    ///
750    /// This may fail for a variety of backend-specific reasons.
751    #[cfg(feature = "clipboard")]
752    pub fn get_clipboard(&mut self) -> Result<String, Box<dyn Error + Send + Sync + 'static>> {
753        self.current_window_clipboard().get_contents()
754    }
755
756    /// Set the contents of the system clipboard.
757    ///
758    /// This may fail for a variety of backend-specific reasons.
759    #[cfg(feature = "clipboard")]
760    pub fn set_clipboard(
761        &mut self,
762        text: String,
763    ) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
764        self.current_window_clipboard().set_contents(text)
765    }
766
767    #[cfg(feature = "clipboard")]
768    fn current_window_clipboard(&mut self) -> &mut Box<dyn ClipboardProvider> {
769        let window = if self.tree.is_window(self.current) {
770            self.current
771        } else {
772            self.tree.get_parent_window(self.current).unwrap_or(Entity::root())
773        };
774
775        self.clipboards.entry(window).or_insert_with(super::default_clipboard_provider)
776    }
777
778    /// Toggles the addition/removal of a class name for the current view.
779    ///
780    /// # Example
781    /// ```rust
782    /// # use vizia_core::prelude::*;
783    /// # let context = &mut Context::default();
784    /// # let mut cx = &mut EventContext::new(context);
785    /// cx.toggle_class("foo", true);
786    /// ```
787    pub fn toggle_class(&mut self, class_name: &str, applied: bool) {
788        let current = self.current();
789        self.style.set_class(self.tree, current, class_name, applied);
790    }
791
792    /// Returns a reference to the [Environment] model.
793    pub fn environment(&self) -> &Environment {
794        self.data::<Environment>()
795    }
796
797    /// Marks the current view as needing to be redrawn.
798    pub fn needs_redraw(&mut self) {
799        let parent_window = self.tree.get_parent_window(self.current).unwrap_or(Entity::root());
800        if let Some(window_state) = self.windows.get_mut(&parent_window) {
801            window_state.redraw_list.insert(self.current);
802        }
803    }
804
805    /// Marks the current view as needing a layout computation.
806    pub fn needs_relayout(&mut self) {
807        self.style.needs_relayout(self.current);
808        self.needs_redraw();
809    }
810
811    /// Marks the current view as needing to be restyled.
812    pub fn needs_restyle(&mut self) {
813        self.style.needs_restyle_with_dependents(self.tree, self.current);
814    }
815
816    pub fn needs_retransform(&mut self) {
817        self.style.needs_retransform(self.current);
818    }
819
820    pub fn needs_reclip(&mut self) {
821        self.style.needs_reclip(self.current);
822    }
823
824    /// Reloads the stylesheets linked to the application.
825    pub fn reload_styles(&mut self) -> Result<(), std::io::Error> {
826        if self.resource_manager.styles.is_empty() {
827            return Ok(());
828        }
829
830        self.style.remove_rules();
831
832        self.style.clear_style_rules();
833
834        let mut overall_theme = String::new();
835
836        for style_string in self.resource_manager.styles.iter().flat_map(|style| style.get_style())
837        {
838            overall_theme += &style_string;
839        }
840
841        self.style.parse_theme(&overall_theme);
842
843        self.style.needs_relayout(Entity::root());
844
845        for entity in self.tree.into_iter() {
846            self.style.needs_restyle(entity);
847
848            //self.style.needs_redraw(entity);
849            self.style.needs_text_update(entity);
850        }
851
852        Ok(())
853    }
854
855    /// Spawns a thread and provides a [ContextProxy] for sending events back to the main UI thread.
856    pub fn spawn<F>(&self, target: F)
857    where
858        F: 'static + Send + FnOnce(&mut ContextProxy),
859    {
860        let mut cxp = ContextProxy {
861            current: self.current,
862            event_proxy: self.event_proxy.as_ref().map(|p| p.make_clone()),
863        };
864
865        std::thread::spawn(move || target(&mut cxp));
866    }
867
868    /// Returns a [ContextProxy] which can be moved between threads and used to send events back to the main UI thread.
869    pub fn get_proxy(&self) -> ContextProxy {
870        ContextProxy {
871            current: self.current,
872            event_proxy: self.event_proxy.as_ref().map(|p| p.make_clone()),
873        }
874    }
875
876    /// Submits a configured [`TaskBuilder`] for asynchronous execution.
877    ///
878    /// Tasks run on Vizia's shared Tokio runtime and complete through the
879    /// `on_result(...)` callback attached to the builder, when one is provided.
880    ///
881    /// Returns a [`TaskHandle`] that can be used to request cancellation.
882    ///
883    /// # Example
884    /// ```rust,no_run
885    /// # use vizia_core::prelude::*;
886    /// # #[cfg(feature = "tokio")]
887    /// # fn trigger(cx: &EventContext) {
888    /// // Fire-and-forget:
889    /// cx.add_task(Task::new(|_| async move { Ok::<(), &'static str>(()) }));
890    ///
891    /// // With completion handling:
892    /// cx.add_task(
893    ///     Task::new(|_| async move { Ok::<_, &'static str>(()) })
894    ///         .name("refresh")
895    ///         .on_result(|_, _| {}),
896    /// );
897    /// # }
898    /// ```
899    #[cfg(feature = "tokio")]
900    pub fn add_task<T, E>(&self, task: TaskBuilder<T, E>) -> TaskHandle
901    where
902        T: Send + 'static,
903        E: Send + 'static,
904    {
905        task.add_to_event_context(self)
906    }
907
908    pub fn modify<V: View>(&mut self, f: impl FnOnce(&mut V)) {
909        if let Some(view) = self
910            .views
911            .get_mut(&self.current)
912            .and_then(|view_handler| view_handler.downcast_mut::<V>())
913        {
914            (f)(view);
915        }
916    }
917
918    // TODO: Abstract this to shared trait for all contexts
919
920    // Getters
921
922    /// Returns the background color of the view.
923    ///
924    /// Returns a transparent color if the view does not have a background color.
925    pub fn background_color(&mut self) -> Color {
926        self.style.background_color.get(self.current).copied().unwrap_or_default()
927    }
928
929    // Setters
930
931    pub fn set_id(&mut self, id: &str) {
932        self.style.set_id(self.tree, self.current, id.to_string())
933    }
934
935    // Pseudoclass Setters
936
937    /// Sets the hover state of the current view.
938    ///
939    /// Hovered elements can be selected with the `:hover` CSS pseudo-class selector:
940    /// ```css
941    /// element:hover {
942    ///     background-color: red;
943    /// }
944    /// ```
945    /// Typically this is set by the hover system and should not be set manually.
946    pub fn set_hover(&mut self, flag: bool) {
947        self.set_pseudo_class(self.current, PseudoClassFlags::HOVER, flag);
948    }
949
950    /// Set the active state for the current view.
951    ///
952    /// Active elements can be selected with the `:active` CSS pseudo-class selector:
953    /// ```css
954    /// element:active {
955    ///     background-color: red;
956    /// }
957    /// ```
958    pub fn set_active(&mut self, active: bool) {
959        self.set_pseudo_class(self.current, PseudoClassFlags::ACTIVE, active);
960    }
961
962    pub fn set_read_only(&mut self, flag: bool) {
963        self.set_pseudo_class(self.current, PseudoClassFlags::READ_ONLY, flag);
964    }
965
966    pub fn set_read_write(&mut self, flag: bool) {
967        self.set_pseudo_class(self.current, PseudoClassFlags::READ_WRITE, flag);
968    }
969
970    /// Sets the checked state of the current view.
971    ///
972    /// Checked elements can be selected with the `:checked` CSS pseudo-class selector:
973    /// ```css
974    /// element:checked {
975    ///     background-color: red;
976    /// }
977    /// ```
978    pub fn set_checked(&mut self, flag: bool) {
979        self.set_pseudo_class(self.current, PseudoClassFlags::CHECKED, flag);
980    }
981
982    /// Sets the valid state of the current view.
983    ///
984    /// Checked elements can be selected with the `:checked` CSS pseudo-class selector:
985    /// ```css
986    /// element:checked {
987    ///     background-color: red;
988    /// }
989    /// ```
990    pub fn set_valid(&mut self, flag: bool) {
991        let current = self.current();
992        self.set_pseudo_class(current, PseudoClassFlags::VALID, flag);
993        self.set_pseudo_class(current, PseudoClassFlags::INVALID, !flag);
994    }
995
996    pub fn set_placeholder_shown(&mut self, flag: bool) {
997        self.set_pseudo_class(self.current, PseudoClassFlags::PLACEHOLDER_SHOWN, flag);
998    }
999
1000    /// Returns whether the entity is still alive, that is, it has been created and not removed.
1001    ///
1002    /// This is independent of [`is_valid`](Self::is_valid), which reports form validation.
1003    pub fn is_entity_alive(&self, entity: Entity) -> bool {
1004        self.entity_manager.is_alive(entity)
1005    }
1006
1007    // TODO: Move me
1008    pub fn is_valid(&self) -> bool {
1009        self.style
1010            .pseudo_classes
1011            .get(self.current)
1012            .map(|pseudo_classes| pseudo_classes.contains(PseudoClassFlags::VALID))
1013            .unwrap_or_default()
1014    }
1015
1016    pub fn is_placeholder_shown(&self) -> bool {
1017        self.style
1018            .pseudo_classes
1019            .get(self.current)
1020            .map(|pseudo_classes| pseudo_classes.contains(PseudoClassFlags::PLACEHOLDER_SHOWN))
1021            .unwrap_or_default()
1022    }
1023
1024    // Accessibility Properties
1025
1026    /// Sets the accessibility name of the view.
1027    pub fn set_name(&mut self, name: &str) {
1028        self.style.name.insert(self.current, name.to_string());
1029    }
1030
1031    /// Sets the accessibility role of the view.
1032    pub fn set_role(&mut self, role: Role) {
1033        self.style.role.insert(self.current, role);
1034    }
1035
1036    // /// Sets the accessibility default action verb of the view.
1037    // pub fn set_default_action_verb(&mut self, default_action_verb: DefaultActionVerb) {
1038    //     self.style.default_action_verb.insert(self.current, default_action_verb);
1039    // }
1040
1041    /// Sets the view to be an accessibility live region.
1042    pub fn set_live(&mut self, live: Live) {
1043        self.style.live.insert(self.current, live);
1044    }
1045
1046    /// Sets the view, by id name, which labels the current view for accessibility.  
1047    pub fn labelled_by(&mut self, id: &str) {
1048        self.style.labelled_by.insert(self.current, id.to_string());
1049    }
1050
1051    /// Sets the view, by id name, which describes the current view for accessibility.
1052    pub fn described_by(&mut self, id: &str) {
1053        self.style.described_by.insert(self.current, id.to_string());
1054    }
1055
1056    /// Sets the view, by id name, which is controlled by the current view for accessibility.
1057    pub fn controls(&mut self, id: &str) {
1058        self.style.controls.insert(self.current, id.to_string());
1059    }
1060
1061    /// Sets whether the view should be explicitely hidden from accessibility.
1062    pub fn set_hidden(&mut self, hidden: bool) {
1063        self.style.hidden.insert(self.current, hidden)
1064    }
1065
1066    /// Sets a text value used for accessbility for the current view.
1067    pub fn text_value(&mut self, text: &str) {
1068        self.style.text_value.insert(self.current, text.to_string());
1069    }
1070
1071    /// Sets a numeric value used for accessibility for the current view.
1072    pub fn numeric_value(&mut self, value: f64) {
1073        self.style.numeric_value.insert(self.current, value);
1074    }
1075
1076    // DISPLAY
1077
1078    /// Sets the display type of the current view.
1079    ///
1080    /// A display value of `Display::None` causes the view to be ignored by both layout and rendering.
1081    pub fn set_display(&mut self, display: Display) {
1082        self.style.display.insert(self.current, display);
1083    }
1084
1085    /// Sets the visibility of the current view.
1086    ///
1087    /// The layout system will still compute the size and position of an invisible (hidden) view.
1088    pub fn set_visibility(&mut self, visibility: Visibility) {
1089        self.style.visibility.insert(self.current, visibility);
1090    }
1091
1092    /// Sets the opacity of the current view.
1093    ///
1094    /// Expects a number between 0.0 (transparent) and 1.0 (opaque).
1095    pub fn set_opacity(&mut self, opacity: f32) {
1096        self.style.opacity.insert(self.current, Opacity(opacity));
1097    }
1098
1099    /// Sets the z-index of the current view.
1100    pub fn set_z_index(&mut self, z_index: i32) {
1101        self.style.z_index.insert(self.current, z_index);
1102    }
1103
1104    /// Sets the clip path of the current view.
1105    pub fn set_clip_path(&mut self, clip_path: ClipPath) {
1106        self.style.clip_path.insert(self.current, clip_path);
1107        self.needs_reclip();
1108        self.needs_redraw();
1109    }
1110
1111    /// Sets the overflow type on the horizontal axis of the current view.
1112    pub fn set_overflowx(&mut self, overflowx: impl Into<Overflow>) {
1113        self.style.overflowx.insert(self.current, overflowx.into());
1114        self.needs_reclip();
1115        self.needs_redraw();
1116    }
1117
1118    /// Sets the overflow type on the vertical axis of the current view.
1119    pub fn set_overflowy(&mut self, overflowy: impl Into<Overflow>) {
1120        self.style.overflowy.insert(self.current, overflowy.into());
1121        self.needs_reclip();
1122        self.needs_redraw();
1123    }
1124
1125    // TRANSFORM
1126
1127    /// Sets the transform of the current view.
1128    pub fn set_transform(&mut self, transform: impl Into<Vec<Transform>>) {
1129        self.style.transform.insert(self.current, transform.into());
1130        self.needs_retransform();
1131        self.needs_redraw();
1132    }
1133
1134    /// Sets the transform origin of the current view.
1135    pub fn set_transform_origin(&mut self, transform_origin: Translate) {
1136        self.style.transform_origin.insert(self.current, transform_origin);
1137        self.needs_retransform();
1138        self.needs_redraw();
1139    }
1140
1141    /// Sets the translation of the current view.
1142    pub fn set_translate(&mut self, translate: impl Into<Translate>) {
1143        self.style.translate.insert(self.current, translate.into());
1144        self.needs_retransform();
1145        self.needs_redraw();
1146    }
1147
1148    /// Sets the rotation of the current view.
1149    pub fn set_rotate(&mut self, angle: impl Into<Angle>) {
1150        self.style.rotate.insert(self.current, angle.into());
1151        self.needs_retransform();
1152        self.needs_redraw();
1153    }
1154
1155    /// Sets the scale of the current view.
1156    pub fn set_scale(&mut self, scale: impl Into<Scale>) {
1157        self.style.scale.insert(self.current, scale.into());
1158        self.needs_retransform();
1159        self.needs_redraw();
1160    }
1161
1162    // FILTER
1163
1164    /// Sets the filter of the current view.
1165    pub fn set_filter(&mut self, filter: Filter) {
1166        self.style.filter.insert(self.current, filter);
1167        self.style.filter_entities.insert(self.current);
1168        self.needs_redraw();
1169    }
1170
1171    /// Sets the backdrop filter of the current view.
1172    pub fn set_backdrop_filter(&mut self, filter: Filter) {
1173        self.style.backdrop_filter.insert(self.current, filter);
1174        self.style.filter_entities.insert(self.current);
1175        self.needs_redraw();
1176    }
1177
1178    // BOX SHADOW
1179
1180    // TODO
1181
1182    // BACKGROUND
1183
1184    pub fn set_background_color(&mut self, background_color: Color) {
1185        self.style.background_color.insert(self.current, background_color);
1186        self.needs_redraw();
1187    }
1188
1189    // SIZE
1190
1191    pub fn set_width(&mut self, width: Units) {
1192        self.style.width.insert(self.current, width);
1193        self.needs_relayout();
1194        self.needs_redraw();
1195    }
1196
1197    pub fn set_height(&mut self, height: Units) {
1198        self.style.height.insert(self.current, height);
1199        self.needs_relayout();
1200        self.needs_redraw();
1201    }
1202
1203    pub fn set_max_height(&mut self, height: Units) {
1204        self.style.max_height.insert(self.current, height);
1205        self.needs_relayout();
1206        self.needs_redraw();
1207    }
1208
1209    // SPACE
1210
1211    pub fn set_left(&mut self, left: Units) {
1212        self.style.left.insert(self.current, left);
1213        self.needs_relayout();
1214        self.needs_redraw();
1215    }
1216
1217    pub fn set_top(&mut self, top: Units) {
1218        self.style.top.insert(self.current, top);
1219        self.needs_relayout();
1220        self.needs_redraw();
1221    }
1222
1223    pub fn set_right(&mut self, right: Units) {
1224        self.style.right.insert(self.current, right);
1225        self.needs_relayout();
1226        self.needs_redraw();
1227    }
1228
1229    pub fn set_bottom(&mut self, bottom: Units) {
1230        self.style.bottom.insert(self.current, bottom);
1231        self.needs_relayout();
1232        self.needs_redraw();
1233    }
1234
1235    // PADDING
1236
1237    pub fn set_padding_left(&mut self, padding_left: Units) {
1238        self.style.padding_left.insert(self.current, padding_left);
1239        self.needs_relayout();
1240        self.needs_redraw();
1241    }
1242
1243    pub fn set_padding_top(&mut self, padding_top: Units) {
1244        self.style.padding_top.insert(self.current, padding_top);
1245        self.needs_relayout();
1246        self.needs_redraw();
1247    }
1248
1249    pub fn set_padding_right(&mut self, padding_right: Units) {
1250        self.style.padding_right.insert(self.current, padding_right);
1251        self.needs_relayout();
1252        self.needs_redraw();
1253    }
1254
1255    pub fn set_padding_bottom(&mut self, padding_bottom: Units) {
1256        self.style.padding_bottom.insert(self.current, padding_bottom);
1257        self.needs_relayout();
1258        self.needs_redraw();
1259    }
1260
1261    // TEXT
1262
1263    /// Sets the text of the current view.
1264    pub fn set_text(&mut self, text: &str) {
1265        self.style.set_text(self.tree, self.current, text.to_owned());
1266        self.style.needs_text_update(self.current);
1267        self.needs_relayout();
1268        self.needs_redraw();
1269    }
1270
1271    pub fn set_pointer_events(&mut self, pointer_events: impl Into<PointerEvents>) {
1272        self.style.pointer_events.insert(self.current, pointer_events.into());
1273    }
1274
1275    // GETTERS
1276
1277    /// Returns the top border width of the current view in physical pixels.
1278    pub fn border_top_width(&self) -> f32 {
1279        if let Some(length) = self.style.border_top_width.get(self.current) {
1280            let bounds = self.bounds();
1281            return length.to_pixels(bounds.w.min(bounds.h), self.scale_factor()).round();
1282        }
1283        0.0
1284    }
1285
1286    /// Returns the right border width of the current view in physical pixels.
1287    pub fn border_right_width(&self) -> f32 {
1288        if let Some(length) = self.style.border_right_width.get(self.current) {
1289            let bounds = self.bounds();
1290            return length.to_pixels(bounds.w.min(bounds.h), self.scale_factor()).round();
1291        }
1292        0.0
1293    }
1294
1295    /// Returns the bottom border width of the current view in physical pixels.
1296    pub fn border_bottom_width(&self) -> f32 {
1297        if let Some(length) = self.style.border_bottom_width.get(self.current) {
1298            let bounds = self.bounds();
1299            return length.to_pixels(bounds.w.min(bounds.h), self.scale_factor()).round();
1300        }
1301        0.0
1302    }
1303
1304    /// Returns the left border width of the current view in physical pixels.
1305    pub fn border_left_width(&self) -> f32 {
1306        if let Some(length) = self.style.border_left_width.get(self.current) {
1307            let bounds = self.bounds();
1308            return length.to_pixels(bounds.w.min(bounds.h), self.scale_factor()).round();
1309        }
1310        0.0
1311    }
1312
1313    /// Returns the top border width of the current view in physical pixels.
1314    /// Equivalent to `border_top_width`; kept for backward compatibility.
1315    pub fn border_width(&self) -> f32 {
1316        self.border_top_width()
1317    }
1318
1319    /// Returns the font-size of the current view in physical pixels.
1320    pub fn font_size(&self) -> f32 {
1321        self.logical_to_physical(
1322            self.style
1323                .font_size
1324                .get(self.current)
1325                .cloned()
1326                .map(|f| f.0.to_px().unwrap())
1327                .unwrap_or(16.0),
1328        )
1329    }
1330
1331    /// Adds a timer to the application.
1332    ///
1333    /// `interval` - The time between ticks of the timer.
1334    /// `duration` - An optional duration for the timer. Pass `None` for a continuos timer.
1335    /// `callback` - A callback which is called on when the timer is started, ticks, and stops. Disambiguated by the `TimerAction` parameter of the callback.
1336    ///
1337    /// Returns a `Timer` id which can be used to start and stop the timer.  
1338    ///
1339    /// # Example
1340    /// Creates a timer which calls the provided callback every second for 5 seconds:
1341    /// ```rust
1342    /// # use vizia_core::prelude::*;
1343    /// # use instant::{Instant, Duration};
1344    /// # let cx = &mut Context::default();
1345    /// let timer = cx.add_timer(Duration::from_secs(1), Some(Duration::from_secs(5)), |cx, reason|{
1346    ///     match reason {
1347    ///         TimerAction::Start => {
1348    ///             debug!("Start timer");
1349    ///         }
1350    ///     
1351    ///         TimerAction::Tick(delta) => {
1352    ///             debug!("Tick timer: {:?}", delta);
1353    ///         }
1354    ///
1355    ///         TimerAction::Stop => {
1356    ///             debug!("Stop timer");
1357    ///         }
1358    ///     }
1359    /// });
1360    /// ```
1361    pub fn add_timer(
1362        &mut self,
1363        interval: Duration,
1364        duration: Option<Duration>,
1365        callback: impl Fn(&mut EventContext, TimerAction) + 'static,
1366    ) -> Timer {
1367        let id = Timer(self.timers.len());
1368        self.timers.push(TimerState {
1369            entity: Entity::root(),
1370            id,
1371            time: Instant::now(),
1372            interval,
1373            duration,
1374            start_time: Instant::now(),
1375            callback: Rc::new(callback),
1376            ticking: false,
1377            stopping: false,
1378        });
1379
1380        id
1381    }
1382
1383    /// Starts a timer with the provided timer id.
1384    ///
1385    /// Events sent within the timer callback provided in `add_timer()` will target the current view.
1386    pub fn start_timer(&mut self, timer: Timer) {
1387        let current = self.current;
1388        if !self.timer_is_running(timer) {
1389            let timer_state = self.timers[timer.0].clone();
1390            // Copy timer state from pending to playing
1391            self.running_timers.push(timer_state);
1392        }
1393
1394        self.modify_timer(timer, |timer_state| {
1395            let now = Instant::now();
1396            timer_state.start_time = now;
1397            timer_state.time = now;
1398            timer_state.entity = current;
1399            timer_state.ticking = false;
1400            timer_state.stopping = false;
1401        });
1402    }
1403
1404    /// Modifies the state of an existing timer with the provided `Timer` id.
1405    pub fn modify_timer(&mut self, timer: Timer, timer_function: impl Fn(&mut TimerState)) {
1406        let mut running_timers = self.running_timers.clone().into_vec();
1407
1408        if let Some(timer_state) =
1409            running_timers.iter_mut().find(|timer_state| timer_state.id == timer)
1410        {
1411            (timer_function)(timer_state);
1412            *self.running_timers = running_timers.into();
1413            return;
1414        }
1415
1416        for pending_timer in self.timers.iter_mut() {
1417            if pending_timer.id == timer {
1418                (timer_function)(pending_timer);
1419            }
1420        }
1421    }
1422
1423    pub fn query_timer<T>(
1424        &mut self,
1425        timer: Timer,
1426        timer_function: impl Fn(&TimerState) -> T,
1427    ) -> Option<T> {
1428        if let Some(timer_state) =
1429            self.running_timers.iter().find(|timer_state| timer_state.id == timer)
1430        {
1431            return Some(timer_function(timer_state));
1432        }
1433
1434        for pending_timer in self.timers.iter() {
1435            if pending_timer.id == timer {
1436                return Some(timer_function(pending_timer));
1437            }
1438        }
1439
1440        None
1441    }
1442
1443    /// Returns true if the timer with the provided timer id is currently running.
1444    pub fn timer_is_running(&mut self, timer: Timer) -> bool {
1445        for timer_state in self.running_timers.iter() {
1446            if timer_state.id == timer {
1447                return true;
1448            }
1449        }
1450
1451        false
1452    }
1453
1454    /// Stops the timer with the given timer id.
1455    ///
1456    /// Any events emitted in response to the timer stopping, as determined by the callback provided in `add_timer()`, will target the view which called `start_timer()`.
1457    pub fn stop_timer(&mut self, timer: Timer) {
1458        let mut running_timers = self.running_timers.clone();
1459
1460        for timer_state in running_timers.iter() {
1461            if timer_state.id == timer {
1462                self.with_current(timer_state.entity, |cx| {
1463                    (timer_state.callback)(cx, TimerAction::Stop);
1464                });
1465            }
1466        }
1467
1468        *self.running_timers =
1469            running_timers.drain().filter(|timer_state| timer_state.id != timer).collect();
1470    }
1471}
1472
1473impl DataContext for EventContext<'_> {
1474    fn try_data<T: 'static>(&self) -> Option<&T> {
1475        // Return data for the static model.
1476        if let Some(t) = <dyn Any>::downcast_ref::<T>(&()) {
1477            return Some(t);
1478        }
1479
1480        for entity in self.current.parent_iter(self.tree) {
1481            // Return model data.
1482            if let Some(models) = self.models.get(&entity)
1483                && let Some(model) = models.get(&TypeId::of::<T>())
1484            {
1485                return model.downcast_ref::<T>();
1486            }
1487
1488            // Return view data.
1489            if let Some(view_handler) = self.views.get(&entity)
1490                && let Some(data) = view_handler.downcast_ref::<T>()
1491            {
1492                return Some(data);
1493            }
1494        }
1495
1496        None
1497    }
1498
1499    fn localization_context(&self) -> Option<LocalizationContext<'_>> {
1500        Some(LocalizationContext::from_event_context(self))
1501    }
1502}
1503
1504impl EmitContext for EventContext<'_> {
1505    fn emit<M: Any>(&mut self, message: M) {
1506        self.send_event(
1507            Event::new(message)
1508                .target(self.current)
1509                .origin(self.current)
1510                .propagate(Propagation::Up),
1511        );
1512    }
1513
1514    fn emit_to<M: Any>(&mut self, target: Entity, message: M) {
1515        self.send_event(
1516            Event::new(message).target(target).origin(self.current).propagate(Propagation::Direct),
1517        );
1518    }
1519
1520    fn emit_custom(&mut self, event: Event) {
1521        self.send_event(event);
1522    }
1523
1524    fn schedule_emit<M: Any>(&mut self, message: M, at: Instant) -> TimedEventHandle {
1525        self.schedule_emit_custom(
1526            Event::new(message)
1527                .target(self.current)
1528                .origin(self.current)
1529                .propagate(Propagation::Up),
1530            at,
1531        )
1532    }
1533    fn schedule_emit_to<M: Any>(
1534        &mut self,
1535        target: Entity,
1536        message: M,
1537        at: Instant,
1538    ) -> TimedEventHandle {
1539        self.schedule_emit_custom(
1540            Event::new(message).target(target).origin(self.current).propagate(Propagation::Direct),
1541            at,
1542        )
1543    }
1544    fn schedule_emit_custom(&mut self, event: Event, at: Instant) -> TimedEventHandle {
1545        let handle = TimedEventHandle(*self.next_event_id);
1546        self.event_schedule.push(TimedEvent {
1547            event: event.inherit_ui_modifiers(*self.modifiers),
1548            time: at,
1549            ident: handle,
1550        });
1551        *self.next_event_id += 1;
1552        handle
1553    }
1554    fn cancel_scheduled(&mut self, handle: TimedEventHandle) {
1555        *self.event_schedule =
1556            self.event_schedule.drain().filter(|item| item.ident != handle).collect();
1557    }
1558}
1559
1560/// Trait for querying properties of the tree from a context.
1561pub trait TreeProps {
1562    /// Returns the entity id of the parent of the current view.
1563    fn parent(&self) -> Entity;
1564    /// Returns the entity id of the first_child of the current view.
1565    fn first_child(&self) -> Entity;
1566    /// Returns the entity id of the parent window of the current view.
1567    fn parent_window(&self) -> Entity;
1568}
1569
1570impl TreeProps for EventContext<'_> {
1571    fn parent(&self) -> Entity {
1572        self.tree.get_layout_parent(self.current).unwrap()
1573    }
1574
1575    fn first_child(&self) -> Entity {
1576        self.tree.get_layout_first_child(self.current).unwrap()
1577    }
1578
1579    fn parent_window(&self) -> Entity {
1580        self.tree.get_parent_window(self.current).unwrap_or(Entity::root())
1581    }
1582}
1583
1584#[cfg(test)]
1585mod tests {
1586    use super::*;
1587
1588    #[test]
1589    fn entity_alive_follows_removal_and_ignores_form_validity() {
1590        let mut cx = Context::new();
1591        let removed = Element::new(&mut cx).entity();
1592        let invalid = Element::new(&mut cx).entity();
1593        EventContext::new_with_current(&mut cx, invalid).set_valid(false);
1594        cx.remove(removed);
1595
1596        let cx = EventContext::new_with_current(&mut cx, invalid);
1597        assert!(!cx.is_valid());
1598        assert!(cx.is_entity_alive(invalid));
1599        assert!(cx.is_entity_alive(Entity::root()));
1600        assert!(!cx.is_entity_alive(removed));
1601    }
1602}