use std::fmt;
use std::rc::Rc;
use mitsuami_reactive::{IntoValue, Value};
use crate::a11y::{A11yAction, A11yProps};
use crate::any_value::{AnyValue, Opaque};
use crate::backend::{MeasureRequest, PlatformMetrics};
use crate::command::{PointerEvent, UiEvent};
use crate::draw::{Canvas, DisplayList};
use crate::element::{Element, ElementBuilder};
use crate::geometry::Size;
use crate::ui::Ui;
use crate::view::{AnyView, View};
use crate::widget::{NodeId, Prop, WidgetKind};
pub trait CustomWidget: Sized + 'static {
const NAME: &'static str;
type Props: Clone + PartialEq + fmt::Debug + 'static;
type Event: Clone + PartialEq + fmt::Debug + 'static;
fn a11y(props: &Self::Props) -> A11yProps;
fn action(props: &Self::Props, action: &A11yAction) -> Option<Self::Event> {
let _ = (props, action);
None
}
}
pub trait Drawn: CustomWidget {
fn measure(props: &Self::Props, request: &MeasureRequest, metrics: &PlatformMetrics) -> Size;
fn draw(props: &Self::Props, canvas: &mut Canvas);
fn pointer(props: &Self::Props, size: Size, event: &PointerEvent) -> Option<Self::Event> {
let _ = (props, size, event);
None
}
}
pub trait Render: CustomWidget {
fn renderer() -> Renderer<Self>;
}
pub struct Renderer<W: CustomWidget> {
native: Option<Opaque>,
platform_control: bool,
drawn: Option<DrawnFns>,
composed: Option<ComposeFn<W>>,
}
type ComposeFn<W> = Rc<dyn Fn(Composed<W>) -> AnyView>;
pub struct Composed<W: CustomWidget> {
props: Rc<dyn Fn() -> W::Props>,
emit: Rc<dyn Fn(W::Event)>,
label: Option<String>,
}
impl<W: CustomWidget> Clone for Composed<W> {
fn clone(&self) -> Self {
Composed { props: self.props.clone(), emit: self.emit.clone(), label: self.label.clone() }
}
}
impl<W: CustomWidget> Composed<W> {
pub fn props(&self) -> W::Props {
(self.props)()
}
pub fn emit(&self, event: W::Event) {
(self.emit)(event)
}
pub fn label(&self) -> Option<String> {
self.label.clone()
}
}
impl<W: CustomWidget> Renderer<W> {
pub fn drawn() -> Renderer<W>
where
W: Drawn,
{
Renderer { native: None, platform_control: false, drawn: Some(DrawnFns::of::<W>()), composed: None }
}
pub fn native(render: Opaque) -> Renderer<W> {
Renderer { native: Some(render), platform_control: true, drawn: None, composed: None }
}
pub fn ad_hoc(render: Opaque) -> Renderer<W> {
Renderer { native: Some(render), platform_control: false, drawn: None, composed: None }
}
pub fn with_drawn(mut self) -> Renderer<W>
where
W: Drawn,
{
self.drawn = Some(DrawnFns::of::<W>());
self
}
pub fn composed<V: View>(compose: impl Fn(Composed<W>) -> V + 'static) -> Renderer<W> {
Renderer {
native: None,
platform_control: false,
drawn: None,
composed: Some(Rc::new(move |c| AnyView::new(compose(c)))),
}
}
pub fn with_composed<V: View>(mut self, compose: impl Fn(Composed<W>) -> V + 'static) -> Renderer<W> {
self.composed = Some(Rc::new(move |c| AnyView::new(compose(c))));
self
}
pub fn is_native(&self) -> bool {
self.native.is_some() && self.platform_control
}
}
#[derive(Clone, Copy)]
struct DrawnFns {
measure: fn(&AnyValue, &MeasureRequest, &PlatformMetrics) -> Size,
draw: fn(&AnyValue, &mut Canvas),
pointer: fn(&AnyValue, Size, &PointerEvent) -> Option<AnyValue>,
}
impl DrawnFns {
fn of<W: Drawn>() -> DrawnFns {
DrawnFns {
measure: |props, request, metrics| W::measure(props_of::<W>(props), request, metrics),
draw: |props, canvas| W::draw(props_of::<W>(props), canvas),
pointer: |props, size, event| W::pointer(props_of::<W>(props), size, event).map(AnyValue::new),
}
}
}
fn props_of<W: CustomWidget>(props: &AnyValue) -> &W::Props {
props.downcast_ref().unwrap_or_else(|| panic!("{}: props of another type: {props:?}", W::NAME))
}
struct Definition {
name: &'static str,
a11y: fn(&AnyValue) -> A11yProps,
action: fn(&AnyValue, &A11yAction) -> Option<AnyValue>,
native: Option<Opaque>,
drawn: Option<DrawnFns>,
force_drawn: bool,
}
#[derive(Clone)]
pub struct CustomProps {
props: AnyValue,
definition: Rc<Definition>,
}
impl CustomProps {
pub fn name(&self) -> &'static str {
self.definition.name
}
pub fn props(&self) -> &AnyValue {
&self.props
}
pub fn get<T: 'static>(&self) -> Option<&T> {
self.props.downcast_ref()
}
pub fn with_props(&self, props: AnyValue) -> CustomProps {
CustomProps { props, definition: self.definition.clone() }
}
pub fn is_drawn(&self) -> bool {
self.definition.drawn.is_some() && (self.definition.force_drawn || self.definition.native.is_none())
}
pub fn native(&self) -> Option<&Opaque> {
if self.is_drawn() { None } else { self.definition.native.as_ref() }
}
pub fn a11y(&self) -> A11yProps {
(self.definition.a11y)(&self.props)
}
pub fn action(&self, action: &A11yAction) -> Option<AnyValue> {
(self.definition.action)(&self.props, action)
}
pub fn measure_drawn(&self, request: &MeasureRequest, metrics: &PlatformMetrics) -> Option<Size> {
self.definition.drawn.map(|d| (d.measure)(&self.props, request, metrics))
}
pub fn draw(&self, size: Size, metrics: &PlatformMetrics) -> Option<DisplayList> {
let drawn = self.definition.drawn?;
let mut canvas = Canvas::new(size, metrics);
(drawn.draw)(&self.props, &mut canvas);
Some(canvas.finish())
}
pub fn pointer(&self, size: Size, event: &PointerEvent) -> Option<AnyValue> {
self.definition.drawn.and_then(|d| (d.pointer)(&self.props, size, event))
}
}
impl PartialEq for CustomProps {
fn eq(&self, other: &CustomProps) -> bool {
self.props == other.props && self.name() == other.name() && self.is_drawn() == other.is_drawn()
}
}
impl fmt::Debug for CustomProps {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self.props)?;
if self.is_drawn() {
f.write_str(" (drawn)")?;
}
Ok(())
}
}
pub struct Custom<W: CustomWidget, P = Value<<W as CustomWidget>::Props>> {
element: Element,
props: P,
renderer: Renderer<W>,
force_drawn: bool,
force_composed: bool,
}
impl<W: Render> Custom<W> {
pub fn new(props: impl IntoValue<W::Props>) -> Custom<W> {
Custom {
element: Element::new(WidgetKind::Custom(W::NAME)),
props: props.into_value(),
renderer: W::renderer(),
force_drawn: false,
force_composed: false,
}
}
}
impl<W: CustomWidget, P> Custom<W, P> {
pub fn props(self, props: impl IntoValue<W::Props>) -> Custom<W> {
let Custom { element, props: _, renderer, force_drawn, force_composed } = self;
Custom { element, props: props.into_value(), renderer, force_drawn, force_composed }
}
pub fn drawn(mut self) -> Custom<W, P>
where
W: Drawn,
{
self.renderer.drawn = Some(DrawnFns::of::<W>());
self.force_drawn = true;
self
}
pub fn composed(mut self) -> Custom<W, P> {
self.force_composed = true;
self
}
pub fn on_event(mut self, handler: impl Fn(&W::Event) + 'static) -> Custom<W, P> {
self.element.on(move |event| {
if let UiEvent::Custom(value) = event
&& let Some(event) = value.downcast_ref::<W::Event>()
{
handler(event);
}
});
self
}
}
impl<W: CustomWidget, P> ElementBuilder for Custom<W, P> {
fn element(&mut self) -> &mut Element {
&mut self.element
}
}
impl<W: CustomWidget> View for Custom<W> {
fn build(self, ui: &Ui) -> NodeId {
let Custom { mut element, props, renderer, force_drawn, force_composed } = self;
let composed = force_composed || (!force_drawn && renderer.native.is_none() && renderer.drawn.is_none());
if composed {
let compose = renderer.composed.unwrap_or_else(|| panic!("{}: no composed render", W::NAME));
return build_composed(ui, element, props, compose);
}
let definition = Rc::new(Definition {
name: W::NAME,
a11y: |props| W::a11y(props_of::<W>(props)),
action: |props, action| W::action(props_of::<W>(props), action).map(AnyValue::new),
native: renderer.native,
drawn: renderer.drawn,
force_drawn,
});
element.prop(props, move |props| {
Prop::Custom(CustomProps { props: AnyValue::new(props), definition: definition.clone() })
});
element.build(ui)
}
}
fn build_composed<W: CustomWidget>(
ui: &Ui,
mut element: Element,
props: Value<W::Props>,
compose: ComposeFn<W>,
) -> NodeId {
element.kind = WidgetKind::Container;
let label = element.a11y.label.take();
let props: Rc<dyn Fn() -> W::Props> = match props {
Value::Static(props) => Rc::new(move || props.clone()),
Value::Dynamic(props) => props,
};
let node: Rc<std::cell::Cell<Option<NodeId>>> = Rc::default();
let (target, weak) = (node.clone(), ui.downgrade());
let emit = Rc::new(move |event: W::Event| {
if let (Some(id), Some(ui)) = (target.get(), weak.upgrade()) {
ui.events().emit(id, UiEvent::Custom(AnyValue::new(event)));
}
});
element.add_children(compose(Composed { props, emit, label }));
let id = element.build(ui);
node.set(Some(id));
id
}
pub trait CustomView: Render {
fn view(props: impl IntoValue<Self::Props>) -> Custom<Self> {
Custom::new(props)
}
#[doc(hidden)]
fn __tag() -> Custom<Self, ()> {
Custom {
element: Element::new(WidgetKind::Custom(Self::NAME)),
props: (),
renderer: Self::renderer(),
force_drawn: false,
force_composed: false,
}
}
}
impl<W: Render> CustomView for W {}