use std::any::Any;
use std::borrow::Cow;
use std::marker::PhantomData;
use std::rc::Rc;
use web_time::Instant;
use taffy::{AvailableSpace, Size, Style};
use crate::path::{Path, Quad, Shape};
use crate::render::{Bitmap, Color, Rect, Scene, Shadow};
use crate::runtime::task::Tasks;
use crate::text::{Font, Text, TextLayout};
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum Event {
PointerDown {
x: f32,
y: f32,
},
PointerMove {
x: f32,
y: f32,
},
PointerUp {
x: f32,
y: f32,
},
Wheel {
x: f32,
y: f32,
dy: f32,
},
Cancel,
Leave,
Text(String),
Key(Key),
Back,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Keyboard {
#[default]
Text,
Number,
Email,
Password,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Key {
Backspace,
Delete,
DeleteBefore(usize),
Left,
Right,
Home,
End,
SelectAll,
Copy,
Cut,
}
pub struct Element {
pub(crate) widget: Box<dyn Widget>,
pub(crate) key: Option<u64>,
}
impl Element {
pub fn new(w: impl Widget + 'static) -> Self {
Element {
widget: Box::new(w),
key: None,
}
}
pub fn key(mut self, key: u64) -> Self {
self.key = Some(key);
self
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Placement {
pub clip: Rect,
pub rest: Rect,
pub anchor: Rect,
pub content: Size<f32>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Layer {
Parent,
Window,
}
pub trait Widget {
fn style(&self) -> Style {
Style::default()
}
fn children(&self) -> &[Element] {
&[]
}
fn expand(&self, _cx: &mut BuildCx) {}
fn layer(&self) -> Option<Layer> {
None
}
fn inert(&self) -> bool {
false
}
fn provide(&self) -> Option<&dyn Any> {
None
}
fn measure(
&self,
_known: Size<Option<f32>>,
_available: Size<AvailableSpace>,
_text: &Text,
) -> Size<f32> {
Size::ZERO
}
fn measure_key(&self) -> u64 {
0
}
fn scroll(&self, _state: &mut State, _at: Placement, _now: Instant) -> Option<(f32, f32)> {
None
}
fn clips(&self) -> bool {
true
}
fn paint(&self, _cx: &mut PaintCx) {}
fn event(&self, _ev: &Event, _cx: &mut EventCx) {}
}
#[derive(Default)]
pub struct State(Option<Box<dyn Any>>);
impl State {
pub fn get<T: Default + 'static>(&mut self) -> &mut T {
self.get_or_insert_with(T::default)
}
pub(crate) fn get_or_insert_with<T: 'static>(&mut self, init: impl FnOnce() -> T) -> &mut T {
if !self.0.as_ref().is_some_and(|b| b.is::<T>()) {
self.0 = Some(Box::new(init()));
}
self.0.as_mut().unwrap().downcast_mut().unwrap()
}
}
pub struct Handle<S> {
pub(crate) id: u64,
_s: PhantomData<fn() -> S>,
}
impl<S> Handle<S> {
pub(crate) fn new(id: u64) -> Self {
Handle {
id,
_s: PhantomData,
}
}
}
impl<S> Clone for Handle<S> {
fn clone(&self) -> Self {
*self
}
}
impl<S> Copy for Handle<S> {}
pub(crate) type Update = (u64, Box<dyn FnOnce(&mut State)>);
#[derive(Clone, Copy)]
pub struct Scope<'a>(pub(crate) &'a [&'a dyn Any]);
impl<'a> Scope<'a> {
pub fn get<T: 'static>(&self) -> Option<&'a T> {
self.0.iter().rev().find_map(|v| v.downcast_ref())
}
}
pub struct BuildCx<'a> {
pub id: u64,
pub state: &'a mut State,
pub scope: Scope<'a>,
pub(crate) tasks: &'a mut Tasks,
}
pub struct PaintCx<'a> {
pub now: Instant,
pub rect: Rect,
pub clip: Rect,
pub focused: bool,
pub theme: &'a crate::Theme,
pub state: &'a mut State,
pub(crate) scene: &'a mut Scene,
pub(crate) text: &'a mut Text,
pub(crate) frame: &'a mut bool,
pub(crate) wake: &'a mut Option<Instant>,
pub(crate) place: &'a mut bool,
pub(crate) rebuild: &'a mut bool,
}
impl PaintCx<'_> {
pub fn color(&self, ink: impl Into<crate::Ink>) -> Color {
match ink.into() {
crate::Ink::Fixed(c) => c,
crate::Ink::Role(r) => self.theme.color(r),
crate::Ink::Content => self.theme.ink,
}
}
pub fn request_rebuild(&mut self) {
*self.frame = true;
*self.rebuild = true;
}
pub fn request_frame(&mut self) {
*self.frame = true;
}
pub fn request_placement(&mut self) {
*self.frame = true;
*self.place = true;
}
pub fn request_frame_at(&mut self, t: Instant) {
*self.wake = Some(self.wake.map_or(t, |w| w.min(t)));
}
pub fn path(&mut self, path: &Path, color: Color) {
self.fill_path(path, None, color);
}
pub fn path_masked(&mut self, path: &Path, mask: &Path, color: Color) {
self.fill_path(path, Some(mask), color);
}
fn fill_path(&mut self, path: &Path, mask: Option<&Path>, color: Color) {
let quads = || path.contours.iter().flatten();
let mask_quads = || mask.into_iter().flat_map(|m| m.contours.iter().flatten());
let (mut lo, mut hi) = ([f32::MAX; 2], [f32::MIN; 2]);
for p in quads().chain(mask_quads()).flatten() {
lo = [lo[0].min(p[0]), lo[1].min(p[1])];
hi = [hi[0].max(p[0]), hi[1].max(p[1])];
}
let span = (hi[0] - lo[0]).max(hi[1] - lo[1]);
if !span.is_finite() || span <= 0.0 || mask.is_some_and(|m| m.contours.is_empty()) {
return;
}
let s = 1.0 / span;
let unit = |q: &Quad| q.map(|[x, y]| [(x - lo[0]) * s, (hi[1] - y) * s]);
let far = [(hi[0] - lo[0]) * s, (hi[1] - lo[1]) * s];
let (p0, p1, p2, p3) = ([0.0; 2], [1e-4, 0.0], far, [far[0] - 1e-4, far[1]]);
let rim = [[p0, p0, p1], [p1, p1, p0], [p2, p2, p3], [p3, p3, p2]];
let corners = mask.map(|_| rim).into_iter().flatten();
let body = quads().map(unit).chain(corners).collect();
let Some(g) = self.text.outlines.transient(body, s) else {
return;
};
let cover = mask.and_then(|_| {
let edge = mask_quads().map(unit).chain(rim);
self.text.outlines.transient(edge.collect(), s)
});
let [x0, y0, x1, y1] = g.bbox;
let r = Rect::new(lo[0] + x0 / s, hi[1] - y1 / s, (x1 - x0) / s, (y1 - y0) / s);
let bands = [g.header as f32, g.bands_h as f32, g.bands_v as f32];
let cover = cover.map(|c| [c.header as f32, c.bands_h as f32, c.bands_v as f32]);
self.scene
.glyph(r, [x0, y1, x1, y0], color, self.clip, bands, cover);
}
pub fn shape(&mut self, shape: &Shape, r: Rect, color: Color) {
self.text.draw_shape(shape, r, color, self.clip, self.scene);
}
pub fn glyph_path(&self, font: Font, c: char, size: f32) -> Option<Path> {
self.text.glyph_path(font, c, size)
}
pub fn fill(&mut self, r: Rect, radius: f32, color: Color) {
self.scene
.shape(r, radius, color, 0.0, Color::TRANSPARENT, self.clip);
}
pub fn fill_bordered(
&mut self,
r: Rect,
radius: f32,
color: Color,
border: f32,
border_color: Color,
) {
self.scene
.shape(r, radius, color, border, border_color, self.clip);
}
pub fn shadow(&mut self, r: Rect, radius: f32, s: Shadow) {
self.scene.shadow(r, radius, s, self.clip);
}
pub fn image(&mut self, r: Rect, bitmap: &Bitmap, radius: f32, tint: Color) {
self.scene.image(r, bitmap, radius, tint, self.clip);
}
pub fn with_clip<R>(&mut self, r: Rect, f: impl FnOnce(&mut Self) -> R) -> R {
let saved = self.clip;
self.clip = saved.intersect(&r);
let out = f(self);
self.clip = saved;
out
}
pub fn truncate<'s>(
&self,
s: &'s str,
font: Font,
size: f32,
max_width: f32,
max_lines: usize,
) -> Cow<'s, str> {
self.text.truncate(s, font, size, max_width, max_lines)
}
pub fn measure(
&self,
s: &str,
font: Font,
size: f32,
max_width: Option<f32>,
) -> Rc<TextLayout> {
self.text.layout(s, font, size, max_width)
}
pub fn text(
&mut self,
s: &str,
font: Font,
size: f32,
color: Color,
max_width: Option<f32>,
origin: (f32, f32),
) {
self.text.draw(
s, font, size, max_width, origin, color, self.clip, self.scene,
);
}
}
pub struct EventCx<'a> {
pub now: Instant,
pub rect: Rect,
pub clip: Rect,
pub content: Size<f32>,
pub focused: bool,
pub shift: bool,
pub state: &'a mut State,
pub(crate) text: &'a Text,
pub(crate) updates: &'a mut Vec<Update>,
pub(crate) copied: &'a mut Option<String>,
pub(crate) capture: bool,
pub(crate) focus: Option<Keyboard>,
pub(crate) stop: bool,
pub(crate) redraw: bool,
}
impl EventCx<'_> {
pub fn hit(&self, x: f32, y: f32) -> bool {
self.rect.contains(x, y) && self.clip.contains(x, y)
}
pub fn update<S: 'static>(&mut self, h: Handle<S>, f: impl FnOnce(&mut S) + 'static) {
let apply = move |st: &mut State| {
if let Some(s) = st.0.as_mut().and_then(|b| b.downcast_mut()) {
f(s);
}
};
self.updates.push((h.id, Box::new(apply)));
}
pub fn capture(&mut self) {
self.capture = true;
}
pub fn copy(&mut self, text: impl Into<String>) {
*self.copied = Some(text.into());
}
pub fn focus(&mut self, keyboard: Keyboard) {
self.focus = Some(keyboard);
}
pub fn stop(&mut self) {
self.stop = true;
}
pub fn request_redraw(&mut self) {
self.redraw = true;
}
}