use crate::{Element, FrameSource, Handler, Kind, Node, Point, Prop, Rect, Widget};
use serge_style::StyleProp;
use std::{
any::Any,
cell::{Cell, RefCell},
collections::HashMap,
rc::{Rc, Weak},
sync::atomic::{AtomicU64, Ordering},
};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Extent {
pub width: u32,
pub height: u32,
}
impl Extent {
pub const MAX_BYTES: u64 = 256 * 1024 * 1024;
pub fn pixels(rect: Rect, scale: f32) -> Self {
Self {
width: (rect.width * scale).round() as u32,
height: (rect.height * scale).round() as u32,
}
}
pub fn byte_len(self) -> Option<usize> {
let bytes = u64::from(self.width)
.checked_mul(u64::from(self.height))?
.checked_mul(4)?;
(bytes > 0 && bytes <= Self::MAX_BYTES).then_some(bytes as usize)
}
}
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Pointer {
Down(Point),
Move(Point),
Up(Point),
Cancel,
}
type Cpu = Rc<dyn Fn(Extent) -> Option<Vec<u8>>>;
#[derive(Clone)]
pub struct Viewport {
label: String,
cpu: Option<Cpu>,
backend: Option<Rc<dyn Any>>,
input: Option<Rc<dyn Fn(Pointer)>>,
source: FrameSource,
fallback: serge_style::Color,
}
impl Viewport {
pub fn new(label: impl Into<String>) -> Self {
Self {
label: label.into(),
cpu: None,
backend: None,
input: None,
source: Default::default(),
fallback: serge_style::Color::rgba(64, 64, 64, 255),
}
}
pub fn cpu(mut self, draw: impl Fn(Extent) -> Option<Vec<u8>> + 'static) -> Self {
self.cpu = Some(Rc::new(draw));
self
}
pub fn backend<T: 'static>(mut self, backend: T) -> Self {
self.backend = Some(Rc::new(backend));
self
}
pub fn fallback(mut self, color: serge_style::Color) -> Self {
self.fallback = color;
self
}
pub fn input(mut self, f: impl Fn(Pointer) + 'static) -> Self {
self.input = Some(Rc::new(f));
self
}
pub fn source(&self) -> FrameSource {
self.source.clone()
}
pub fn label(&self) -> &str {
&self.label
}
pub fn element(&self, style: impl IntoIterator<Item = StyleProp>) -> Element {
let mut w = Widget::new(Kind::Canvas);
w.style.extend(style.into_iter().map(Prop::Static));
w.handlers.push(Handler::Viewport(self.clone()));
Element(Node::Widget(Box::new(w)))
}
pub fn mount(&self) -> Slot {
static NEXT: AtomicU64 = AtomicU64::new(1);
let id = NEXT.fetch_add(1, Ordering::Relaxed);
let inner = Rc::new(Instance {
id,
producer: self.clone(),
extent: Cell::default(),
generation: Cell::new(0),
seen: Cell::new(0),
available: Cell::new(None),
});
SLOTS.with(|slots| slots.borrow_mut().insert(id, Rc::downgrade(&inner)));
Slot(inner)
}
}
thread_local! { static SLOTS:RefCell<HashMap<u64,Weak<Instance>>>=RefCell::default(); }
struct Instance {
id: u64,
producer: Viewport,
extent: Cell<Extent>,
generation: Cell<u64>,
seen: Cell<u64>,
available: Cell<Option<bool>>,
}
impl Drop for Instance {
fn drop(&mut self) {
let _ = SLOTS.try_with(|s| s.borrow_mut().remove(&self.id));
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct TextureKey {
id: u64,
generation: u64,
}
#[derive(Clone)]
pub struct Slot(Rc<Instance>);
impl Slot {
pub fn frame(&self, size: Extent) -> TextureKey {
if self.0.extent.replace(size) != size {
self.invalidate();
}
self.0.seen.set(self.0.producer.source.version());
TextureKey {
id: self.0.id,
generation: self.0.generation.get(),
}
}
pub fn invalidate(&self) {
self.0
.generation
.set(self.0.generation.get().wrapping_add(1));
}
pub fn resolve(key: TextureKey) -> Option<Self> {
let instance = SLOTS.with(|slots| slots.borrow().get(&key.id).and_then(Weak::upgrade))?;
(instance.generation.get() == key.generation).then_some(Self(instance))
}
pub fn dirty(&self) -> bool {
self.0.seen.get() != self.0.producer.source.version()
}
pub fn presented(&self, available: bool) {
if self.0.available.replace(Some(available)) != Some(available) {
self.0.producer.source.bump();
}
}
pub fn unavailable(&self) -> bool {
self.0.available.get() == Some(false)
}
pub fn fallback(&self) -> serge_style::Color {
self.0.producer.fallback
}
pub fn extent(&self) -> Extent {
self.0.extent.get()
}
pub fn rgba(&self) -> Option<Vec<u8>> {
let size = self.extent();
let len = size.byte_len()?;
self.0.producer.cpu.as_ref()?(size).filter(|buf| buf.len() == len)
}
pub fn backend<T: 'static>(&self) -> Option<&T> {
self.0.producer.backend.as_ref()?.downcast_ref()
}
pub fn label(&self) -> &str {
self.0.producer.label()
}
pub fn pointer(&self, p: Pointer) {
if let Some(f) = &self.0.producer.input {
f(p);
}
}
}