use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use crate::component::ComponentId;
use crate::event::{EventArgs, PointerEvent};
use crate::timing::{self, TimerPrecision};
use crate::ui::Ui;
pub const LONG_PRESS_TIME: f64 = 0.5;
pub(crate) const HOVER_CARD_GRACE: f64 = 0.3;
#[derive(Default)]
struct HoverCards {
current: Option<HoverCard>,
last: Option<(ComponentId, Option<ComponentId>, crate::PointF, Option<(ComponentId, ComponentId)>)>,
}
#[derive(Clone, Copy, Debug)]
struct HoverCard {
root: ComponentId,
anchor: ComponentId,
card: ComponentId,
since: f64,
at: crate::PointF,
shown: bool,
seen: bool,
dismissed: bool,
outside: Option<f64>,
}
pub(crate) struct Timeout {
pub(crate) id: u64,
pub(crate) due: f64,
pub(crate) job: Box<dyn FnOnce(&mut Ui)>,
}
pub(crate) struct TimerEntry {
pub(crate) id: ComponentId,
pub(crate) interval: f64,
pub(crate) next: f64,
pub(crate) precision: TimerPrecision,
pub(crate) thread: Option<(Arc<AtomicBool>, std::thread::Thread)>,
}
impl TimerEntry {
fn start(ui: &Ui, id: ComponentId, interval: f64, precision: TimerPrecision, background: bool) -> Self {
if precision != TimerPrecision::Normal {
timing::fine_clock(true);
}
let thread = background.then(|| {
let stop = Arc::new(AtomicBool::new(false));
let poster = ui.poster();
let flag = stop.clone();
let period = Duration::from_secs_f64(interval);
let spawned = std::thread::Builder::new().name("aylis-timer".into()).spawn(move || {
let mut next = Instant::now() + period;
loop {
if !timing::park_until(next, precision, &flag) {
break;
}
let now = Instant::now();
let late = now.saturating_duration_since(next).as_secs_f64();
if Arc::strong_count(&poster.0) == 1 {
break;
}
let f = flag.clone();
poster.post(move |ui| {
if !f.load(Ordering::Relaxed) {
ui.fire_timer(id, late);
}
});
next += period;
if next <= now {
next = now + period;
}
}
});
match spawned {
Ok(handle) => (stop, handle.thread().clone()),
Err(_) => (stop, std::thread::current()),
}
});
let next = if thread.is_some() { f64::INFINITY } else { ui.time + interval };
Self { id, interval, next, precision, thread }
}
pub(crate) fn stop(self) {
if self.precision != TimerPrecision::Normal {
timing::fine_clock(false);
}
if let Some((flag, thread)) = self.thread {
flag.store(true, Ordering::Relaxed);
thread.unpark();
}
}
}
impl Ui {
pub fn sync_timer(&mut self, id: ComponentId) {
let wanted = self.component(id).and_then(|c| {
let c = c.timed()?;
let interval = c.timer_interval().filter(|i| *i > 0.0)?;
Some((interval, c.timer_precision(), c.timer_background()))
});
let position = self.timers.iter().position(|t| t.id == id);
match (position, wanted) {
(Some(i), Some((interval, precision, background))) => {
let t = &self.timers[i];
if (t.interval - interval).abs() > f64::EPSILON || t.precision != precision || t.thread.is_some() != background {
self.timers.remove(i).stop();
let entry = TimerEntry::start(self, id, interval, precision, background);
self.timers.push(entry);
}
}
(Some(i), None) => self.timers.remove(i).stop(),
(None, Some((interval, precision, background))) => {
let entry = TimerEntry::start(self, id, interval, precision, background);
self.timers.push(entry);
}
(None, None) => {}
}
}
pub fn restart_timer(&mut self, id: ComponentId) {
if let Some(i) = self.timers.iter().position(|t| t.id == id) {
self.timers.remove(i).stop();
}
self.sync_timer(id);
}
fn fire_timer(&mut self, id: ComponentId, late: f64) {
let _profile = crate::profile::scope(crate::profile::Lane::Timer, || self.path_of(id));
let _ = self.with_component(id, |c, ctx| {
match c.timed_mut() {
Some(t) => {
t.timer_late(late);
t.timer(ctx);
}
None => ctx.fire("on_timer", crate::EventArgs::None),
}
});
self.sync_timer(id);
}
pub fn exact_timer_due(&self) -> Option<f64> {
self.timers.iter().filter(|t| t.precision == TimerPrecision::Exact && t.thread.is_none()).map(|t| t.next).reduce(f64::min)
}
pub fn set_timeout(&mut self, ms: u64, job: impl FnOnce(&mut Ui) + 'static) -> u64 {
self.next_timeout += 1;
let id = self.next_timeout;
self.timeouts.push(Timeout { id, due: self.time + ms as f64 / 1000.0, job: Box::new(job) });
self.request_repaint();
id
}
pub fn clear_timeout(&mut self, id: u64) {
self.timeouts.retain(|t| t.id != id);
}
pub fn run_timers(&mut self) -> bool {
if self.design_mode {
return false;
}
let now = self.time;
let mut due_now: Vec<(f64, u64)> = self.timeouts.iter().filter(|t| t.due <= now).map(|t| (t.due, t.id)).collect();
due_now.sort_by(|a, b| a.0.total_cmp(&b.0));
let ran_timeout = !due_now.is_empty();
for (_, id) in due_now {
if let Some(i) = self.timeouts.iter().position(|t| t.id == id) {
let t = self.timeouts.remove(i);
(t.job)(self);
}
}
if ran_timeout {
self.process_events();
}
let due: Vec<(ComponentId, f64)> = self.timers.iter().filter(|t| t.next <= now).map(|t| (t.id, now - t.next)).collect();
for t in self.timers.iter_mut().filter(|t| t.next <= now) {
t.next = if now - t.next > t.interval { now + t.interval } else { t.next + t.interval };
}
for &(id, late) in &due {
self.fire_timer(id, late);
}
let pressed = self.check_long_press();
let hint = self.check_hints();
let card = self.check_hover_cards();
ran_timeout || !due.is_empty() || pressed || hint || card
}
fn check_hover_cards(&mut self) -> bool {
let now = self.time;
let state = self.extension_ref::<HoverCards>().and_then(|h| h.current);
let roots: Vec<ComponentId> = self.input.keys().copied().collect();
let mut found = None;
for &root in &roots {
let Some(pointer) = self.pointer_position(root) else { continue };
let hovered = self.hovered(root);
let cached = self.extension_ref::<HoverCards>().and_then(|h| h.last).filter(|l| l.0 == root && l.1 == hovered && l.2 == pointer).map(|l| l.3);
let hit = match cached {
Some(hit) => hit,
None => {
let hit = self.hover_card_at(root, hovered, pointer);
self.extension::<HoverCards>().last = Some((root, hovered, pointer, hit));
hit
}
};
if let Some((anchor, card)) = hit {
found = Some((root, anchor, card, pointer));
break;
}
}
let open = |ui: &Ui, card: ComponentId| ui.cb(card).is_some_and(|cb| cb.visible());
let next = match state {
None => found.map(|(root, anchor, card, at)| HoverCard { root, anchor, card, since: now, at, shown: false, seen: false, dismissed: false, outside: None }),
Some(s) if !s.shown => match found {
Some((root, anchor, card, at)) if anchor == s.anchor && card == s.card => {
let d = at - s.at;
let moved = d.x.abs() > 4.0 || d.y.abs() > 4.0;
let s = if moved { HoverCard { since: now, at, ..s } } else { s };
if !s.dismissed && now >= s.since + self.hover_card_delay(anchor) {
let _ = self.invoke(s.card, "popup_hover", &[crate::PropValue::Component(Some(s.anchor))]);
Some(HoverCard { root, shown: true, seen: false, since: now, ..s })
} else {
Some(s)
}
}
Some((root, anchor, card, at)) => Some(HoverCard { root, anchor, card, since: now, at, shown: false, seen: false, dismissed: false, outside: None }),
None => None,
},
Some(s) => {
let visible = open(self, s.card);
let s = HoverCard { seen: s.seen || visible, ..s };
if s.seen && !visible {
match found {
Some((_, anchor, _, _)) if anchor == s.anchor => Some(HoverCard { shown: false, dismissed: true, ..s }),
_ => None,
}
} else {
let pointer = self.pointer_position(s.root);
let inside = pointer.is_some_and(|p| self.hover_card_region(s.anchor, s.card).iter().any(|r| r.contains(p)))
|| found.is_some_and(|(_, anchor, _, _)| anchor == s.anchor);
match (inside, s.outside) {
(true, _) => Some(HoverCard { outside: None, ..s }),
(false, None) => Some(HoverCard { outside: Some(now), ..s }),
(false, Some(since)) if now < since + HOVER_CARD_GRACE => Some(s),
(false, Some(_)) => {
let _ = self.invoke(s.card, "close", &[]);
found
.filter(|&(_, anchor, _, _)| anchor != s.anchor)
.map(|(root, anchor, card, at)| HoverCard { root, anchor, card, since: now, at, shown: false, seen: false, dismissed: false, outside: None })
}
}
}
}
};
if next.is_none() && state.is_none() {
return false;
}
let changed = next.map(|n| n.shown) != state.map(|s| s.shown);
self.extension::<HoverCards>().current = next;
changed
}
fn hover_card_at(&self, root: ComponentId, hovered: Option<ComponentId>, p: crate::PointF) -> Option<(ComponentId, ComponentId)> {
let card_of = |c: ComponentId| self.cb(c).and_then(|cb| cb.hover_card()).filter(|&card| card != c && self.contains(card));
let start = hovered?;
let mut below = None;
let mut cur = start;
while let Some(next) = self
.children(cur)
.iter()
.rev()
.copied()
.find(|&c| self.cb(c).is_some_and(|cb| cb.visible()) && self.absolute_rect(c).is_some_and(|r| r.contains(p)))
{
if let Some(card) = card_of(next) {
below = Some((next, card));
}
cur = next;
}
if below.is_some() {
return below;
}
let mut cur = Some(start);
while let Some(c) = cur {
if let Some(card) = card_of(c) {
return Some((c, card));
}
if c == root {
break;
}
cur = self.parent(c);
}
None
}
fn hover_card_delay(&self, anchor: ComponentId) -> f64 {
match self.cb(anchor).map_or(0.0, |cb| cb.hover_delay()) {
ms if ms > 0.0 => ms as f64 / 1000.0,
_ => self.hint_delay(),
}
}
fn hover_card_region(&self, anchor: ComponentId, card: ComponentId) -> Vec<crate::RectF> {
let (Some(a), Some(c)) = (self.absolute_rect(anchor), self.absolute_rect(card)) else { return Vec::new() };
let span = |a0: f32, a1: f32, c0: f32, c1: f32| if a1 <= c0 { Some((a1, c0)) } else if c1 <= a0 { Some((c1, a0)) } else { None };
let mut out = vec![a, c];
if let Some((top, bottom)) = span(a.y, a.bottom(), c.y, c.bottom()) {
let (x0, x1) = (a.x.max(c.x), a.right().min(c.right()));
let (x0, x1) = if x1 > x0 { (x0, x1) } else { (a.x.min(c.x), a.right().max(c.right())) };
out.push(crate::RectF::new(x0, top, x1 - x0, bottom - top));
} else if let Some((left, right)) = span(a.x, a.right(), c.x, c.right()) {
let (y0, y1) = (a.y.max(c.y), a.bottom().min(c.bottom()));
let (y0, y1) = if y1 > y0 { (y0, y1) } else { (a.y.min(c.y), a.bottom().max(c.bottom())) };
out.push(crate::RectF::new(left, y0, right - left, y1 - y0));
}
out
}
fn check_hints(&mut self) -> bool {
let now = self.time;
let delay = self.hint_delay();
let mut any = false;
for state in self.input.values_mut() {
if let Some(h) = state.hint.as_mut().filter(|h| !h.shown && now >= h.since + delay) {
h.shown = true;
any = true;
}
}
if any {
self.request_repaint();
}
any
}
pub(crate) fn timers_wake(&self) -> Option<f64> {
let timer = self.timers.iter().map(|t| t.next).filter(|n| n.is_finite()).chain(self.timeouts.iter().map(|t| t.due)).reduce(f64::min);
let delay = self.hint_delay();
let card = self.extension_ref::<HoverCards>().and_then(|h| h.current).and_then(|s| match (s.shown, s.outside) {
(false, _) if !s.dismissed => Some(s.since + self.hover_card_delay(s.anchor)),
(true, Some(since)) => Some(since + HOVER_CARD_GRACE),
_ => None,
});
let press = self
.input
.values()
.flat_map(|s| [s.long_press_due(), s.hint_due(delay)])
.flatten()
.chain(card)
.reduce(f64::min);
match (timer, press) {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
}
}
fn check_long_press(&mut self) -> bool {
let now = self.time;
let roots: Vec<ComponentId> = self.input.keys().copied().collect();
let mut any = false;
for root in roots {
let Some((target, position, touch)) = self.input.get_mut(&root).and_then(|s| s.take_long_press(now)) else {
continue;
};
if !touch || !self.contains(target) {
continue;
}
any = true;
let local = self.local_point(target, position);
let event = PointerEvent { position: local, kind: crate::event::PointerKind::Touch, ..Default::default() };
self.fire(target, "on_long_press", &EventArgs::Pointer(event));
if self.contains(target) && self.open_context_menu(target, position, true) {
self.mark_press_menu(root, target);
}
self.request_repaint();
}
any
}
}