Skip to main content

vizia_core/context/
mod.rs

1//! Context types for retained state, used during view building, event handling, and drawing.
2
3mod access;
4#[doc(hidden)]
5pub mod backend;
6mod draw;
7mod event;
8mod proxy;
9mod resource;
10#[cfg(feature = "tokio")]
11mod task;
12
13use log::debug;
14use skia_safe::{
15    FontMgr, svg,
16    textlayout::{FontCollection, TypefaceFontProvider},
17};
18use std::cell::RefCell;
19use std::collections::{BinaryHeap, VecDeque};
20use std::rc::Rc;
21use std::sync::Mutex;
22use std::sync::atomic::{AtomicU64, Ordering};
23use std::{
24    any::{Any, TypeId},
25    sync::Arc,
26};
27use vizia_id::IdManager;
28use vizia_window::WindowDescription;
29
30#[cfg(all(
31    feature = "clipboard",
32    not(all(
33        any(
34            target_os = "linux",
35            target_os = "dragonfly",
36            target_os = "freebsd",
37            target_os = "netbsd",
38            target_os = "openbsd"
39        ),
40        feature = "wayland",
41    ))
42))]
43use copypasta::ClipboardContext;
44#[cfg(feature = "clipboard")]
45use copypasta::{ClipboardProvider, nop_clipboard::NopClipboardContext};
46use hashbrown::{HashMap, HashSet, hash_map::Entry};
47
48pub use access::*;
49pub use draw::*;
50pub use event::*;
51pub use proxy::*;
52pub use resource::*;
53#[cfg(feature = "tokio")]
54pub use task::*;
55
56use crate::{
57    events::{TimedEvent, TimedEventHandle, TimerState, ViewHandler},
58    model::ModelData,
59};
60
61use crate::environment::{apply_direction_class, apply_theme_class};
62use crate::{binding::BindingHandler, resource::StoredImage};
63use crate::{cache::CachedData, resource::ImageOrSvg};
64
65use crate::prelude::*;
66use crate::resource::ResourceManager;
67use crate::text::TextContext;
68use vizia_input::{ImeState, MouseState};
69use vizia_storage::{ChildIterator, LayoutParentIterator};
70
71#[cfg(feature = "tokio")]
72pub(crate) type TaskRuntime = Arc<tokio::runtime::Runtime>;
73
74static DEFAULT_LAYOUT: &str = include_str!("../../resources/themes/default_layout.css");
75static DEFAULT_THEME: &str = include_str!("../../resources/themes/default_theme.css");
76static MARKDOWN: &str = include_str!("../../resources/themes/markdown.css");
77static DEFAULT_TRANSLATION_EN_US: &str =
78    include_str!("../../resources/translations/en-US/core.ftl");
79
80type Views = HashMap<Entity, Box<dyn ViewHandler>>;
81type Models = HashMap<Entity, HashMap<TypeId, Box<dyn ModelData>>>;
82type Bindings = HashMap<Entity, Box<dyn BindingHandler>>;
83
84static NEXT_CONTEXT_ID: AtomicU64 = AtomicU64::new(1);
85
86#[derive(Clone, Copy, PartialEq, Eq, Hash)]
87pub(crate) struct SignalRebuild {
88    pub(crate) context_id: u64,
89    pub(crate) entity: Entity,
90}
91
92#[cfg(feature = "clipboard")]
93fn default_clipboard_provider() -> Box<dyn ClipboardProvider> {
94    #[cfg(all(
95        any(
96            target_os = "linux",
97            target_os = "dragonfly",
98            target_os = "freebsd",
99            target_os = "netbsd",
100            target_os = "openbsd"
101        ),
102        feature = "wayland"
103    ))]
104    {
105        Box::new(NopClipboardContext::new().unwrap())
106    }
107
108    #[cfg(not(all(
109        any(
110            target_os = "linux",
111            target_os = "dragonfly",
112            target_os = "freebsd",
113            target_os = "netbsd",
114            target_os = "openbsd"
115        ),
116        feature = "wayland",
117    )))]
118    {
119        if let Ok(context) = ClipboardContext::new() {
120            Box::new(context)
121        } else {
122            Box::new(NopClipboardContext::new().unwrap())
123        }
124    }
125}
126
127thread_local! {
128    /// Entities for `Binding` views that need to be rebuilt because a reactive signal changed.
129    /// Signal effects push to this set; the binding system drains matching context entries each frame.
130    pub(crate) static SIGNAL_REBUILDS: RefCell<HashSet<SignalRebuild>> = RefCell::new(HashSet::new());
131}
132
133#[derive(Default, Clone)]
134pub struct WindowState {
135    pub window_description: WindowDescription,
136    pub scale_factor: f32,
137    pub needs_relayout: bool,
138    pub needs_redraw: bool,
139    pub redraw_list: HashSet<Entity>,
140    pub dirty_rect: Option<BoundingBox>,
141    pub owner: Option<Entity>,
142    pub is_modal: bool,
143    pub should_close: bool,
144    pub content: Option<Arc<dyn Fn(&mut Context)>>,
145}
146
147/// The main storage and control object for a Vizia application.
148pub struct Context {
149    pub(crate) context_id: u64,
150    pub(crate) entity_manager: IdManager<Entity>,
151    pub(crate) entity_identifiers: HashMap<String, Entity>,
152    pub tree: Tree<Entity>,
153    pub(crate) current: Entity,
154    pub(crate) views: Views,
155    pub(crate) models: Models,
156    pub(crate) bindings: Bindings,
157    event_queue: VecDeque<Event>,
158    pub(crate) event_schedule: BinaryHeap<TimedEvent>,
159    pub(crate) next_event_id: usize,
160    pub(crate) timers: Vec<TimerState>,
161    pub(crate) running_timers: BinaryHeap<TimerState>,
162    pub tree_updates: Vec<Option<accesskit::TreeUpdate>>,
163    pub(crate) listeners:
164        HashMap<Entity, Box<dyn Fn(&mut dyn ViewHandler, &mut EventContext, &mut Event)>>,
165    pub(crate) global_listeners: Vec<Box<dyn Fn(&mut EventContext, &mut Event)>>,
166    pub(crate) style: Style,
167    pub(crate) cache: CachedData,
168    pub windows: HashMap<Entity, WindowState>,
169
170    pub mouse: MouseState<Entity>,
171    pub(crate) modifiers: Modifiers,
172
173    pub(crate) captured: Entity,
174    pub(crate) triggered: Entity,
175    pub(crate) hovered: Entity,
176    /// The entities whose hover state was set by the hover system, per window.
177    pub(crate) hover_tracking: HashMap<Entity, crate::systems::hover::HoverTracking>,
178    pub(crate) drag_hovered: Entity,
179    pub(crate) focused: Entity,
180    pub(crate) focus_stack: Vec<Entity>,
181    pub(crate) cursor_icon_locked_by: Option<Entity>,
182
183    pub(crate) resource_manager: ResourceManager,
184
185    pub text_context: TextContext,
186
187    #[cfg(feature = "tokio")]
188    pub(crate) task_runtime: TaskRuntime,
189    #[cfg(feature = "tokio")]
190    pub(crate) named_tasks: NamedTaskMap,
191
192    pub(crate) event_proxy: Option<Box<dyn EventProxy>>,
193
194    #[cfg(feature = "clipboard")]
195    pub(crate) clipboards: HashMap<Entity, Box<dyn ClipboardProvider>>,
196
197    pub(crate) click_time: Instant,
198    pub(crate) clicks: usize,
199    pub(crate) click_pos: (f32, f32),
200    pub(crate) click_button: MouseButton,
201
202    pub ignore_default_theme: bool,
203    built_in_translations_added: bool,
204    built_in_styles_added: bool,
205    pub window_has_focus: bool,
206    pub ime_state: ImeState,
207
208    pub(crate) drop_data: Option<DropData>,
209    pub(crate) active_drag_view: Option<Entity>,
210}
211
212impl Default for Context {
213    fn default() -> Self {
214        Context::new()
215    }
216}
217
218impl Context {
219    /// Queue a same-thread emission with its current UI modifier context.
220    pub(crate) fn send_event(&mut self, event: Event) {
221        self.event_queue.push_back(event.inherit_ui_modifiers(self.modifiers));
222    }
223
224    /// Drain queued events for dispatch without exposing an enqueue path outside this module.
225    pub(crate) fn drain_events(&mut self) -> impl Iterator<Item = Event> + '_ {
226        self.event_queue.drain(..)
227    }
228
229    pub(crate) fn has_queued_events(&self) -> bool {
230        !self.event_queue.is_empty()
231    }
232
233    /// Creates a new context.
234    pub fn new() -> Self {
235        let mut cache = CachedData::default();
236        cache.add(Entity::root());
237
238        let mut result = Self {
239            context_id: NEXT_CONTEXT_ID.fetch_add(1, Ordering::Relaxed),
240            entity_manager: IdManager::new(),
241            entity_identifiers: HashMap::new(),
242            tree: Tree::new(),
243            current: Entity::root(),
244            views: HashMap::default(),
245            models: HashMap::default(),
246            bindings: HashMap::default(),
247            style: Style::default(),
248            cache,
249            windows: HashMap::new(),
250            event_queue: VecDeque::new(),
251            event_schedule: BinaryHeap::new(),
252            next_event_id: 0,
253            timers: Vec::new(),
254            running_timers: BinaryHeap::new(),
255            tree_updates: Vec::new(),
256            listeners: HashMap::default(),
257            global_listeners: Vec::new(),
258            mouse: MouseState::default(),
259            modifiers: Modifiers::empty(),
260            captured: Entity::null(),
261            triggered: Entity::null(),
262            hovered: Entity::root(),
263            hover_tracking: HashMap::new(),
264            drag_hovered: Entity::null(),
265            focused: Entity::root(),
266            focus_stack: Vec::new(),
267            cursor_icon_locked_by: None,
268            resource_manager: ResourceManager::new(),
269            text_context: {
270                let mut font_collection = FontCollection::new();
271
272                let default_font_manager = FontMgr::default();
273
274                let asset_provider = TypefaceFontProvider::new();
275
276                font_collection.set_default_font_manager(default_font_manager.clone(), None);
277                let asset_font_manager: FontMgr = asset_provider.clone().into();
278                font_collection.set_asset_font_manager(asset_font_manager);
279
280                TextContext {
281                    font_collection,
282                    default_font_manager,
283                    asset_provider,
284                    text_bounds: Default::default(),
285                    text_paragraphs: Default::default(),
286                }
287            },
288            #[cfg(feature = "tokio")]
289            task_runtime: Self::new_task_runtime(),
290            #[cfg(feature = "tokio")]
291            named_tasks: new_named_task_map(),
292
293            event_proxy: None,
294
295            #[cfg(feature = "clipboard")]
296            clipboards: HashMap::new(),
297            click_time: Instant::now(),
298            clicks: 0,
299            click_pos: (0.0, 0.0),
300            click_button: MouseButton::Left,
301
302            ignore_default_theme: false,
303            built_in_translations_added: false,
304            built_in_styles_added: false,
305            window_has_focus: true,
306
307            ime_state: Default::default(),
308
309            drop_data: None,
310            active_drag_view: None,
311        };
312
313        result.style.needs_restyle(Entity::root());
314        result.style.needs_relayout(Entity::root());
315        result.style.needs_retransform(Entity::root());
316        result.style.needs_reclip(Entity::root());
317        result.needs_redraw(Entity::root());
318
319        // Set the default DPI factor to 1.0.
320        result.style.dpi_factor = 1.0;
321
322        // Build the environment model at the root.
323        Environment::new(&mut result).build(&mut result);
324
325        result.entity_manager.create();
326
327        result
328    }
329
330    #[cfg(feature = "tokio")]
331    fn new_task_runtime() -> TaskRuntime {
332        Arc::new(
333            tokio::runtime::Builder::new_multi_thread()
334                .enable_all()
335                .build()
336                .expect("failed to build context task runtime"),
337        )
338    }
339
340    /// The "current" entity, generally the entity which is currently being built or the entity
341    /// which is currently having an event dispatched to it.
342    pub fn current(&self) -> Entity {
343        self.current
344    }
345
346    /// Makes the above black magic more explicit
347    pub fn with_current<T>(&mut self, current: Entity, f: impl FnOnce(&mut Context) -> T) -> T {
348        let previous = self.current;
349        self.current = current;
350        let ret = f(self);
351        self.current = previous;
352        ret
353    }
354
355    /// Returns a reference to the [Environment] model.
356    pub fn environment(&self) -> &Environment {
357        self.data::<Environment>()
358    }
359
360    /// Returns the entity id of the parent window of the current view.
361    pub fn parent_window(&self) -> Entity {
362        self.tree.get_parent_window(self.current).unwrap_or(Entity::root())
363    }
364
365    /// Returns the scale factor of the display.
366    pub fn scale_factor(&self) -> f32 {
367        self.style.dpi_factor as f32
368    }
369
370    /// Mark the application as needing to rerun the draw method
371    pub fn needs_redraw(&mut self, entity: Entity) {
372        if self.entity_manager.is_alive(entity) {
373            // If a child window needs redrawing, add itself to the redraw list.
374            // This ensures that the entire window is redrawn: https://github.com/vizia/vizia/issues/580
375            let window = if self.tree.is_window(entity) {
376                entity
377            } else {
378                self.tree.get_parent_window(entity).unwrap_or(Entity::root())
379            };
380            if let Some(window_state) = self.windows.get_mut(&window) {
381                window_state.redraw_list.insert(entity);
382            }
383        }
384    }
385
386    /// Mark the application as needing to recompute view styles
387    pub fn needs_restyle(&mut self, entity: Entity) {
388        self.style.needs_restyle_with_dependents(&self.tree, entity);
389    }
390
391    pub fn needs_retransform(&mut self, entity: Entity) {
392        self.style.needs_retransform(entity);
393    }
394
395    pub fn needs_reclip(&mut self, entity: Entity) {
396        self.style.needs_reclip(entity);
397    }
398
399    /// Mark the application as needing to rerun layout computations
400    pub fn needs_relayout(&mut self) {
401        self.style.needs_relayout(Entity::root());
402    }
403
404    pub(crate) fn set_system_flags(&mut self, entity: Entity, system_flags: SystemFlags) {
405        if system_flags.contains(SystemFlags::RELAYOUT) {
406            self.style.needs_relayout(entity);
407        }
408
409        if system_flags.contains(SystemFlags::RESTYLE) {
410            self.needs_restyle(entity);
411        }
412
413        if system_flags.contains(SystemFlags::REDRAW) {
414            self.needs_redraw(entity);
415        }
416
417        if system_flags.contains(SystemFlags::REFLOW) {
418            self.style.needs_text_update(entity);
419        }
420
421        if system_flags.contains(SystemFlags::RETRANSFORM) {
422            self.needs_retransform(entity);
423        }
424
425        if system_flags.contains(SystemFlags::RECLIP) {
426            self.needs_reclip(entity);
427        }
428
429        if system_flags.contains(SystemFlags::REACCESS) {
430            self.style.needs_access_update(entity);
431        }
432    }
433
434    /// Enables or disables PseudoClasses for the focus of an entity
435    pub(crate) fn set_focus_pseudo_classes(
436        &mut self,
437        focused: Entity,
438        enabled: bool,
439        focus_visible: bool,
440    ) {
441        if enabled {
442            debug!(
443                "Focus changed to {:?} parent: {:?}, view: {}, posx: {}, posy: {} width: {} height: {}",
444                focused,
445                self.tree.get_parent(focused),
446                self.views
447                    .get(&focused)
448                    .map_or("<None>", |view| view.element().unwrap_or("<Unnamed>")),
449                self.cache.get_posx(focused),
450                self.cache.get_posy(focused),
451                self.cache.get_width(focused),
452                self.cache.get_height(focused),
453            );
454        }
455
456        self.set_pseudo_class(focused, PseudoClassFlags::FOCUS, enabled);
457        if !enabled || focus_visible {
458            self.set_pseudo_class(focused, PseudoClassFlags::FOCUS_VISIBLE, enabled);
459            self.style.needs_access_update(focused);
460        }
461
462        let ancestors = focused.parent_iter(&self.tree).collect::<Vec<_>>();
463        for entity in ancestors {
464            self.set_pseudo_class(entity, PseudoClassFlags::FOCUS_WITHIN, enabled);
465        }
466    }
467
468    /// Sets or clears pseudo-class flags of an entity, restyling the entities whose matched rules
469    /// may depend on them if they changed.
470    pub(crate) fn set_pseudo_class(
471        &mut self,
472        entity: Entity,
473        flags: PseudoClassFlags,
474        enabled: bool,
475    ) {
476        if let Some(pseudo_classes) = self.style.pseudo_classes.get_mut(entity) {
477            let previous = *pseudo_classes;
478            pseudo_classes.set(flags, enabled);
479            let changed = previous.symmetric_difference(*pseudo_classes);
480            self.style.needs_restyle_for_state(&self.tree, entity, changed);
481        }
482    }
483
484    /// Sets application focus to the current entity with the specified focus visiblity
485    pub fn focus_with_visibility(&mut self, focus_visible: bool) {
486        let focusable = self.current == Entity::root()
487            || self
488                .style
489                .abilities
490                .get(self.current)
491                .is_some_and(|abilities| abilities.contains(Abilities::FOCUSABLE));
492        if !focusable {
493            return;
494        }
495
496        self.update_focus(focus_visible);
497    }
498
499    fn update_focus(&mut self, focus_visible: bool) {
500        let old_focus = self.focused;
501        let new_focus = self.current;
502        self.set_focus_pseudo_classes(old_focus, false, focus_visible);
503        if self.current != self.focused {
504            self.emit_to(old_focus, WindowEvent::FocusOut);
505            self.emit_to(new_focus, WindowEvent::FocusIn);
506            self.focused = self.current;
507        }
508        self.set_focus_pseudo_classes(new_focus, true, focus_visible);
509
510        self.emit_custom(Event::new(WindowEvent::FocusVisibility(focus_visible)).target(old_focus));
511        self.emit_custom(Event::new(WindowEvent::FocusVisibility(focus_visible)).target(new_focus));
512
513        self.needs_restyle(self.focused);
514        self.needs_restyle(self.current);
515        self.style.needs_access_update(self.focused);
516        self.style.needs_access_update(self.current);
517    }
518
519    /// Sets application focus to the current entity using the previous focus visibility
520    pub fn focus(&mut self) {
521        let focused = self.focused;
522        let old_focus_visible = self
523            .style
524            .pseudo_classes
525            .get_mut(focused)
526            .filter(|class| class.contains(PseudoClassFlags::FOCUS_VISIBLE))
527            .is_some();
528        self.focus_with_visibility(old_focus_visible)
529    }
530
531    /// Removes the children of the provided entity from the application.
532    pub(crate) fn remove_children(&mut self, entity: Entity) {
533        let child_iter = ChildIterator::new(&self.tree, entity);
534        let children = child_iter.collect::<Vec<_>>();
535        for child in children.into_iter() {
536            self.remove(child);
537        }
538    }
539
540    /// Removes the provided entity from the application.
541    pub fn remove(&mut self, entity: Entity) {
542        let delete_list = entity.branch_iter(&self.tree).collect::<Vec<_>>();
543
544        if !delete_list.is_empty() {
545            self.style.needs_restyle(self.current);
546            // An absolutely-positioned node is out of its parent's flow, so removing it cannot
547            // change the parent's layout — no relayout is needed (the vacated region is unioned
548            // into the window's dirty_rect below). Otherwise relayout incrementally from the parent
549            // of the removed entity so its remaining children reflow, rather than the whole tree.
550            let is_absolute = self.style.position_type.get(entity).copied().unwrap_or_default()
551                == PositionType::Absolute;
552            if !is_absolute {
553                if let Some(parent) = self.tree.get_layout_parent(entity) {
554                    self.style.needs_relayout(parent);
555                } else {
556                    self.style.needs_relayout(entity);
557                }
558            }
559            self.needs_redraw(self.current);
560        }
561
562        // Dirty the drawn areas of the removed entities before any cached draw bounds are
563        // invalidated, as invalidating an entity also invalidates its ancestors. The cached bounds
564        // of an entity cover all of its descendants, so covered descendants are skipped.
565        // Surviving ancestors can shrink during relayout, so preserve their own painted areas too.
566        for ancestor in LayoutParentIterator::new(&self.tree, entity)
567            .skip(1)
568            .take_while(|ancestor| !self.tree.is_window(*ancestor))
569        {
570            if let Some(bounds) =
571                crate::systems::draw::cached_own_screen_bounds(&self.cache, &self.tree, ancestor)
572                    .filter(|bounds| bounds.w > 0.0 && bounds.h > 0.0)
573            {
574                let window_entity = self.tree.get_parent_window(ancestor).unwrap_or(Entity::root());
575                let window = self.windows.get_mut(&window_entity).unwrap();
576                window.dirty_rect =
577                    Some(window.dirty_rect.map_or(bounds, |dirty_rect| dirty_rect.union(&bounds)));
578            }
579        }
580
581        let mut dirtied: HashSet<Entity> = HashSet::new();
582        for entity in delete_list.iter().copied() {
583            if self.tree.is_window(entity)
584                || LayoutParentIterator::new(&self.tree, entity)
585                    .skip(1)
586                    .any(|ancestor| dirtied.contains(&ancestor))
587            {
588                continue;
589            }
590
591            let Some(bounds) =
592                crate::systems::draw::cached_screen_bounds(&self.cache, &self.tree, entity)
593            else {
594                continue;
595            };
596            dirtied.insert(entity);
597
598            if bounds.w <= 0.0 || bounds.h <= 0.0 {
599                continue;
600            }
601            let window_entity = self.tree.get_parent_window(entity).unwrap_or(Entity::root());
602            if let Some(window) = self.windows.get_mut(&window_entity) {
603                window.dirty_rect =
604                    Some(window.dirty_rect.map_or(bounds, |dirty_rect| dirty_rect.union(&bounds)));
605            }
606        }
607
608        let mut cursor_icon_lock_window = None;
609
610        for entity in delete_list.iter().rev() {
611            if let Some(mut view) = self.views.remove(entity) {
612                view.event(
613                    &mut EventContext::new_with_current(self, *entity),
614                    &mut Event::new(WindowEvent::Destroyed).direct(*entity),
615                );
616
617                self.views.insert(*entity, view);
618            }
619
620            if let Some(binding) = self.bindings.remove(entity) {
621                binding.remove(self);
622
623                self.bindings.insert(*entity, binding);
624            }
625
626            for image in self.resource_manager.images.values_mut() {
627                // no need to drop them here. garbage collection happens after draw (policy based)
628                image.observers.remove(entity);
629            }
630
631            if let Some(identifier) = self.style.ids.get(*entity) {
632                self.entity_identifiers.remove(identifier);
633            }
634
635            if let Some(index) = self.focus_stack.iter().position(|r| r == entity) {
636                self.focus_stack.remove(index);
637            }
638
639            if self.focused == *entity {
640                if let Some(new_focus) = self.focus_stack.pop() {
641                    self.with_current(new_focus, |cx| cx.focus());
642                } else {
643                    // Fall back to the nearest enclosing window so focus is never
644                    // stranded on the root sentinel.
645                    let fallback = self.tree.get_parent_window(*entity).unwrap_or(Entity::root());
646                    self.with_current(fallback, |cx| cx.focus());
647                }
648
649                // `focus()` silently refuses to move focus to a non-focusable target (such as
650                // a plain window), which would leave `focused` dangling on the deleted entity
651                // and later crash consumers of the focus id (e.g. the accesskit tree update).
652                // Force focus to the nearest surviving ancestor window (or root) in that case.
653                if self.focused == *entity {
654                    let fallback = self.tree.get_parent_window(*entity).unwrap_or(Entity::root());
655                    let focus_visible =
656                        self.style.pseudo_classes.get_mut(*entity).is_some_and(|classes| {
657                            classes.contains(PseudoClassFlags::FOCUS_VISIBLE)
658                        });
659                    self.with_current(fallback, |cx| cx.update_focus(focus_visible));
660                }
661            }
662
663            if self.captured == *entity {
664                self.captured = Entity::null();
665            }
666
667            if let Some(parent) = self.tree.get_layout_parent(*entity) {
668                self.style.needs_access_update(parent);
669            }
670
671            let mut stopped_timers = Vec::new();
672
673            for timer in self.running_timers.iter() {
674                if timer.entity == *entity {
675                    stopped_timers.push(timer.id);
676                }
677            }
678
679            for timer in stopped_timers {
680                self.stop_timer(timer);
681            }
682
683            let window_entity = if self.tree.is_window(*entity) {
684                // The entity being removed IS a window – its own WindowState is the target.
685                *entity
686            } else {
687                self.tree.get_parent_window(*entity).unwrap_or(Entity::root())
688            };
689
690            if let Some(ws) = self.windows.get_mut(&window_entity) {
691                ws.redraw_list.remove(entity);
692            }
693
694            if self.cursor_icon_locked_by == Some(*entity) {
695                self.cursor_icon_locked_by = None;
696                cursor_icon_lock_window = Some(window_entity);
697            }
698
699            self.cache.invalidate_draw_bounds(&self.tree, *entity);
700
701            if self.windows.contains_key(entity) {
702                self.windows.remove(entity);
703                #[cfg(feature = "clipboard")]
704                self.clipboards.remove(entity);
705            }
706
707            self.tree.remove(*entity).expect("");
708            self.cache.remove(*entity);
709            self.style.remove(*entity);
710            self.models.remove(entity);
711            self.views.remove(entity);
712            self.listeners.remove(entity);
713            self.text_context.text_bounds.remove(*entity);
714            self.text_context.text_paragraphs.remove(*entity);
715            self.entity_manager.destroy(*entity);
716        }
717
718        // Releasing the lock of a removed view refreshes the cursor icon as an unlock does.
719        if let Some(window) = cursor_icon_lock_window
720            && self.windows.contains_key(&window)
721        {
722            let cursor = self.style.cursor.get(self.hovered).cloned().unwrap_or_default();
723            self.with_current(window, |cx| cx.emit(WindowEvent::SetCursor(cursor)));
724        }
725    }
726
727    /// Sets whether a view should have the given class name.
728    pub fn toggle_class(&mut self, name: &str, applied: impl Res<bool>) {
729        let name = name.to_owned();
730        let entity = self.current();
731        let current = self.current();
732        self.with_current(current, |cx| {
733            applied.set_or_bind(cx, move |cx, applied| {
734                let applied = applied.get_value(cx);
735                cx.style.set_class(&cx.tree, entity, &name, applied);
736            });
737        });
738    }
739
740    /// Add a listener to an entity.
741    ///
742    /// A listener can be used to handle events which would not normally propagate to the entity.
743    /// For example, mouse events when a different entity has captured them. Useful for things like
744    /// closing a popup when clicking outside of its bounding box.
745    pub fn add_listener<F, W>(&mut self, listener: F)
746    where
747        W: View,
748        F: 'static + Fn(&mut W, &mut EventContext, &mut Event),
749    {
750        self.listeners.insert(
751            self.current,
752            Box::new(move |event_handler, context, event| {
753                if let Some(widget) = event_handler.downcast_mut::<W>() {
754                    (listener)(widget, context, event);
755                }
756            }),
757        );
758    }
759
760    /// Adds a global listener to the application.
761    ///
762    /// Global listeners have the first opportunity to handle every event that is sent in an
763    /// application. They will *never* be removed. If you need a listener tied to the lifetime of a
764    /// view, use `add_listener`.
765    pub fn add_global_listener<F>(&mut self, listener: F)
766    where
767        F: 'static + Fn(&mut EventContext, &mut Event),
768    {
769        self.global_listeners.push(Box::new(listener));
770    }
771
772    /// Loads a font into the application from in-memory bytes.
773    pub fn load_font_mem(&mut self, data: impl AsRef<[u8]>) {
774        self.text_context.asset_provider.register_typeface(
775            self.text_context
776                .default_font_manager
777                .new_from_data(skia_safe::Data::new_copy(data.as_ref()), None)
778                .unwrap(),
779            None,
780        );
781    }
782
783    fn request_resource_if_not_loaded(
784        &mut self,
785        path: String,
786        request: crate::resource::ResourceRequest,
787        options: crate::resource::ResourceLoadOptions,
788    ) {
789        // Avoid re-issuing requests for resources that are already loading or resolved.
790        if self.resource_manager.resource_status(&path) != LoadingStatus::NotLoaded {
791            return;
792        }
793
794        self.resource_manager.queue_resource_request(request, options);
795    }
796
797    /// Returns a reactive loading-status signal for the provided resource path.
798    ///
799    /// The signal value is updated by resource loaders as the request progresses.
800    pub fn resource_status_signal(&mut self, path: impl Into<String>) -> Signal<LoadingStatus> {
801        let path = path.into();
802
803        if let Some(signal) = self.resource_manager.loading_status.get(&path).copied() {
804            return signal;
805        }
806
807        let status = self.resource_manager.resource_status(&path);
808        let signal = Signal::new(status);
809        self.resource_manager.loading_status.insert(path, signal);
810        signal
811    }
812
813    /// Returns the current loading status for the provided resource path.
814    ///
815    /// This reads from the same reactive signal used by [`Context::resource_status_signal`].
816    pub fn resource_status(&mut self, path: impl Into<String>) -> LoadingStatus {
817        self.resource_status_signal(path).get()
818    }
819
820    /// Adds a font to the application by loading it through the configured resource loaders.
821    ///
822    /// This supports local files (including `file://` URLs) and any custom loader you register.
823    pub fn add_font(
824        &mut self,
825        path: impl Into<String>,
826        options: Option<crate::resource::ResourceLoadOptions>,
827    ) {
828        let path = path.into();
829        let options = options.unwrap_or_default();
830
831        self.request_resource_if_not_loaded(
832            path.clone(),
833            crate::resource::ResourceRequest::Font(crate::resource::FontRequest { path }),
834            options,
835        );
836    }
837
838    /// Queues an image resource request and returns a reactive loading-status signal.
839    ///
840    /// `name` is the key used to reference the image from CSS and [`Image::new`].
841    /// `path` can be a filesystem path, `file://` URL, or HTTP(S) URL (with `url-loader`).
842    pub fn add_image(
843        &mut self,
844        name: impl Into<String>,
845        path: impl Into<String>,
846        policy: ImageRetentionPolicy,
847        options: Option<crate::resource::ResourceLoadOptions>,
848    ) -> Signal<LoadingStatus> {
849        let name = name.into();
850        let path = path.into();
851        let options = options.unwrap_or_default();
852
853        self.resource_manager.register_image_source(name.clone(), path.clone());
854
855        // If the path is already loaded and load_image ran before this add_image call,
856        // immediately alias the existing ImageId to the new name so it resolves without
857        // waiting for another load cycle.
858        if self.resource_manager.resource_status(&path) != crate::resource::LoadingStatus::NotLoaded
859        {
860            let existing_id = self
861                .resource_manager
862                .image_sources
863                .iter()
864                .find(|(alias, alias_path)| {
865                    *alias_path == &path && self.resource_manager.image_ids.contains_key(*alias)
866                })
867                .and_then(|(alias, _)| self.resource_manager.image_ids.get(alias).copied());
868            if let Some(id) = existing_id {
869                self.resource_manager.image_ids.entry(name.clone()).or_insert(id);
870            }
871            // If no id exists yet the path is still loading; load_image will back-fill via
872            // the alias scan above when it runs.
873        }
874
875        self.request_resource_if_not_loaded(
876            path.clone(),
877            crate::resource::ResourceRequest::Image(crate::resource::ImageRequest {
878                name,
879                path: path.clone(),
880                policy,
881            }),
882            options,
883        );
884
885        self.resource_status_signal(path)
886    }
887
888    /// Adds a translation file to the application by loading it through the configured resource
889    /// loaders.
890    ///
891    /// This supports local files (including `file://` URLs), HTTP(S) URLs when the
892    /// `url-loader` feature is enabled, and any custom loader you register.
893    pub fn add_translation_file(
894        &mut self,
895        lang: LanguageIdentifier,
896        path: impl Into<String>,
897        options: Option<crate::resource::ResourceLoadOptions>,
898    ) {
899        let path = path.into();
900        let options = options.unwrap_or_default();
901
902        self.request_resource_if_not_loaded(
903            path.clone(),
904            crate::resource::ResourceRequest::Translation(crate::resource::TranslationRequest {
905                lang,
906                path,
907            }),
908            options,
909        );
910    }
911
912    /// Returns the element name (e.g. `"textbox"`) of the currently focused
913    /// view, or `None` if the focused entity has no view or the view doesn't
914    /// declare an element name.
915    ///
916    /// Mirrors [`BackendContext::focused_element`] for use from contexts
917    /// (such as the `on_idle` application callback) that receive a
918    /// `&mut Context` directly.
919    pub fn focused_element(&self) -> Option<&'static str> {
920        self.views.get(&self.focused).and_then(|view| view.element())
921    }
922
923    pub fn add_stylesheet(&mut self, style: impl IntoCssStr) -> Result<(), std::io::Error> {
924        self.resource_manager.styles.push(Box::new(style));
925
926        EventContext::new(self).reload_styles().expect("Failed to reload styles");
927
928        Ok(())
929    }
930
931    /// Remove all user themes from the application.
932    pub fn add_built_in_styles(&mut self) {
933        self.add_built_in_translations();
934
935        let user_styles = if self.built_in_styles_added {
936            if self.resource_manager.styles.len() >= 3 {
937                self.resource_manager.styles.drain(3..).collect::<Vec<_>>()
938            } else {
939                Vec::new()
940            }
941        } else {
942            std::mem::take(&mut self.resource_manager.styles)
943        };
944
945        self.resource_manager.styles.clear();
946
947        self.resource_manager.styles.push(Box::new(DEFAULT_LAYOUT));
948        self.resource_manager.styles.push(Box::new(MARKDOWN));
949
950        if !self.ignore_default_theme {
951            self.resource_manager.styles.push(Box::new(DEFAULT_THEME));
952            let environment = self.data::<Environment>();
953            let theme_mode = environment.effective_theme();
954            let direction = environment.direction.get();
955            let cx = &mut EventContext::new(self);
956            apply_theme_class(cx, theme_mode == ThemeMode::DarkMode);
957            apply_direction_class(cx, direction);
958        } else {
959            // Add an empty stylesheet to ensure that the list of styles contains at least three entries.
960            self.resource_manager.styles.push(Box::new(""));
961        }
962
963        self.resource_manager.styles.extend(user_styles);
964        self.built_in_styles_added = true;
965
966        EventContext::new(self).reload_styles().unwrap();
967    }
968
969    /// Adds built-in translations for default view strings.
970    pub fn add_built_in_translations(&mut self) {
971        if self.built_in_translations_added {
972            return;
973        }
974
975        self.load_translation("en-US".parse().unwrap(), DEFAULT_TRANSLATION_EN_US)
976            .expect("Failed to load built-in en-US translation resources");
977        self.built_in_translations_added = true;
978    }
979
980    pub fn add_animation(&mut self, animation: AnimationBuilder) -> Animation {
981        self.style.add_animation(animation)
982    }
983
984    /// Adds a resource loader to the loading chain.
985    ///
986    /// Loaders are tried in list order, and this method inserts at the front so custom
987    /// loaders take priority over built-in loaders. The first loader that returns `true`
988    /// handles the request, and subsequent loaders are skipped.
989    pub fn add_resource_loader<L: crate::resource::ResourceLoader>(&mut self, loader: L) {
990        self.resource_manager.resource_loaders.insert(0, Box::new(loader));
991    }
992
993    /// Loads a translation into the application for the provided language.
994    ///
995    /// Returns an error if the FTL syntax is invalid or the resource cannot be added to the bundle.
996    pub fn load_translation(
997        &mut self,
998        lang: LanguageIdentifier,
999        ftl: impl ToString,
1000    ) -> Result<(), crate::resource::TranslationError> {
1001        self.resource_manager.add_translation(lang, ftl.to_string())
1002    }
1003
1004    /// Adds a timer to the application.
1005    ///
1006    /// `interval` - The time between ticks of the timer.
1007    /// `duration` - An optional duration for the timer. Pass `None` for a continuos timer.
1008    /// `callback` - A callback which is called on when the timer is started, ticks, and stops. Disambiguated by the `TimerAction` parameter of the callback.
1009    ///
1010    /// Returns a `Timer` id which can be used to start and stop the timer.  
1011    ///
1012    /// # Example
1013    /// Creates a timer which calls the provided callback every second for 5 seconds:
1014    /// ```rust
1015    /// # use vizia_core::prelude::*;
1016    /// # use instant::{Instant, Duration};
1017    /// # let cx = &mut Context::default();
1018    /// let timer = cx.add_timer(Duration::from_secs(1), Some(Duration::from_secs(5)), |cx, reason|{
1019    ///     match reason {
1020    ///         TimerAction::Start => {
1021    ///             debug!("Start timer");
1022    ///         }
1023    ///     
1024    ///         TimerAction::Tick(delta) => {
1025    ///             debug!("Tick timer: {:?}", delta);
1026    ///         }
1027    ///
1028    ///         TimerAction::Stop => {
1029    ///             debug!("Stop timer");
1030    ///         }
1031    ///     }
1032    /// });
1033    /// ```
1034    pub fn add_timer(
1035        &mut self,
1036        interval: Duration,
1037        duration: Option<Duration>,
1038        callback: impl Fn(&mut EventContext, TimerAction) + 'static,
1039    ) -> Timer {
1040        let id = Timer(self.timers.len());
1041        self.timers.push(TimerState {
1042            entity: Entity::root(),
1043            id,
1044            time: Instant::now(),
1045            interval,
1046            duration,
1047            start_time: Instant::now(),
1048            callback: Rc::new(callback),
1049            ticking: false,
1050            stopping: false,
1051        });
1052
1053        id
1054    }
1055
1056    /// Starts a timer with the provided timer id.
1057    ///
1058    /// Events sent within the timer callback provided in `add_timer()` will target the current view.
1059    pub fn start_timer(&mut self, timer: Timer) {
1060        let current = self.current;
1061        if !self.timer_is_running(timer) {
1062            let timer_state = self.timers[timer.0].clone();
1063            // Copy timer state from pending to playing
1064            self.running_timers.push(timer_state);
1065        }
1066
1067        self.modify_timer(timer, |timer_state| {
1068            let now = Instant::now();
1069            timer_state.start_time = now;
1070            timer_state.time = now;
1071            timer_state.entity = current;
1072            timer_state.ticking = false;
1073            timer_state.stopping = false;
1074        });
1075    }
1076
1077    /// Modifies the state of an existing timer with the provided `Timer` id.
1078    pub fn modify_timer(&mut self, timer: Timer, timer_function: impl Fn(&mut TimerState)) {
1079        let mut running_timers = self.running_timers.clone().into_vec();
1080
1081        if let Some(timer_state) =
1082            running_timers.iter_mut().find(|timer_state| timer_state.id == timer)
1083        {
1084            (timer_function)(timer_state);
1085            self.running_timers = running_timers.into();
1086            return;
1087        }
1088
1089        for pending_timer in self.timers.iter_mut() {
1090            if pending_timer.id == timer {
1091                (timer_function)(pending_timer);
1092            }
1093        }
1094    }
1095
1096    /// Returns true if the timer with the provided timer id is currently running.
1097    pub fn timer_is_running(&mut self, timer: Timer) -> bool {
1098        for timer_state in self.running_timers.iter() {
1099            if timer_state.id == timer {
1100                return true;
1101            }
1102        }
1103
1104        false
1105    }
1106
1107    /// Stops the timer with the given timer id.
1108    ///
1109    /// 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()`.
1110    pub fn stop_timer(&mut self, timer: Timer) {
1111        let mut running_timers = self.running_timers.clone();
1112
1113        for timer_state in running_timers.iter() {
1114            if timer_state.id == timer {
1115                (timer_state.callback)(
1116                    &mut EventContext::new_with_current(self, timer_state.entity),
1117                    TimerAction::Stop,
1118                );
1119            }
1120        }
1121
1122        self.running_timers =
1123            running_timers.drain().filter(|timer_state| timer_state.id != timer).collect();
1124    }
1125
1126    // Tick all timers.
1127    pub(crate) fn tick_timers(&mut self) {
1128        let now = Instant::now();
1129        while let Some(next_timer_state) = self.running_timers.peek() {
1130            if next_timer_state.time <= now {
1131                let mut timer_state = self.running_timers.pop().unwrap();
1132
1133                if timer_state.end_time().unwrap_or_else(|| now + Duration::from_secs(1)) >= now {
1134                    if !timer_state.ticking {
1135                        (timer_state.callback)(
1136                            &mut EventContext::new_with_current(self, timer_state.entity),
1137                            TimerAction::Start,
1138                        );
1139                        timer_state.ticking = true;
1140                    } else {
1141                        (timer_state.callback)(
1142                            &mut EventContext::new_with_current(self, timer_state.entity),
1143                            TimerAction::Tick(now - timer_state.time),
1144                        );
1145                    }
1146                    timer_state.time = now + timer_state.interval - (now - timer_state.time);
1147                    self.running_timers.push(timer_state);
1148                } else {
1149                    (timer_state.callback)(
1150                        &mut EventContext::new_with_current(self, timer_state.entity),
1151                        TimerAction::Stop,
1152                    );
1153                }
1154            } else {
1155                break;
1156            }
1157        }
1158    }
1159
1160    /// Loads an image from memory and associates it with the provided path.
1161    pub fn load_image(&mut self, path: &str, data: &'static [u8], policy: ImageRetentionPolicy) {
1162        let id = if let Some(image_id) = self.resource_manager.image_ids.get(path) {
1163            *image_id
1164        } else {
1165            let id = self.resource_manager.image_id_manager.create();
1166            self.resource_manager.image_ids.insert(path.to_owned(), id);
1167            id
1168        };
1169
1170        if let Some(image) =
1171            skia_safe::Image::from_encoded(unsafe { skia_safe::Data::new_bytes(data) })
1172        {
1173            match self.resource_manager.images.entry(id) {
1174                Entry::Occupied(mut occ) => {
1175                    occ.get_mut().image = ImageOrSvg::Image(image);
1176                    occ.get_mut().dirty = true;
1177                    occ.get_mut().retention_policy = policy;
1178                }
1179                Entry::Vacant(vac) => {
1180                    vac.insert(StoredImage {
1181                        image: ImageOrSvg::Image(image),
1182                        retention_policy: policy,
1183                        used: true,
1184                        dirty: false,
1185                        observers: HashSet::new(),
1186                    });
1187                }
1188            }
1189            let observers: Vec<Entity> = self
1190                .resource_manager
1191                .images
1192                .get(&id)
1193                .map(|img| img.observers.iter().copied().collect())
1194                .unwrap_or_default();
1195            for observer in observers {
1196                self.style.needs_relayout(observer);
1197                self.needs_redraw(observer);
1198            }
1199            self.style.needs_relayout(self.current);
1200            self.needs_redraw(self.current);
1201        }
1202    }
1203
1204    pub fn load_svg(&mut self, path: &str, data: &[u8], policy: ImageRetentionPolicy) -> ImageId {
1205        let id = if let Some(image_id) = self.resource_manager.image_ids.get(path) {
1206            return *image_id;
1207        } else {
1208            let id = self.resource_manager.image_id_manager.create();
1209            self.resource_manager.image_ids.insert(path.to_owned(), id);
1210            id
1211        };
1212
1213        if let Ok(svg) = svg::Dom::from_bytes(data, self.text_context.default_font_manager.clone())
1214        {
1215            match self.resource_manager.images.entry(id) {
1216                Entry::Occupied(mut occ) => {
1217                    occ.get_mut().image = ImageOrSvg::Svg(svg);
1218                    occ.get_mut().dirty = true;
1219                    occ.get_mut().retention_policy = policy;
1220                }
1221                Entry::Vacant(vac) => {
1222                    vac.insert(StoredImage {
1223                        image: ImageOrSvg::Svg(svg),
1224                        retention_policy: policy,
1225                        used: true,
1226                        dirty: false,
1227                        observers: HashSet::new(),
1228                    });
1229                }
1230            }
1231            // Relayout only the entities that display this resource (its observers) plus the
1232            // current entity (e.g. the freshly-built Svg view triggering the load), rather than
1233            // forcing a full tree relayout.
1234            let observers: Vec<Entity> = self
1235                .resource_manager
1236                .images
1237                .get(&id)
1238                .map(|img| img.observers.iter().copied().collect())
1239                .unwrap_or_default();
1240            for observer in observers {
1241                self.style.needs_relayout(observer);
1242                self.needs_redraw(observer);
1243            }
1244            self.style.needs_relayout(self.current);
1245            self.needs_redraw(self.current);
1246        }
1247
1248        id
1249    }
1250
1251    pub fn spawn<F>(&self, target: F)
1252    where
1253        F: 'static + Send + FnOnce(&mut ContextProxy),
1254    {
1255        let mut cxp = ContextProxy {
1256            current: self.current,
1257            event_proxy: self.event_proxy.as_ref().map(|p| p.make_clone()),
1258        };
1259
1260        std::thread::spawn(move || target(&mut cxp));
1261    }
1262
1263    pub fn get_proxy(&self) -> ContextProxy {
1264        ContextProxy {
1265            current: self.current,
1266            event_proxy: self.event_proxy.as_ref().map(|p| p.make_clone()),
1267        }
1268    }
1269
1270    #[cfg(feature = "tokio")]
1271    /// Submits a configured [`TaskBuilder`] for asynchronous execution.
1272    ///
1273    /// Tasks run on Vizia's shared Tokio runtime and complete through the
1274    /// `on_result(...)` callback attached to the builder, when one is provided.
1275    ///
1276    /// Returns a [`TaskHandle`] that can be used to request cancellation.
1277    ///
1278    /// # Example
1279    /// ```rust,no_run
1280    /// # use vizia_core::prelude::*;
1281    /// # #[cfg(feature = "tokio")]
1282    /// # {
1283    /// # let cx = Context::default();
1284    /// // Fire-and-forget:
1285    /// cx.add_task(Task::new(|_| async move { Ok::<(), &'static str>(()) }));
1286    ///
1287    /// // With completion handling:
1288    /// cx.add_task(
1289    ///     Task::new(|_| async move { Ok::<_, &'static str>("loaded") })
1290    ///         .on_result(|result, proxy| {
1291    ///             if let TaskResult::Completed(message) = result {
1292    ///                 let _ = proxy.emit(message);
1293    ///             }
1294    ///         }),
1295    /// );
1296    /// # }
1297    /// ```
1298    pub fn add_task<T, E>(&self, task: TaskBuilder<T, E>) -> TaskHandle
1299    where
1300        T: Send + 'static,
1301        E: Send + 'static,
1302    {
1303        task.add_to_context(self)
1304    }
1305
1306    /// Finds the entity that identifier identifies
1307    pub(crate) fn resolve_entity_identifier(&self, identity: &str) -> Option<Entity> {
1308        self.entity_identifiers.get(identity).cloned()
1309    }
1310
1311    pub fn set_ime_state(&mut self, new_state: ImeState) {
1312        self.ime_state = new_state;
1313    }
1314}
1315
1316pub(crate) enum InternalEvent {
1317    Redraw,
1318    RefreshHover,
1319    LoadImage { path: String, image: Mutex<Option<skia_safe::Image>>, policy: ImageRetentionPolicy },
1320    LoadSvg { path: String, data: Vec<u8>, policy: ImageRetentionPolicy },
1321    LoadFont { path: String, data: Vec<u8> },
1322    LoadTranslation { lang: LanguageIdentifier, path: String, ftl: String },
1323    UpdateResourceStatus { path: String, status: LoadingStatus },
1324}
1325
1326pub struct LocalizationContext<'a> {
1327    pub(crate) current: Entity,
1328    pub(crate) resource_manager: &'a ResourceManager,
1329    pub(crate) models: &'a Models,
1330    pub(crate) views: &'a Views,
1331    pub(crate) tree: &'a Tree<Entity>,
1332}
1333
1334impl<'a> LocalizationContext<'a> {
1335    pub(crate) fn from_context(cx: &'a Context) -> Self {
1336        Self {
1337            current: cx.current,
1338            resource_manager: &cx.resource_manager,
1339            models: &cx.models,
1340            views: &cx.views,
1341            tree: &cx.tree,
1342        }
1343    }
1344
1345    pub(crate) fn from_event_context(cx: &'a EventContext) -> Self {
1346        Self {
1347            current: cx.current,
1348            resource_manager: cx.resource_manager,
1349            models: cx.models,
1350            views: cx.views,
1351            tree: cx.tree,
1352        }
1353    }
1354
1355    pub(crate) fn environment(&self) -> &Environment {
1356        self.data::<Environment>()
1357    }
1358}
1359
1360/// A trait for any Context-like object that lets you access stored model data.
1361///
1362/// This lets resource reads be generic over any of these types.
1363pub trait DataContext {
1364    /// Get model/view data from the context. Returns `None` if the data does not exist.
1365    fn try_data<T: 'static>(&self) -> Option<&T>;
1366
1367    /// Get model/view data from the context. Panics if the data does not exist.
1368    fn data<T: 'static>(&self) -> &T {
1369        self.try_data::<T>().expect("data not found in context")
1370    }
1371
1372    /// Convert the current context into a [LocalizationContext].
1373    fn localization_context(&self) -> Option<LocalizationContext<'_>> {
1374        None
1375    }
1376}
1377
1378/// A trait for any Context-like object that lets you emit events.
1379pub trait EmitContext {
1380    /// Send an event containing the provided message up the tree from the current entity.
1381    ///
1382    /// # Example
1383    /// ```rust
1384    /// # use vizia_core::prelude::*;
1385    /// # use instant::{Instant, Duration};
1386    /// # let cx = &mut Context::default();
1387    /// # enum AppEvent {Increment}
1388    /// cx.emit(AppEvent::Increment);
1389    /// ```
1390    fn emit<M: Any>(&mut self, message: M);
1391
1392    /// Send an event containing the provided message directly to a specified entity from the current entity.
1393    ///
1394    /// # Example
1395    /// ```rust
1396    /// # use vizia_core::prelude::*;
1397    /// # use instant::{Instant, Duration};
1398    /// # let cx = &mut Context::default();
1399    /// # enum AppEvent {Increment}
1400    /// cx.emit_to(Entity::root(), AppEvent::Increment);
1401    /// ```
1402    fn emit_to<M: Any>(&mut self, target: Entity, message: M);
1403
1404    /// Send a custom event with custom origin and propagation information.
1405    ///
1406    /// # Example
1407    /// ```rust
1408    /// # use vizia_core::prelude::*;
1409    /// # use instant::{Instant, Duration};
1410    /// # let cx = &mut Context::default();
1411    /// # enum AppEvent {Increment}
1412    /// cx.emit_custom(
1413    ///     Event::new(AppEvent::Increment)
1414    ///         .origin(cx.current())
1415    ///         .target(Entity::root())
1416    ///         .propagate(Propagation::Subtree)
1417    /// );
1418    /// ```
1419    fn emit_custom(&mut self, event: Event);
1420
1421    /// Send an event containing the provided message up the tree at a particular time instant.
1422    ///
1423    /// Returns a `TimedEventHandle` which can be used to cancel the scheduled event.
1424    ///
1425    /// # Example
1426    /// Emit an event after a delay of 2 seconds:
1427    /// ```rust
1428    /// # use vizia_core::prelude::*;
1429    /// # use instant::{Instant, Duration};
1430    /// # let cx = &mut Context::default();
1431    /// # enum AppEvent {Increment}
1432    /// cx.schedule_emit(AppEvent::Increment, Instant::now() + Duration::from_secs(2));
1433    /// ```
1434    fn schedule_emit<M: Any>(&mut self, message: M, at: Instant) -> TimedEventHandle;
1435
1436    /// Send an event containing the provided message directly to a specified view at a particular time instant.
1437    ///
1438    /// Returns a `TimedEventHandle` which can be used to cancel the scheduled event.
1439    ///
1440    /// # Example
1441    /// Emit an event to the root view (window) after a delay of 2 seconds:
1442    /// ```rust
1443    /// # use vizia_core::prelude::*;
1444    /// # use instant::{Instant, Duration};
1445    /// # let cx = &mut Context::default();
1446    /// # enum AppEvent {Increment}
1447    /// cx.schedule_emit_to(Entity::root(), AppEvent::Increment, Instant::now() + Duration::from_secs(2));
1448    /// ```
1449    fn schedule_emit_to<M: Any>(
1450        &mut self,
1451        target: Entity,
1452        message: M,
1453        at: Instant,
1454    ) -> TimedEventHandle;
1455
1456    /// Send a custom event with custom origin and propagation information at a particular time instant.
1457    ///
1458    /// Returns a `TimedEventHandle` which can be used to cancel the scheduled event.
1459    ///
1460    /// # Example
1461    /// Emit a custom event after a delay of 2 seconds:
1462    /// ```rust
1463    /// # use vizia_core::prelude::*;
1464    /// # use instant::{Instant, Duration};
1465    /// # let cx = &mut Context::default();
1466    /// # enum AppEvent {Increment}
1467    /// cx.schedule_emit_custom(    
1468    ///     Event::new(AppEvent::Increment)
1469    ///         .target(Entity::root())
1470    ///         .origin(cx.current())
1471    ///         .propagate(Propagation::Subtree),
1472    ///     Instant::now() + Duration::from_secs(2)
1473    /// );
1474    /// ```
1475    fn schedule_emit_custom(&mut self, event: Event, at: Instant) -> TimedEventHandle;
1476
1477    /// Cancel a scheduled event before it is sent.
1478    ///
1479    /// # Example
1480    /// ```rust
1481    /// # use vizia_core::prelude::*;
1482    /// # use instant::{Instant, Duration};
1483    /// # let cx = &mut Context::default();
1484    /// # enum AppEvent {Increment}
1485    /// let timed_event = cx.schedule_emit_to(Entity::root(), AppEvent::Increment, Instant::now() + Duration::from_secs(2));
1486    /// cx.cancel_scheduled(timed_event);
1487    /// ```
1488    fn cancel_scheduled(&mut self, handle: TimedEventHandle);
1489}
1490
1491impl DataContext for Context {
1492    fn try_data<T: 'static>(&self) -> Option<&T> {
1493        // return data for the static model.
1494        if let Some(t) = <dyn Any>::downcast_ref::<T>(&()) {
1495            return Some(t);
1496        }
1497
1498        for entity in self.current.parent_iter(&self.tree) {
1499            // Return any model data.
1500            if let Some(models) = self.models.get(&entity)
1501                && let Some(model) = models.get(&TypeId::of::<T>())
1502            {
1503                return model.downcast_ref::<T>();
1504            }
1505
1506            // Return any view data.
1507            if let Some(view_handler) = self.views.get(&entity)
1508                && let Some(data) = view_handler.downcast_ref::<T>()
1509            {
1510                return Some(data);
1511            }
1512        }
1513
1514        None
1515    }
1516
1517    fn localization_context(&self) -> Option<LocalizationContext<'_>> {
1518        Some(LocalizationContext::from_context(self))
1519    }
1520}
1521
1522impl DataContext for LocalizationContext<'_> {
1523    fn try_data<T: 'static>(&self) -> Option<&T> {
1524        // return data for the static model.
1525        if let Some(t) = <dyn Any>::downcast_ref::<T>(&()) {
1526            return Some(t);
1527        }
1528
1529        for entity in self.current.parent_iter(self.tree) {
1530            // Return any model data.
1531            if let Some(models) = self.models.get(&entity)
1532                && let Some(model) = models.get(&TypeId::of::<T>())
1533            {
1534                return model.downcast_ref::<T>();
1535            }
1536
1537            // Return any view data.
1538            if let Some(view_handler) = self.views.get(&entity)
1539                && let Some(data) = view_handler.downcast_ref::<T>()
1540            {
1541                return Some(data);
1542            }
1543        }
1544
1545        None
1546    }
1547}
1548
1549impl EmitContext for Context {
1550    fn emit<M: Any>(&mut self, message: M) {
1551        self.send_event(
1552            Event::new(message)
1553                .target(self.current)
1554                .origin(self.current)
1555                .propagate(Propagation::Up),
1556        );
1557    }
1558
1559    fn emit_to<M: Any>(&mut self, target: Entity, message: M) {
1560        self.send_event(
1561            Event::new(message).target(target).origin(self.current).propagate(Propagation::Direct),
1562        );
1563    }
1564
1565    fn emit_custom(&mut self, event: Event) {
1566        self.send_event(event);
1567    }
1568
1569    fn schedule_emit<M: Any>(&mut self, message: M, at: Instant) -> TimedEventHandle {
1570        self.schedule_emit_custom(
1571            Event::new(message)
1572                .target(self.current)
1573                .origin(self.current)
1574                .propagate(Propagation::Up),
1575            at,
1576        )
1577    }
1578
1579    fn schedule_emit_to<M: Any>(
1580        &mut self,
1581        target: Entity,
1582        message: M,
1583        at: Instant,
1584    ) -> TimedEventHandle {
1585        self.schedule_emit_custom(
1586            Event::new(message).target(target).origin(self.current).propagate(Propagation::Direct),
1587            at,
1588        )
1589    }
1590
1591    fn schedule_emit_custom(&mut self, event: Event, at: Instant) -> TimedEventHandle {
1592        let handle = TimedEventHandle(self.next_event_id);
1593        self.event_schedule.push(TimedEvent {
1594            event: event.inherit_ui_modifiers(self.modifiers),
1595            time: at,
1596            ident: handle,
1597        });
1598        self.next_event_id += 1;
1599        handle
1600    }
1601
1602    fn cancel_scheduled(&mut self, handle: TimedEventHandle) {
1603        self.event_schedule =
1604            self.event_schedule.drain().filter(|item| item.ident != handle).collect();
1605    }
1606}
1607
1608#[cfg(test)]
1609mod tests {
1610    use super::*;
1611    use crate::events::EventManager;
1612
1613    fn context() -> Context {
1614        let mut cx = Context::new();
1615        cx.windows.insert(Entity::root(), WindowState::default());
1616        cx.cache.set_bounds(Entity::root(), BoundingBox { x: 0.0, y: 0.0, w: 400.0, h: 400.0 });
1617        cx
1618    }
1619
1620    #[test]
1621    fn removed_subtrees_release_typed_listeners_and_preserve_survivors() {
1622        let mut cx = context();
1623        let deliveries = Rc::new(std::cell::Cell::new(0));
1624        let survivor = Element::new(&mut cx).entity();
1625        cx.with_current(survivor, |cx| {
1626            let deliveries = deliveries.clone();
1627            cx.add_listener(move |_: &mut Element, _, event| {
1628                event.map(|_: &u32, _| deliveries.set(deliveries.get() + 1));
1629            });
1630        });
1631        let baseline = cx.listeners.len();
1632        for cycle in 0..16 {
1633            let parent = Element::new(&mut cx).entity();
1634            let child = cx.with_current(parent, |cx| Element::new(cx).entity());
1635            for owner in [parent, child] {
1636                cx.with_current(owner, |cx| cx.add_listener(|_: &mut Element, _, _| {}));
1637            }
1638            assert_eq!(cx.listeners.len(), baseline + 2);
1639            cx.remove(parent);
1640            assert_eq!(cx.listeners.len(), baseline, "cycle {cycle} retains only living owners");
1641            assert!(!cx.listeners.contains_key(&parent));
1642            assert!(!cx.listeners.contains_key(&child));
1643            cx.emit_to(Entity::root(), cycle as u32);
1644            EventManager::new().flush_events(&mut cx, |_| {});
1645            assert_eq!(deliveries.get(), cycle + 1);
1646            assert!(cx.listeners.contains_key(&survivor));
1647        }
1648    }
1649
1650    #[test]
1651    fn recycled_entities_own_only_their_current_typed_listener() {
1652        let mut cx = context();
1653        let baseline = cx.listeners.len();
1654        let removed_deliveries = Rc::new(std::cell::Cell::new(0));
1655        let removed = Element::new(&mut cx).entity();
1656        cx.with_current(removed, |cx| {
1657            let deliveries = removed_deliveries.clone();
1658            cx.add_listener(move |_: &mut Element, _, event| {
1659                event.map(|_: &u32, _| deliveries.set(deliveries.get() + 1));
1660            });
1661        });
1662        cx.remove(removed);
1663        let replacement = loop {
1664            let candidate = Element::new(&mut cx).entity();
1665            if candidate.index() == removed.index() {
1666                break candidate;
1667            }
1668            cx.remove(candidate);
1669        };
1670        assert_ne!(replacement.generation(), removed.generation());
1671        let deliveries = Rc::new(std::cell::Cell::new(0));
1672        cx.with_current(replacement, |cx| {
1673            let deliveries = deliveries.clone();
1674            cx.add_listener(move |_: &mut Element, _, event| {
1675                event.map(|_: &u32, _| deliveries.set(deliveries.get() + 1));
1676            });
1677        });
1678        cx.emit_to(Entity::root(), 7_u32);
1679        EventManager::new().flush_events(&mut cx, |_| {});
1680        assert_eq!(deliveries.get(), 1);
1681        assert_eq!(removed_deliveries.get(), 0);
1682        assert!(!cx.listeners.contains_key(&removed), "destroyed generation releases its listener");
1683        assert!(cx.listeners.contains_key(&replacement));
1684        assert_eq!(cx.listeners.len(), baseline + 1);
1685        cx.remove(replacement);
1686        assert_eq!(cx.listeners.len(), baseline);
1687    }
1688
1689    fn lock_cursor_icon(cx: &mut Context, holder: Entity) {
1690        EventContext::new_with_current(cx, holder).lock_cursor_icon();
1691    }
1692
1693    fn unlock_cursor_icon(cx: &mut Context, caller: Entity) {
1694        EventContext::new_with_current(cx, caller).unlock_cursor_icon();
1695    }
1696
1697    fn is_cursor_icon_locked(cx: &mut Context) -> bool {
1698        EventContext::new(cx).is_cursor_icon_locked()
1699    }
1700
1701    fn flush_cursor_updates(cx: &mut Context) -> Vec<CursorIcon> {
1702        let mut cursors = Vec::new();
1703        EventManager::new().flush_events(cx, |window_event| {
1704            if let WindowEvent::SetCursor(cursor) = window_event {
1705                cursors.push(*cursor);
1706            }
1707        });
1708        cursors
1709    }
1710
1711    #[test]
1712    fn removed_subtrees_release_their_cursor_icon_lock() {
1713        let mut cx = context();
1714        let hovered = Element::new(&mut cx).entity();
1715        cx.style.cursor.insert(hovered, CursorIcon::Move);
1716        cx.hovered = hovered;
1717        for cycle in 0..4 {
1718            let parent = Element::new(&mut cx).entity();
1719            let holder = cx.with_current(parent, |cx| Element::new(cx).entity());
1720            lock_cursor_icon(&mut cx, holder);
1721            assert!(is_cursor_icon_locked(&mut cx));
1722            assert!(flush_cursor_updates(&mut cx).is_empty());
1723            cx.remove(parent);
1724            assert!(
1725                !is_cursor_icon_locked(&mut cx),
1726                "cycle {cycle} releases the removed holder's lock"
1727            );
1728            assert_eq!(flush_cursor_updates(&mut cx), vec![CursorIcon::Move]);
1729        }
1730    }
1731
1732    #[test]
1733    fn cursor_icon_lock_belongs_to_its_living_holder() {
1734        let mut cx = context();
1735        let holder = Element::new(&mut cx).entity();
1736        let bystander = Element::new(&mut cx).entity();
1737        let removed = Element::new(&mut cx).entity();
1738        cx.with_current(removed, |cx| Element::new(cx).entity());
1739        lock_cursor_icon(&mut cx, holder);
1740        cx.remove(removed);
1741        assert!(is_cursor_icon_locked(&mut cx), "removing an unrelated subtree keeps the lock");
1742        assert!(flush_cursor_updates(&mut cx).is_empty());
1743        unlock_cursor_icon(&mut cx, bystander);
1744        assert!(is_cursor_icon_locked(&mut cx), "only the holder releases its lock");
1745        assert!(flush_cursor_updates(&mut cx).is_empty());
1746        unlock_cursor_icon(&mut cx, holder);
1747        assert!(!is_cursor_icon_locked(&mut cx));
1748        assert_eq!(flush_cursor_updates(&mut cx), vec![CursorIcon::Default]);
1749        cx.remove(holder);
1750        assert!(flush_cursor_updates(&mut cx).is_empty());
1751    }
1752
1753    #[test]
1754    fn removed_windows_release_their_cursor_icon_lock_without_a_cursor_update() {
1755        let mut cx = context();
1756        let window = Element::new(&mut cx).entity();
1757        cx.tree.set_window(window, true);
1758        cx.windows.insert(window, WindowState::default());
1759        let holder = cx.with_current(window, |cx| Element::new(cx).entity());
1760        lock_cursor_icon(&mut cx, holder);
1761        cx.remove(window);
1762        assert!(!is_cursor_icon_locked(&mut cx));
1763        assert!(flush_cursor_updates(&mut cx).is_empty(), "a removed window gets no cursor update");
1764    }
1765}