use scheduler::Instant;
use std::{cell::RefCell, rc::Rc, time::Duration};
use crate::{
App, Hitbox, HoverListenerMode, MouseDownEvent, Pixels, Point, ScrollDelta, ScrollEvent,
TouchPhase, Window,
};
pub(crate) const HOVER_FREEZE: Duration = Duration::from_millis(100);
pub(crate) struct HoverFreeze {
last_wheel: Option<(Instant, Point<Pixels>)>,
fingers: Fingers,
enabled: bool,
hovered: Vec<HoveredListener>,
}
#[derive(Clone, Copy, Default, PartialEq, Eq)]
enum Fingers {
#[default]
Lifted,
Resting,
Scrolling,
}
impl Fingers {
fn after(self, phase: TouchPhase, delta: ScrollDelta) -> Self {
let moved = match delta {
ScrollDelta::Pixels(delta) => delta.x != Pixels::ZERO || delta.y != Pixels::ZERO,
ScrollDelta::Lines(delta) => delta.x != 0. || delta.y != 0.,
};
match phase {
TouchPhase::Started if moved => Self::Scrolling,
TouchPhase::Started => Self::Resting,
TouchPhase::Moved if self == Self::Lifted || !moved => Self::Lifted,
TouchPhase::Moved => Self::Scrolling,
TouchPhase::Ended | TouchPhase::Cancelled => Self::Lifted,
}
}
}
#[derive(Clone)]
struct HoveredListener {
was_hovered: Rc<RefCell<bool>>,
has_mouse_down: Rc<RefCell<Option<MouseDownEvent>>>,
listener: Rc<dyn Fn(&bool, &mut Window, &mut App)>,
hitbox: Hitbox,
mode: HoverListenerMode,
}
impl HoveredListener {
fn update(&self, is_hovered: bool, window: &mut Window, cx: &mut App) {
if is_hovered == *self.was_hovered.borrow() {
return;
}
*self.was_hovered.borrow_mut() = is_hovered;
self.heard(is_hovered, window);
(self.listener)(&is_hovered, window, cx);
}
fn heard(&self, is_hovered: bool, window: &mut Window) {
if is_hovered {
note_hovered(window, self);
} else {
let hovered = &mut window.fast_layers.hover_freeze.hovered;
hovered.retain(|listener| !Rc::ptr_eq(&listener.was_hovered, &self.was_hovered));
}
}
fn still_hovered(&self, window: &Window, cx: &App) -> bool {
(self.has_mouse_down.borrow().is_some()
&& window
.rendered_frame
.hitboxes
.iter()
.any(|hitbox| hitbox.id == self.hitbox.id))
|| (!cx.has_active_drag() && self.mode.is_hovered(&self.hitbox, window))
}
}
pub(crate) fn track_listener(
window: &mut Window,
was_hovered: &Rc<RefCell<bool>>,
has_mouse_down: &Rc<RefCell<Option<MouseDownEvent>>>,
listener: impl Fn(&bool, &mut Window, &mut App) + 'static,
hitbox: &Hitbox,
mode: HoverListenerMode,
) -> Rc<dyn Fn(&bool, &mut Window, &mut App)> {
let tracked = HoveredListener {
was_hovered: was_hovered.clone(),
has_mouse_down: has_mouse_down.clone(),
listener: Rc::new(listener),
hitbox: hitbox.clone(),
mode,
};
if *was_hovered.borrow() {
note_hovered(window, &tracked);
}
Rc::new(
move |is_hovered: &bool, window: &mut Window, cx: &mut App| {
tracked.heard(*is_hovered, window);
(tracked.listener)(is_hovered, window, cx);
},
)
}
fn note_hovered(window: &mut Window, listener: &HoveredListener) {
let hovered = &mut window.fast_layers.hover_freeze.hovered;
match hovered
.iter_mut()
.find(|held| Rc::ptr_eq(&held.was_hovered, &listener.was_hovered))
{
Some(held) => *held = listener.clone(),
None => hovered.push(listener.clone()),
}
}
pub(crate) fn release_unhovered(window: &mut Window, cx: &mut App) {
if window.fast_layers.hover_freeze.hovered.is_empty() || frozen(window) {
return;
}
for index in 0..window.fast_layers.hover_freeze.hovered.len() {
let held = &window.fast_layers.hover_freeze.hovered[index];
if !held.still_hovered(window, cx) {
let held = held.clone();
window.defer(cx, move |window, cx| held.update(false, window, cx));
}
}
}
impl Default for HoverFreeze {
fn default() -> Self {
Self {
last_wheel: None,
fingers: Fingers::default(),
enabled: !cfg!(test),
hovered: Vec::new(),
}
}
}
pub(crate) fn note_wheel(window: &mut Window, cx: &mut App, event: &ScrollEvent) {
let freeze = &mut window.fast_layers.hover_freeze;
if !freeze.enabled {
return;
}
freeze.last_wheel = Some((Instant::now(), window.mouse_position));
freeze.fingers = freeze.fingers.after(event.touch_phase, event.delta);
window
.spawn(cx, async move |cx| {
cx.background_executor()
.timer(HOVER_FREEZE + Duration::from_millis(10))
.await;
cx.update(|window, _| {
if !frozen(window) {
window.refresh();
}
})
.ok();
})
.detach();
}
pub(crate) fn frozen(window: &Window) -> bool {
let freeze = &window.fast_layers.hover_freeze;
freeze.last_wheel.is_some_and(|(at, position)| {
(freeze.fingers == Fingers::Scrolling || at.elapsed() < HOVER_FREEZE)
&& position == window.mouse_position
})
}
pub(crate) fn hides_hover(window: &Window) -> bool {
window.last_input_was_keyboard() || (!window.invalidator.not_drawing() && frozen(window))
}
pub(crate) fn holds_listeners(window: &Window) -> bool {
!window.invalidator.not_drawing() && frozen(window)
}
impl Window {
#[cfg(test)]
pub(crate) fn set_hover_freeze(&mut self, enabled: bool) {
self.fast_layers.hover_freeze.enabled = enabled;
self.fast_layers.hover_freeze.last_wheel = None;
self.fast_layers.hover_freeze.fingers = Fingers::default();
}
}
#[cfg(test)]
impl HoverFreeze {
pub(crate) fn end_for_test(&mut self) {
self.last_wheel = None;
self.fingers = Fingers::default();
}
pub(crate) fn hovered_listeners(&self) -> usize {
self.hovered.len()
}
}
#[cfg(test)]
mod tests {
use super::{HOVER_FREEZE, frozen};
use crate::{
Context, IntoElement, MouseMoveEvent, PlatformInput, Render, ScrollDelta, ScrollEvent,
Styled as _, TestAppContext, TouchPhase, Window, WindowHandle, div, point, px,
};
struct Page;
impl Render for Page {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div().size_full()
}
}
fn open(cx: &mut TestAppContext) -> WindowHandle<Page> {
let window = cx.add_window(|_, _| Page);
window
.update(cx, |_, window, _| window.set_hover_freeze(true))
.unwrap();
window
}
fn wheel(cx: &mut TestAppContext, window: WindowHandle<Page>, phase: TouchPhase, dy: f32) {
window
.update(cx, |_, window, cx| {
window.dispatch_event(
PlatformInput::Scroll(ScrollEvent {
position: point(px(10.), px(10.)),
delta: ScrollDelta::Pixels(point(px(0.), px(dy))),
touch_phase: phase,
..Default::default()
}),
cx,
);
})
.unwrap();
}
fn held_after_a_pause(cx: &mut TestAppContext, window: WindowHandle<Page>) -> bool {
window
.update(cx, |_, window, _| {
if let Some((at, _)) = &mut window.fast_layers.hover_freeze.last_wheel {
*at = at.checked_sub(HOVER_FREEZE * 2).unwrap();
}
frozen(window)
})
.unwrap()
}
#[crate::test]
fn a_swipe_holds_hover_still_until_its_fingers_lift(cx: &mut TestAppContext) {
let window = open(cx);
wheel(cx, window, TouchPhase::Started, 0.);
wheel(cx, window, TouchPhase::Moved, -12.);
assert!(held_after_a_pause(cx, window), "fingers paused mid-swipe");
wheel(cx, window, TouchPhase::Moved, -8.);
assert!(held_after_a_pause(cx, window), "and again");
wheel(cx, window, TouchPhase::Ended, 0.);
assert!(window.update(cx, |_, window, _| frozen(window)).unwrap());
assert!(!held_after_a_pause(cx, window), "lifted");
wheel(cx, window, TouchPhase::Moved, -20.);
assert!(!held_after_a_pause(cx, window), "momentum");
}
#[crate::test]
fn only_a_swipe_that_moved_holds_hover_still(cx: &mut TestAppContext) {
let window = open(cx);
wheel(cx, window, TouchPhase::Started, 0.);
assert!(!held_after_a_pause(cx, window), "resting");
wheel(cx, window, TouchPhase::Moved, 0.);
assert!(!held_after_a_pause(cx, window), "touched and lifted");
wheel(cx, window, TouchPhase::Moved, -40.);
assert!(!held_after_a_pause(cx, window), "wheel");
}
#[crate::test]
fn a_pointer_that_moves_ends_a_held_swipe(cx: &mut TestAppContext) {
let window = open(cx);
wheel(cx, window, TouchPhase::Started, 0.);
wheel(cx, window, TouchPhase::Moved, -12.);
window
.update(cx, |_, window, cx| {
window.dispatch_event(
PlatformInput::MouseMove(MouseMoveEvent {
position: point(px(30.), px(30.)),
pressed_button: None,
modifiers: Default::default(),
}),
cx,
);
})
.unwrap();
assert!(!window.update(cx, |_, window, _| frozen(window)).unwrap());
}
}