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 {
45 const NAME: &'static str;
47 type Props: Clone + PartialEq + fmt::Debug + 'static;
48 type Event: Clone + PartialEq + fmt::Debug + 'static;
49
50 fn a11y(props: &Self::Props) -> A11yProps;
53
54 fn action(props: &Self::Props, action: &A11yAction) -> Option<Self::Event> {
57 let _ = (props, action);
58 None
59 }
60}
61
62pub trait Drawn: CustomWidget {
64 fn measure(props: &Self::Props, request: &MeasureRequest, metrics: &PlatformMetrics) -> Size;
66
67 fn draw(props: &Self::Props, canvas: &mut Canvas);
70
71 fn pointer(props: &Self::Props, size: Size, event: &PointerEvent) -> Option<Self::Event> {
73 let _ = (props, size, event);
74 None
75 }
76}
77
78pub trait Render: CustomWidget {
92 fn renderer() -> Renderer<Self>;
93}
94
95pub struct Renderer<W: CustomWidget> {
99 native: Option<Opaque>,
100 platform_control: bool,
102 drawn: Option<DrawnFns>,
103 composed: Option<ComposeFn<W>>,
104}
105
106type ComposeFn<W> = Rc<dyn Fn(Composed<W>) -> AnyView>;
109
110pub struct Composed<W: CustomWidget> {
113 props: Rc<dyn Fn() -> W::Props>,
114 emit: Rc<dyn Fn(W::Event)>,
115 label: Option<String>,
116}
117
118impl<W: CustomWidget> Clone for Composed<W> {
119 fn clone(&self) -> Self {
120 Composed { props: self.props.clone(), emit: self.emit.clone(), label: self.label.clone() }
121 }
122}
123
124impl<W: CustomWidget> Composed<W> {
125 pub fn props(&self) -> W::Props {
127 (self.props)()
128 }
129
130 pub fn emit(&self, event: W::Event) {
133 (self.emit)(event)
134 }
135
136 pub fn label(&self) -> Option<String> {
139 self.label.clone()
140 }
141}
142
143impl<W: CustomWidget> Renderer<W> {
144 pub fn drawn() -> Renderer<W>
146 where
147 W: Drawn,
148 {
149 Renderer { native: None, platform_control: false, drawn: Some(DrawnFns::of::<W>()), composed: None }
150 }
151
152 pub fn native(render: Opaque) -> Renderer<W> {
156 Renderer { native: Some(render), platform_control: true, drawn: None, composed: None }
157 }
158
159 pub fn ad_hoc(render: Opaque) -> Renderer<W> {
163 Renderer { native: Some(render), platform_control: false, drawn: None, composed: None }
164 }
165
166 pub fn with_drawn(mut self) -> Renderer<W>
169 where
170 W: Drawn,
171 {
172 self.drawn = Some(DrawnFns::of::<W>());
173 self
174 }
175
176 pub fn composed<V: View>(compose: impl Fn(Composed<W>) -> V + 'static) -> Renderer<W> {
179 Renderer {
180 native: None,
181 platform_control: false,
182 drawn: None,
183 composed: Some(Rc::new(move |c| AnyView::new(compose(c)))),
184 }
185 }
186
187 pub fn with_composed<V: View>(mut self, compose: impl Fn(Composed<W>) -> V + 'static) -> Renderer<W> {
189 self.composed = Some(Rc::new(move |c| AnyView::new(compose(c))));
190 self
191 }
192
193 pub fn is_native(&self) -> bool {
196 self.native.is_some() && self.platform_control
197 }
198}
199
200#[derive(Clone, Copy)]
202struct DrawnFns {
203 measure: fn(&AnyValue, &MeasureRequest, &PlatformMetrics) -> Size,
204 draw: fn(&AnyValue, &mut Canvas),
205 pointer: fn(&AnyValue, Size, &PointerEvent) -> Option<AnyValue>,
206}
207
208impl DrawnFns {
209 fn of<W: Drawn>() -> DrawnFns {
210 DrawnFns {
211 measure: |props, request, metrics| W::measure(props_of::<W>(props), request, metrics),
212 draw: |props, canvas| W::draw(props_of::<W>(props), canvas),
213 pointer: |props, size, event| W::pointer(props_of::<W>(props), size, event).map(AnyValue::new),
214 }
215 }
216}
217
218fn props_of<W: CustomWidget>(props: &AnyValue) -> &W::Props {
219 props.downcast_ref().unwrap_or_else(|| panic!("{}: props of another type: {props:?}", W::NAME))
220}
221
222struct Definition {
224 name: &'static str,
225 a11y: fn(&AnyValue) -> A11yProps,
226 action: fn(&AnyValue, &A11yAction) -> Option<AnyValue>,
227 native: Option<Opaque>,
228 drawn: Option<DrawnFns>,
229 force_drawn: bool,
231}
232
233#[derive(Clone)]
236pub struct CustomProps {
237 props: AnyValue,
238 definition: Rc<Definition>,
239}
240
241impl CustomProps {
242 pub fn name(&self) -> &'static str {
243 self.definition.name
244 }
245
246 pub fn props(&self) -> &AnyValue {
247 &self.props
248 }
249
250 pub fn get<T: 'static>(&self) -> Option<&T> {
251 self.props.downcast_ref()
252 }
253
254 pub fn with_props(&self, props: AnyValue) -> CustomProps {
256 CustomProps { props, definition: self.definition.clone() }
257 }
258
259 pub fn is_drawn(&self) -> bool {
262 self.definition.drawn.is_some() && (self.definition.force_drawn || self.definition.native.is_none())
263 }
264
265 pub fn native(&self) -> Option<&Opaque> {
267 if self.is_drawn() { None } else { self.definition.native.as_ref() }
268 }
269
270 pub fn a11y(&self) -> A11yProps {
271 (self.definition.a11y)(&self.props)
272 }
273
274 pub fn action(&self, action: &A11yAction) -> Option<AnyValue> {
276 (self.definition.action)(&self.props, action)
277 }
278
279 pub fn measure_drawn(&self, request: &MeasureRequest, metrics: &PlatformMetrics) -> Option<Size> {
281 self.definition.drawn.map(|d| (d.measure)(&self.props, request, metrics))
282 }
283
284 pub fn draw(&self, size: Size, metrics: &PlatformMetrics) -> Option<DisplayList> {
285 let drawn = self.definition.drawn?;
286 let mut canvas = Canvas::new(size, metrics);
287 (drawn.draw)(&self.props, &mut canvas);
288 Some(canvas.finish())
289 }
290
291 pub fn pointer(&self, size: Size, event: &PointerEvent) -> Option<AnyValue> {
292 self.definition.drawn.and_then(|d| (d.pointer)(&self.props, size, event))
293 }
294}
295
296impl PartialEq for CustomProps {
297 fn eq(&self, other: &CustomProps) -> bool {
298 self.props == other.props && self.name() == other.name() && self.is_drawn() == other.is_drawn()
299 }
300}
301
302impl fmt::Debug for CustomProps {
303 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
304 write!(f, "{:?}", self.props)?;
305 if self.is_drawn() {
306 f.write_str(" (drawn)")?;
307 }
308 Ok(())
309 }
310}
311
312pub struct Custom<W: CustomWidget, P = Value<<W as CustomWidget>::Props>> {
319 element: Element,
320 props: P,
321 renderer: Renderer<W>,
322 force_drawn: bool,
323 force_composed: bool,
324}
325
326impl<W: Render> Custom<W> {
327 pub fn new(props: impl IntoValue<W::Props>) -> Custom<W> {
329 Custom {
330 element: Element::new(WidgetKind::Custom(W::NAME)),
331 props: props.into_value(),
332 renderer: W::renderer(),
333 force_drawn: false,
334 force_composed: false,
335 }
336 }
337}
338
339impl<W: CustomWidget, P> Custom<W, P> {
340 pub fn props(self, props: impl IntoValue<W::Props>) -> Custom<W> {
342 let Custom { element, props: _, renderer, force_drawn, force_composed } = self;
343 Custom { element, props: props.into_value(), renderer, force_drawn, force_composed }
344 }
345
346 pub fn drawn(mut self) -> Custom<W, P>
348 where
349 W: Drawn,
350 {
351 self.renderer.drawn = Some(DrawnFns::of::<W>());
352 self.force_drawn = true;
353 self
354 }
355
356 pub fn composed(mut self) -> Custom<W, P> {
359 self.force_composed = true;
360 self
361 }
362
363 pub fn on_event(mut self, handler: impl Fn(&W::Event) + 'static) -> Custom<W, P> {
365 self.element.on(move |event| {
366 if let UiEvent::Custom(value) = event
367 && let Some(event) = value.downcast_ref::<W::Event>()
368 {
369 handler(event);
370 }
371 });
372 self
373 }
374}
375
376impl<W: CustomWidget, P> ElementBuilder for Custom<W, P> {
377 fn element(&mut self) -> &mut Element {
378 &mut self.element
379 }
380}
381
382impl<W: CustomWidget> View for Custom<W> {
383 fn build(self, ui: &Ui) -> NodeId {
384 let Custom { mut element, props, renderer, force_drawn, force_composed } = self;
385 let composed = force_composed || (!force_drawn && renderer.native.is_none() && renderer.drawn.is_none());
386 if composed {
387 let compose = renderer.composed.unwrap_or_else(|| panic!("{}: no composed render", W::NAME));
388 return build_composed(ui, element, props, compose);
389 }
390 let definition = Rc::new(Definition {
391 name: W::NAME,
392 a11y: |props| W::a11y(props_of::<W>(props)),
393 action: |props, action| W::action(props_of::<W>(props), action).map(AnyValue::new),
394 native: renderer.native,
395 drawn: renderer.drawn,
396 force_drawn,
397 });
398 element.prop(props, move |props| {
399 Prop::Custom(CustomProps { props: AnyValue::new(props), definition: definition.clone() })
400 });
401 element.build(ui)
402 }
403}
404
405fn build_composed<W: CustomWidget>(
409 ui: &Ui,
410 mut element: Element,
411 props: Value<W::Props>,
412 compose: ComposeFn<W>,
413) -> NodeId {
414 element.kind = WidgetKind::Container;
415 let label = element.a11y.label.take();
416 let props: Rc<dyn Fn() -> W::Props> = match props {
417 Value::Static(props) => Rc::new(move || props.clone()),
418 Value::Dynamic(props) => props,
419 };
420 let node: Rc<std::cell::Cell<Option<NodeId>>> = Rc::default();
422 let (target, weak) = (node.clone(), ui.downgrade());
423 let emit = Rc::new(move |event: W::Event| {
424 if let (Some(id), Some(ui)) = (target.get(), weak.upgrade()) {
425 ui.events().emit(id, UiEvent::Custom(AnyValue::new(event)));
426 }
427 });
428 element.add_children(compose(Composed { props, emit, label }));
429 let id = element.build(ui);
430 node.set(Some(id));
431 id
432}
433
434pub trait CustomView: Render {
436 fn view(props: impl IntoValue<Self::Props>) -> Custom<Self> {
437 Custom::new(props)
438 }
439
440 #[doc(hidden)]
442 fn __tag() -> Custom<Self, ()> {
443 Custom {
444 element: Element::new(WidgetKind::Custom(Self::NAME)),
445 props: (),
446 renderer: Self::renderer(),
447 force_drawn: false,
448 force_composed: false,
449 }
450 }
451}
452
453impl<W: Render> CustomView for W {}