1use std::fmt;
20use std::rc::Rc;
21
22use mitsuami_reactive::{IntoValue, Value};
23
24use crate::a11y::{A11yAction, A11yProps};
25use crate::any_value::{AnyValue, Opaque};
26use crate::backend::{MeasureRequest, PlatformMetrics};
27use crate::command::{PointerEvent, UiEvent};
28use crate::draw::{Canvas, DisplayList};
29use crate::element::{Element, ElementBuilder};
30use crate::geometry::Size;
31use crate::ui::Ui;
32use crate::view::{AnyView, View};
33use crate::widget::{NodeId, Prop, WidgetKind};
34
35pub trait CustomWidget: Sized + 'static {
37 const NAME: &'static str;
39 type Props: Clone + PartialEq + fmt::Debug + 'static;
40 type Event: Clone + PartialEq + fmt::Debug + 'static;
41
42 fn a11y(props: &Self::Props) -> A11yProps;
45
46 fn action(props: &Self::Props, action: &A11yAction) -> Option<Self::Event> {
49 let _ = (props, action);
50 None
51 }
52}
53
54pub trait Drawn: CustomWidget {
56 fn measure(props: &Self::Props, request: &MeasureRequest, metrics: &PlatformMetrics) -> Size;
58
59 fn draw(props: &Self::Props, canvas: &mut Canvas);
62
63 fn pointer(props: &Self::Props, size: Size, event: &PointerEvent) -> Option<Self::Event> {
65 let _ = (props, size, event);
66 None
67 }
68}
69
70pub trait Render: CustomWidget {
84 fn renderer() -> Renderer<Self>;
85}
86
87pub struct Renderer<W: CustomWidget> {
91 native: Option<Opaque>,
92 platform_control: bool,
94 drawn: Option<DrawnFns>,
95 composed: Option<ComposeFn<W>>,
96}
97
98type ComposeFn<W> = Rc<dyn Fn(Composed<W>) -> AnyView>;
101
102pub struct Composed<W: CustomWidget> {
105 props: Rc<dyn Fn() -> W::Props>,
106 emit: Rc<dyn Fn(W::Event)>,
107 label: Option<String>,
108}
109
110impl<W: CustomWidget> Clone for Composed<W> {
111 fn clone(&self) -> Self {
112 Composed { props: self.props.clone(), emit: self.emit.clone(), label: self.label.clone() }
113 }
114}
115
116impl<W: CustomWidget> Composed<W> {
117 pub fn props(&self) -> W::Props {
119 (self.props)()
120 }
121
122 pub fn emit(&self, event: W::Event) {
125 (self.emit)(event)
126 }
127
128 pub fn label(&self) -> Option<String> {
131 self.label.clone()
132 }
133}
134
135impl<W: CustomWidget> Renderer<W> {
136 pub fn drawn() -> Renderer<W>
138 where
139 W: Drawn,
140 {
141 Renderer { native: None, platform_control: false, drawn: Some(DrawnFns::of::<W>()), composed: None }
142 }
143
144 pub fn native(render: Opaque) -> Renderer<W> {
148 Renderer { native: Some(render), platform_control: true, drawn: None, composed: None }
149 }
150
151 pub fn ad_hoc(render: Opaque) -> Renderer<W> {
155 Renderer { native: Some(render), platform_control: false, drawn: None, composed: None }
156 }
157
158 pub fn with_drawn(mut self) -> Renderer<W>
161 where
162 W: Drawn,
163 {
164 self.drawn = Some(DrawnFns::of::<W>());
165 self
166 }
167
168 pub fn composed<V: View>(compose: impl Fn(Composed<W>) -> V + 'static) -> Renderer<W> {
171 Renderer {
172 native: None,
173 platform_control: false,
174 drawn: None,
175 composed: Some(Rc::new(move |c| AnyView::new(compose(c)))),
176 }
177 }
178
179 pub fn with_composed<V: View>(mut self, compose: impl Fn(Composed<W>) -> V + 'static) -> Renderer<W> {
181 self.composed = Some(Rc::new(move |c| AnyView::new(compose(c))));
182 self
183 }
184
185 pub fn is_native(&self) -> bool {
188 self.native.is_some() && self.platform_control
189 }
190}
191
192#[derive(Clone, Copy)]
194struct DrawnFns {
195 measure: fn(&AnyValue, &MeasureRequest, &PlatformMetrics) -> Size,
196 draw: fn(&AnyValue, &mut Canvas),
197 pointer: fn(&AnyValue, Size, &PointerEvent) -> Option<AnyValue>,
198}
199
200impl DrawnFns {
201 fn of<W: Drawn>() -> DrawnFns {
202 DrawnFns {
203 measure: |props, request, metrics| W::measure(props_of::<W>(props), request, metrics),
204 draw: |props, canvas| W::draw(props_of::<W>(props), canvas),
205 pointer: |props, size, event| W::pointer(props_of::<W>(props), size, event).map(AnyValue::new),
206 }
207 }
208}
209
210fn props_of<W: CustomWidget>(props: &AnyValue) -> &W::Props {
211 props.downcast_ref().unwrap_or_else(|| panic!("{}: props of another type: {props:?}", W::NAME))
212}
213
214struct Definition {
216 name: &'static str,
217 a11y: fn(&AnyValue) -> A11yProps,
218 action: fn(&AnyValue, &A11yAction) -> Option<AnyValue>,
219 native: Option<Opaque>,
220 drawn: Option<DrawnFns>,
221 force_drawn: bool,
223}
224
225#[derive(Clone)]
228pub struct CustomProps {
229 props: AnyValue,
230 definition: Rc<Definition>,
231}
232
233impl CustomProps {
234 pub fn name(&self) -> &'static str {
235 self.definition.name
236 }
237
238 pub fn props(&self) -> &AnyValue {
239 &self.props
240 }
241
242 pub fn get<T: 'static>(&self) -> Option<&T> {
243 self.props.downcast_ref()
244 }
245
246 pub fn with_props(&self, props: AnyValue) -> CustomProps {
248 CustomProps { props, definition: self.definition.clone() }
249 }
250
251 pub fn is_drawn(&self) -> bool {
254 self.definition.drawn.is_some() && (self.definition.force_drawn || self.definition.native.is_none())
255 }
256
257 pub fn native(&self) -> Option<&Opaque> {
259 if self.is_drawn() { None } else { self.definition.native.as_ref() }
260 }
261
262 pub fn a11y(&self) -> A11yProps {
263 (self.definition.a11y)(&self.props)
264 }
265
266 pub fn action(&self, action: &A11yAction) -> Option<AnyValue> {
268 (self.definition.action)(&self.props, action)
269 }
270
271 pub fn measure_drawn(&self, request: &MeasureRequest, metrics: &PlatformMetrics) -> Option<Size> {
273 self.definition.drawn.map(|d| (d.measure)(&self.props, request, metrics))
274 }
275
276 pub fn draw(&self, size: Size, metrics: &PlatformMetrics) -> Option<DisplayList> {
277 let drawn = self.definition.drawn?;
278 let mut canvas = Canvas::new(size, metrics);
279 (drawn.draw)(&self.props, &mut canvas);
280 Some(canvas.finish())
281 }
282
283 pub fn pointer(&self, size: Size, event: &PointerEvent) -> Option<AnyValue> {
284 self.definition.drawn.and_then(|d| (d.pointer)(&self.props, size, event))
285 }
286}
287
288impl PartialEq for CustomProps {
289 fn eq(&self, other: &CustomProps) -> bool {
290 self.props == other.props && self.name() == other.name() && self.is_drawn() == other.is_drawn()
291 }
292}
293
294impl fmt::Debug for CustomProps {
295 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
296 write!(f, "{:?}", self.props)?;
297 if self.is_drawn() {
298 f.write_str(" (drawn)")?;
299 }
300 Ok(())
301 }
302}
303
304pub struct Custom<W: CustomWidget, P = Value<<W as CustomWidget>::Props>> {
311 element: Element,
312 props: P,
313 renderer: Renderer<W>,
314 force_drawn: bool,
315 force_composed: bool,
316}
317
318impl<W: Render> Custom<W> {
319 pub fn new(props: impl IntoValue<W::Props>) -> Custom<W> {
321 Custom {
322 element: Element::new(WidgetKind::Custom(W::NAME)),
323 props: props.into_value(),
324 renderer: W::renderer(),
325 force_drawn: false,
326 force_composed: false,
327 }
328 }
329}
330
331impl<W: CustomWidget, P> Custom<W, P> {
332 pub fn props(self, props: impl IntoValue<W::Props>) -> Custom<W> {
334 let Custom { element, props: _, renderer, force_drawn, force_composed } = self;
335 Custom { element, props: props.into_value(), renderer, force_drawn, force_composed }
336 }
337
338 pub fn drawn(mut self) -> Custom<W, P>
340 where
341 W: Drawn,
342 {
343 self.renderer.drawn = Some(DrawnFns::of::<W>());
344 self.force_drawn = true;
345 self
346 }
347
348 pub fn composed(mut self) -> Custom<W, P> {
351 self.force_composed = true;
352 self
353 }
354
355 pub fn on_event(mut self, handler: impl Fn(&W::Event) + 'static) -> Custom<W, P> {
357 self.element.on(move |event| {
358 if let UiEvent::Custom(value) = event
359 && let Some(event) = value.downcast_ref::<W::Event>()
360 {
361 handler(event);
362 }
363 });
364 self
365 }
366}
367
368impl<W: CustomWidget, P> ElementBuilder for Custom<W, P> {
369 fn element(&mut self) -> &mut Element {
370 &mut self.element
371 }
372}
373
374impl<W: CustomWidget> View for Custom<W> {
375 fn build(self, ui: &Ui) -> NodeId {
376 let Custom { mut element, props, renderer, force_drawn, force_composed } = self;
377 let composed = force_composed || (!force_drawn && renderer.native.is_none() && renderer.drawn.is_none());
378 if composed {
379 let compose = renderer.composed.unwrap_or_else(|| panic!("{}: no composed render", W::NAME));
380 return build_composed(ui, element, props, compose);
381 }
382 let definition = Rc::new(Definition {
383 name: W::NAME,
384 a11y: |props| W::a11y(props_of::<W>(props)),
385 action: |props, action| W::action(props_of::<W>(props), action).map(AnyValue::new),
386 native: renderer.native,
387 drawn: renderer.drawn,
388 force_drawn,
389 });
390 element.prop(props, move |props| {
391 Prop::Custom(CustomProps { props: AnyValue::new(props), definition: definition.clone() })
392 });
393 element.build(ui)
394 }
395}
396
397fn build_composed<W: CustomWidget>(
401 ui: &Ui,
402 mut element: Element,
403 props: Value<W::Props>,
404 compose: ComposeFn<W>,
405) -> NodeId {
406 element.kind = WidgetKind::Container;
407 let label = element.a11y.label.take();
408 let props: Rc<dyn Fn() -> W::Props> = match props {
409 Value::Static(props) => Rc::new(move || props.clone()),
410 Value::Dynamic(props) => props,
411 };
412 let node: Rc<std::cell::Cell<Option<NodeId>>> = Rc::default();
414 let (target, weak) = (node.clone(), ui.downgrade());
415 let emit = Rc::new(move |event: W::Event| {
416 if let (Some(id), Some(ui)) = (target.get(), weak.upgrade()) {
417 ui.events().emit(id, UiEvent::Custom(AnyValue::new(event)));
418 }
419 });
420 element.add_children(compose(Composed { props, emit, label }));
421 let id = element.build(ui);
422 node.set(Some(id));
423 id
424}
425
426pub trait CustomView: Render {
428 fn view(props: impl IntoValue<Self::Props>) -> Custom<Self> {
429 Custom::new(props)
430 }
431
432 #[doc(hidden)]
434 fn __tag() -> Custom<Self, ()> {
435 Custom {
436 element: Element::new(WidgetKind::Custom(Self::NAME)),
437 props: (),
438 renderer: Self::renderer(),
439 force_drawn: false,
440 force_composed: false,
441 }
442 }
443}
444
445impl<W: Render> CustomView for W {}