azul-layout 0.0.10

Layout solver + font and image loader the Azul GUI framework
Documentation
//! Hover state management for tracking mouse and touch hover history
//!
//! The `HoverManager` records hit test results for multiple input points
//! (mouse, touch, pen) over multiple frames to enable gesture detection
//! (like `DragStart`) that requires analyzing hover patterns over time
//! rather than just the current frame.

use std::collections::{BTreeMap, VecDeque};

use crate::hit_test::FullHitTest;

/// Maximum number of frames to keep in hover history
const MAX_HOVER_HISTORY: usize = 5;

/// Pick the front-most deepest hovered node across all hit DOMs.
///
/// Iterates DOMs from highest `DomId` (most-nested child, composited on top)
/// to lowest and returns the deepest node (last in `NodeId` order) of the first
/// DOM that actually has a regular hit. See [`HoverManager::current_hover_node_full`].
fn deepest_node_across_doms(ht: &FullHitTest) -> Option<azul_core::dom::DomNodeId> {
    for (dom_id, hit) in ht.hovered_nodes.iter().rev() {
        if let Some(node_id) = hit.regular_hit_test_nodes.keys().last().copied() {
            return Some(azul_core::dom::DomNodeId {
                dom: *dom_id,
                node: azul_core::styled_dom::NodeHierarchyItemId::from_crate_internal(Some(
                    node_id,
                )),
            });
        }
    }
    None
}

/// Identifier for an input point (mouse, touch, pen, etc.)
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum InputPointId {
    /// Mouse cursor
    Mouse,
    /// Touch point with unique ID (from TouchEvent.id)
    Touch(u64),
}

/// Manages hover state history for all input points
///
/// Records hit test results for mouse and touch inputs over multiple frames:
/// - `DragStart` detection (requires movement threshold over multiple frames)
/// - Hover-over event detection
/// - Multi-touch gesture detection
/// - Input path analysis
///
/// The manager maintains a separate history for each active input point.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HoverManager {
    /// Hit test history for each input point
    /// Each point has its own ring buffer of the last N frames
    hover_histories: BTreeMap<InputPointId, VecDeque<FullHitTest>>,
}

impl HoverManager {
    /// Create a new empty `HoverManager`
    #[must_use] pub const fn new() -> Self {
        Self {
            hover_histories: BTreeMap::new(),
        }
    }

    /// (input points, total history entries across all points). Used by
    /// `AZ_E2E_TEST` to watch for unbounded growth.
    #[must_use] pub fn debug_counts(&self) -> (usize, usize) {
        let points = self.hover_histories.len();
        let total: usize = self.hover_histories.values().map(VecDeque::len).sum();
        (points, total)
    }

    /// Push a new hit test result for a specific input point
    ///
    /// The most recent result is always at index 0 for that input point.
    /// If the history is full, the oldest frame is dropped.
    pub fn push_hit_test(&mut self, input_id: InputPointId, hit_test: FullHitTest) {
        let history = self
            .hover_histories
            .entry(input_id)
            .or_insert_with(|| VecDeque::with_capacity(MAX_HOVER_HISTORY));

        // Add to front (most recent)
        history.push_front(hit_test);

        // Remove oldest if we exceed the limit
        if history.len() > MAX_HOVER_HISTORY {
            history.pop_back();
        }
    }

    /// Remove an input point's history (e.g., when touch ends)
    pub fn remove_input_point(&mut self, input_id: &InputPointId) {
        self.hover_histories.remove(input_id);
    }

    /// Get the most recent hit test result for an input point
    ///
    /// Returns None if no hit tests have been recorded for this input point.
    #[must_use] pub fn get_current(&self, input_id: &InputPointId) -> Option<&FullHitTest> {
        self.hover_histories
            .get(input_id)
            .and_then(|history| history.front())
    }

    /// Get the most recent mouse cursor hit test (convenience method)
    #[must_use] pub fn get_current_mouse(&self) -> Option<&FullHitTest> {
        self.get_current(&InputPointId::Mouse)
    }

    /// Get the hit test result from N frames ago for an input point
    /// (0 = current frame)
    ///
    /// Returns None if the requested frame is not in history.
    #[must_use] pub fn get_frame(&self, input_id: &InputPointId, frames_ago: usize) -> Option<&FullHitTest> {
        self.hover_histories
            .get(input_id)
            .and_then(|history| history.get(frames_ago))
    }

    /// Get the entire hover history for an input point (most recent first)
    #[must_use] pub fn get_history(&self, input_id: &InputPointId) -> Option<&VecDeque<FullHitTest>> {
        self.hover_histories.get(input_id)
    }

    /// Get all currently tracked input points
    #[must_use] pub fn get_active_input_points(&self) -> Vec<InputPointId> {
        self.hover_histories.keys().copied().collect()
    }

    /// Get the number of frames in history for an input point
    #[must_use] pub fn frame_count(&self, input_id: &InputPointId) -> usize {
        self.hover_histories
            .get(input_id)
            .map_or(0, VecDeque::len)
    }

    /// Purge every recorded hit-test entry for `dom_id` across all input
    /// points and all history frames.
    ///
    /// Called when a `VirtualView` child DOM is rebuilt IN PLACE (fresh `NodeIds`,
    /// no reconcile mapping — e.g. a `MapWidget` pan rebuilding the tile grid):
    /// the recorded hits for that DOM reference the OLD generation's `NodeIds`,
    /// and consumers that resolve them against the NEW styled DOM read out of
    /// bounds (the `hit_test.rs` cursor panic: "len is 25 but the index is 27")
    /// or target the wrong node. Unlike incremental reconciles there is no
    /// `NodeId` map to `remap` with, so the only safe option is to forget that
    /// DOM's hits; the next pointer move re-populates them from a fresh
    /// hit test.
    pub fn purge_dom(&mut self, dom_id: &azul_core::dom::DomId) {
        for history in self.hover_histories.values_mut() {
            for frame in history.iter_mut() {
                frame.hovered_nodes.remove(dom_id);
            }
        }
    }

    /// Clear all hover history for all input points
    pub fn clear(&mut self) {
        self.hover_histories.clear();
    }

    /// Clear history for a specific input point
    pub(crate) fn clear_input_point(&mut self, input_id: &InputPointId) {
        if let Some(history) = self.hover_histories.get_mut(input_id) {
            history.clear();
        }
    }

    /// Check if we have enough frames for gesture detection on an input point
    ///
    /// `DragStart` detection requires analyzing movement over multiple frames.
    /// This returns true if we have at least 2 frames of history.
    #[must_use] pub fn has_sufficient_history_for_gestures(&self, input_id: &InputPointId) -> bool {
        self.frame_count(input_id) >= 2
    }

    /// Check if any input point has enough history for gesture detection
    #[must_use] pub fn any_has_sufficient_history_for_gestures(&self) -> bool {
        self.hover_histories
            .iter()
            .any(|(_, history)| history.len() >= 2)
    }

    /// Get the deepest hovered node from the current mouse hit test.
    ///
    /// Returns the `NodeId` of the most specific (deepest in DOM tree) node
    /// that the mouse cursor is currently over, or None if not hovering anything.
    ///
    /// NOTE: Assumes single-DOM architecture (uses `DomId { inner: 0 }`).
    #[must_use] pub fn current_hover_node(&self) -> Option<azul_core::id::NodeId> {
        let current = self.get_current_mouse()?;
        let dom_id = azul_core::dom::DomId { inner: 0 };
        let ht = current.hovered_nodes.get(&dom_id)?;
        ht.regular_hit_test_nodes.keys().last().copied()
    }

    /// Get the deepest hovered node from the previous frame's mouse hit test.
    ///
    /// Returns the `NodeId` from one frame ago, or None if not hovering anything
    /// or no previous frame exists.
    ///
    /// NOTE: Assumes single-DOM architecture (uses `DomId { inner: 0 }`).
    #[must_use] pub fn previous_hover_node(&self) -> Option<azul_core::id::NodeId> {
        let history = self.hover_histories.get(&InputPointId::Mouse)?;
        let previous = history.get(1)?; // index 1 = one frame ago
        let dom_id = azul_core::dom::DomId { inner: 0 };
        let ht = previous.hovered_nodes.get(&dom_id)?;
        ht.regular_hit_test_nodes.keys().last().copied()
    }

    /// Multi-DOM aware: the deepest hovered node across ALL hit DOMs (current
    /// frame). Returns a full `DomNodeId` so events can target `VirtualView` /
    /// iframe child DOMs, not just the root.
    ///
    /// Selection rule: prefer the most-nested DOM that was hit. Child DOMs
    /// (`VirtualView` / iframe content) always have higher `DomId`s than their
    /// host and are composited on top of it, so the highest hit `DomId` is the
    /// front-most surface. Within that DOM the deepest node (last in `NodeId`
    /// order) is the W3C event target; bubbling then reaches ancestor handlers.
    ///
    /// For single-DOM apps only `DomId 0` is ever hit, so this is equivalent to
    /// [`current_hover_node`] wrapped in `DomId { inner: 0 }`.
    #[must_use] pub fn current_hover_node_full(&self) -> Option<azul_core::dom::DomNodeId> {
        deepest_node_across_doms(self.get_current_mouse()?)
    }

    /// Multi-DOM aware counterpart of [`previous_hover_node`] (one frame ago).
    #[must_use] pub fn previous_hover_node_full(&self) -> Option<azul_core::dom::DomNodeId> {
        let history = self.hover_histories.get(&InputPointId::Mouse)?;
        deepest_node_across_doms(history.get(1)?)
    }

}

impl crate::managers::NodeIdRemap for HoverManager {
    /// Remap `NodeIds` in all hover histories after DOM reconciliation.
    ///
    /// Hits on unmounted nodes are dropped (they cannot be hovered any more) —
    /// keeping them would make the hover history describe a node that no longer
    /// exists at that index.
    fn remap_node_ids(&mut self, dom_id: azul_core::dom::DomId, map: &crate::managers::NodeIdMap) {
        let node_id_map = map.as_btree_map();
        for history in self.hover_histories.values_mut() {
            for hit_test in history.iter_mut() {
                if let Some(ht) = hit_test.hovered_nodes.get_mut(&dom_id) {
                    crate::managers::remap_keys(&mut ht.regular_hit_test_nodes, map);
                    crate::managers::remap_keys(&mut ht.scroll_hit_test_nodes, map);
                    crate::managers::remap_keys(&mut ht.cursor_hit_test_nodes, map);

                    // Remap scrollbar_hit_test_nodes (ScrollbarHitId contains NodeId)
                    let old_sb: Vec<_> = ht.scrollbar_hit_test_nodes.keys().copied().collect();
                    let mut new_sb = BTreeMap::new();
                    for old_key in old_sb {
                        let Some(new_key) = remap_scrollbar_hit_id(&old_key, dom_id, node_id_map)
                        else {
                            // node unmounted — drop the scrollbar hit
                            ht.scrollbar_hit_test_nodes.remove(&old_key);
                            continue;
                        };
                        if let Some(item) = ht.scrollbar_hit_test_nodes.remove(&old_key) {
                            new_sb.insert(new_key, item);
                        }
                    }
                    ht.scrollbar_hit_test_nodes = new_sb;
                }
            }
        }
    }
}

impl Default for HoverManager {
    fn default() -> Self {
        Self::new()
    }
}

/// Remap a `ScrollbarHitId`'s `NodeId` using the reconciliation map.
/// `None` = the node was unmounted, so the hit must be dropped.
/// A `ScrollbarHitId` for a different `DomId` is returned unchanged.
fn remap_scrollbar_hit_id(
    id: &azul_core::hit_test::ScrollbarHitId,
    dom_id: azul_core::dom::DomId,
    node_id_map: &BTreeMap<azul_core::id::NodeId, azul_core::id::NodeId>,
) -> Option<azul_core::hit_test::ScrollbarHitId> {
    use azul_core::hit_test::ScrollbarHitId;
    Some(match id {
        ScrollbarHitId::VerticalTrack(d, n) if *d == dom_id => {
            ScrollbarHitId::VerticalTrack(*d, *node_id_map.get(n)?)
        }
        ScrollbarHitId::VerticalThumb(d, n) if *d == dom_id => {
            ScrollbarHitId::VerticalThumb(*d, *node_id_map.get(n)?)
        }
        ScrollbarHitId::HorizontalTrack(d, n) if *d == dom_id => {
            ScrollbarHitId::HorizontalTrack(*d, *node_id_map.get(n)?)
        }
        ScrollbarHitId::HorizontalThumb(d, n) if *d == dom_id => {
            ScrollbarHitId::HorizontalThumb(*d, *node_id_map.get(n)?)
        }
        other => *other,
    })
}