use std::sync::{Arc, Weak};
use parking_lot::Mutex;
use super::Ctx;
use crate::{
app::window::WindowWaker,
time::{Duration, Instant},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Frame {
pub time: Instant,
pub delta: Duration,
}
impl Frame {
pub fn delta_secs(&self) -> f32 {
self.delta.as_secs_f32()
}
}
type FrameFn = Box<dyn FnMut(Frame) -> bool + Send>;
#[derive(Clone)]
pub struct FrameCallback {
inner: Arc<FrameEntry>,
}
struct FrameEntry {
state: Mutex<FrameState>,
callback: Mutex<FrameFn>,
wake: Option<WindowWaker>,
home: Option<Weak<Mutex<Vec<FrameCallback>>>>,
}
#[derive(Default)]
struct FrameState {
active: bool,
last: Option<Instant>,
}
impl FrameCallback {
fn with_home(callback: FrameFn, wake: Option<WindowWaker>, home: Option<Weak<Mutex<Vec<FrameCallback>>>>) -> Self {
Self {
inner: Arc::new(FrameEntry {
state: Mutex::new(FrameState {
active: true,
last: None,
}),
callback: Mutex::new(callback),
wake,
home,
}),
}
}
pub fn cancel(&self) {
self.inner.state.lock().active = false;
}
pub fn start(&self) {
{
let mut state = self.inner.state.lock();
if state.active {
return;
}
state.active = true;
state.last = None;
}
if let Some(home) = self.inner.home.as_ref().and_then(Weak::upgrade) {
let mut list = home.lock();
if !list.iter().any(|callback| callback.same(self)) {
list.push(self.clone());
}
}
if let Some(wake) = &self.inner.wake {
wake();
}
}
pub fn is_active(&self) -> bool {
self.inner.state.lock().active
}
fn same(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.inner, &other.inner)
}
fn replace(&self, callback: FrameFn) {
*self.inner.callback.lock() = callback;
}
fn run(&self, now: Instant) -> bool {
let delta = {
let mut state = self.inner.state.lock();
if !state.active {
return false;
}
let delta = state
.last
.map_or(Duration::ZERO, |last| now.saturating_duration_since(last));
state.last = Some(now);
delta
};
let more = (self.inner.callback.lock())(Frame { time: now, delta });
if !more {
self.inner.state.lock().active = false;
}
true
}
fn forget_last(&self) {
self.inner.state.lock().last = None;
}
}
#[derive(Clone, Default)]
pub(crate) struct WindowFrames {
list: Arc<Mutex<Vec<FrameCallback>>>,
}
impl WindowFrames {
pub(crate) fn add(&self, callback: FrameFn, wake: Option<WindowWaker>) -> FrameCallback {
let callback = FrameCallback::with_home(callback, wake, Some(Arc::downgrade(&self.list)));
self.list.lock().push(callback.clone());
callback
}
pub(crate) fn any_active(&self) -> bool {
self.list.lock().iter().any(FrameCallback::is_active)
}
pub(crate) fn run(&self, now: Instant) -> bool {
let callbacks: Vec<FrameCallback> = self.list.lock().clone();
let mut ran = false;
for callback in &callbacks {
ran |= callback.run(now);
}
self.list.lock().retain(FrameCallback::is_active);
ran
}
pub(crate) fn forget_last(&self) {
for callback in self.list.lock().iter() {
callback.forget_last();
}
}
}
#[derive(Default)]
pub(super) struct ComponentFrames {
stable: Vec<FrameCallback>,
slots: Vec<FrameCallback>,
cursor: usize,
}
impl ComponentFrames {
pub(super) fn begin_render(&mut self) {
self.cursor = 0;
}
pub(super) fn end_render(&mut self) {
self.slots.truncate(self.cursor);
}
fn iter(&self) -> impl Iterator<Item = &FrameCallback> {
self.stable.iter().chain(&self.slots)
}
pub(super) fn any_active(&self) -> bool {
self.iter().any(FrameCallback::is_active)
}
pub(super) fn run(&self, now: Instant) -> bool {
let mut ran = false;
for callback in self.iter() {
ran |= callback.run(now);
}
ran
}
pub(super) fn forget_last(&self) {
for callback in self.iter() {
callback.forget_last();
}
}
pub(super) fn capacity_bytes(&self) -> usize {
(self.stable.capacity() + self.slots.capacity()) * std::mem::size_of::<FrameCallback>()
}
}
impl Ctx {
pub fn on_frame(&mut self, callback: impl FnMut(Frame) -> bool + Send + 'static) -> FrameCallback {
let callback: FrameFn = Box::new(callback);
let wake = self.window.as_ref().map(crate::app::window::Window::loop_waker);
if !self.rendering {
let made = FrameCallback::with_home(callback, wake, None);
self.frames.stable.push(made.clone());
return made;
}
let cursor = self.frames.cursor;
self.frames.cursor += 1;
if let Some(slot) = self.frames.slots.get(cursor) {
slot.replace(callback);
return slot.clone();
}
let made = FrameCallback::with_home(callback, wake, None);
self.frames.slots.push(made.clone());
made
}
pub(crate) fn has_active_frame_callbacks(&self) -> bool {
self.frames.any_active()
|| self
.children
.iter()
.any(|slot| !slot.offstage && slot.ctx.has_active_frame_callbacks())
}
pub(crate) fn run_frame_callbacks(&self, now: Instant) -> bool {
let mut ran = self.frames.run(now);
for slot in &self.children {
if slot.offstage {
slot.ctx.forget_last_frames();
} else {
ran |= slot.ctx.run_frame_callbacks(now);
}
}
ran
}
pub(crate) fn forget_last_frames(&self) {
self.frames.forget_last();
for slot in &self.children {
slot.ctx.forget_last_frames();
}
}
}