use std::cell::Cell;
use std::rc::Rc;
use std::sync::atomic::{AtomicI64, Ordering};
use std::time::Duration;
use waft_embedder::{AppLifecycleState, Offset, ViewId};
use waft_foundation::{App, AsyncApp, Completer, CompleterFuture, Listener, Timer, delayed};
use waft_gestures::{
GestureBinding, HitTestResult, K_LONG_PRESS_TIMEOUT, K_PRESS_TIMEOUT, PointerDownEvent,
PointerEvent, PointerMoveEvent, PointerUpEvent,
};
use waft_rendering::{
AnyRenderBox, AnyRenderObject, BoxHitTestEntry, RenderView, SliverHitTestEntry,
};
use waft_scheduler::{FrameCallback, SchedulerBinding};
use crate::AnyElement;
pub(super) const WAIT_LIMIT: Duration = Duration::from_secs(5);
const FRAME: Duration = Duration::from_millis(16);
pub(super) async fn wait_until(
cx: &mut AsyncApp,
limit: Duration,
holds: impl Fn(&mut App) -> bool,
) -> bool {
let deadline = cx.update(|app| app.clock()) + limit;
loop {
if cx.update(&holds) {
return true;
}
let now = cx.update(|app| app.clock());
if now >= deadline {
return false;
}
cx.update(|app| next_frame_or_after(app, deadline - now))
.await;
}
}
fn next_frame_or_after(app: &mut App, timeout: Duration) -> CompleterFuture<()> {
let completer: Completer<()> = Completer::new();
let future = completer.future();
let timer: Rc<Cell<Option<Timer>>> = Rc::default();
let finish = {
let timer = Rc::clone(&timer);
Rc::new(move |app: &mut App| {
if completer.is_completed() {
return;
}
if let Some(timer) = timer.take() {
timer.cancel(app);
}
completer.complete(app, ());
})
};
let after_frame = Rc::clone(&finish);
SchedulerBinding::add_post_frame_callback(
app,
FrameCallback::new(move |app, _| after_frame(app)),
None,
);
timer.set(Some(Timer::new(
app,
timeout,
Listener::new(move |app| finish(app)),
)));
future
}
pub(super) async fn settle(cx: &mut AsyncApp) -> bool {
wait_until(cx, WAIT_LIMIT, |app| {
!SchedulerBinding::has_scheduled_frame(app)
&& SchedulerBinding::transient_callback_count(app) == 0
})
.await
}
pub(super) fn why_no_frames(app: &mut App) -> Option<&'static str> {
matches!(
SchedulerBinding::lifecycle_state(app),
Some(AppLifecycleState::Hidden | AppLifecycleState::Paused)
)
.then_some("its windows are out of sight, where it draws no frames")
}
pub(super) fn center_of(app: &App, element: AnyElement) -> Option<(Offset, ViewId)> {
let render = element.find_render_object(app)?.as_box()?;
let center = render.size(app).center(Offset::ZERO);
let at = render.local_to_global(app, center, None);
Some((at, view_of(app, render)?))
}
fn view_of(app: &App, render: AnyRenderBox) -> Option<ViewId> {
std::iter::successors(Some(render.as_object()), |node| node.parent(app)).find_map(|node| {
node.downcast::<RenderView>(app)
.map(|view| view.flutter_view(app).id())
})
}
pub(super) fn hit_at(app: &mut App, at: Offset, view: ViewId) -> Vec<AnyRenderObject> {
let mut result = HitTestResult::new();
GestureBinding::instance(app).hit_test_in_view(app, &mut result, at, view);
result
.path()
.iter()
.filter_map(|entry| {
let target: &dyn std::any::Any = entry.target();
target
.downcast_ref::<BoxHitTestEntry>()
.map(|entry| entry.target().as_object())
.or_else(|| {
target
.downcast_ref::<SliverHitTestEntry>()
.map(|entry| entry.target().as_object())
})
})
.collect()
}
static NEXT_POINTER: AtomicI64 = AtomicI64::new(1 << 20);
struct Touch {
pointer: i64,
view: ViewId,
at: Offset,
}
impl Touch {
fn down(app: &mut App, at: Offset, view: ViewId) -> Touch {
let touch = Touch {
pointer: NEXT_POINTER.fetch_add(1, Ordering::Relaxed),
view,
at,
};
let down = PointerDownEvent {
view_id: view,
pointer: touch.pointer,
position: at,
time_stamp: app.clock(),
..PointerDownEvent::default()
};
dispatch(app, PointerEvent::Down(down));
touch
}
fn move_to(&mut self, app: &mut App, at: Offset) {
let moved = PointerMoveEvent {
view_id: self.view,
pointer: self.pointer,
position: at,
delta: at - self.at,
time_stamp: app.clock(),
..PointerMoveEvent::default()
};
self.at = at;
dispatch(app, PointerEvent::Move(moved));
}
fn up(self, app: &mut App) {
let up = PointerUpEvent {
view_id: self.view,
pointer: self.pointer,
position: self.at,
time_stamp: app.clock(),
..PointerUpEvent::default()
};
dispatch(app, PointerEvent::Up(up));
}
}
fn dispatch(app: &mut App, event: PointerEvent) {
GestureBinding::instance(app).handle_pointer_event(app, event);
}
pub(super) fn tap_at(app: &mut App, at: Offset, view: ViewId) {
Touch::down(app, at, view).up(app);
}
pub(super) async fn long_press_at(cx: &mut AsyncApp, at: Offset, view: ViewId) {
let touch = cx.update(|app| Touch::down(app, at, view));
pause(cx, K_LONG_PRESS_TIMEOUT + K_PRESS_TIMEOUT).await;
cx.update(|app| touch.up(app));
}
pub(super) async fn drag(
cx: &mut AsyncApp,
from: Offset,
view: ViewId,
by: Offset,
duration: Duration,
) {
let steps = (duration.as_millis() / FRAME.as_millis()).max(1);
let mut touch = cx.update(|app| Touch::down(app, from, view));
for step in 1..=steps {
pause(cx, FRAME).await;
let at = from + by * (step as f64 / steps as f64);
cx.update(|app| touch.move_to(app, at));
}
cx.update(|app| touch.up(app));
}
async fn pause(cx: &mut AsyncApp, duration: Duration) {
cx.update(|app| delayed(app, duration)).await;
}