Skip to main content

mitsuami_core/
custom.rs

1//! Custom widgets: one platform-free definition, rendered natively on each
2//! platform or drawn with the [`Canvas`] API.
3//!
4//! - [`CustomWidget`]: the shared part. Props, events, semantics, and what
5//!   accessibility actions mean.
6//! - [`Drawn`]: the drawn tier. Measure, draw and hit-test in shared code;
7//!   runs everywhere, and stands in for the widget in headless tests.
8//! - The composed tier ([`Renderer::composed`]): built from the built-in
9//!   widgets, for widgets the [`Canvas`] can't draw (text, editing).
10//! - A native render per platform, e.g. `mitsuami_appkit::NativeRender`.
11//! - [`Render`]: says which render each platform uses. Using a widget
12//!   requires it, so a platform with no render doesn't compile.
13//!
14//! A widget unique to one platform is native there. Elsewhere it's built
15//! ad hoc from the platform's widgets, the way that platform's apps build
16//! it ([`Renderer::ad_hoc`]), or drawn, or composed; [`Renderer::is_native`]
17//! says which.
18
19use 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
35/// The shared, platform-free definition of a custom widget.
36pub trait CustomWidget: Sized + 'static {
37    /// Shown in trees, logs and snapshots.
38    const NAME: &'static str;
39    type Props: Clone + PartialEq + fmt::Debug + 'static;
40    type Event: Clone + PartialEq + fmt::Debug + 'static;
41
42    /// Semantics, shared by every render. Apps can still override the
43    /// label and description where they use the widget.
44    fn a11y(props: &Self::Props) -> A11yProps;
45
46    /// What an accessibility action (increment, set value, …) means for
47    /// this widget. Used unless the native render performs it itself.
48    fn action(props: &Self::Props, action: &A11yAction) -> Option<Self::Event> {
49        let _ = (props, action);
50        None
51    }
52}
53
54/// The drawn tier: measured, drawn and hit-tested in shared code.
55pub trait Drawn: CustomWidget {
56    /// Intrinsic size, like a backend measures a native control.
57    fn measure(props: &Self::Props, request: &MeasureRequest, metrics: &PlatformMetrics) -> Size;
58
59    /// Draws into `canvas`, sized to the widget's frame. Called again
60    /// whenever the props, the size or the platform metrics change.
61    fn draw(props: &Self::Props, canvas: &mut Canvas);
62
63    /// What a pointer event at `event.position` (widget coordinates) means.
64    fn pointer(props: &Self::Props, size: Size, event: &PointerEvent) -> Option<Self::Event> {
65        let _ = (props, size, event);
66        None
67    }
68}
69
70/// Which render this platform uses. Implement it once, choosing per
71/// platform with `platform!`:
72///
73/// ```ignore
74/// impl Render for Rating {
75///     fn renderer() -> Renderer<Self> {
76///         platform! {
77///             macos => mitsuami_appkit::native::<Self>().with_drawn(),
78///             _ => Renderer::drawn(),
79///         }
80///     }
81/// }
82/// ```
83pub trait Render: CustomWidget {
84    fn renderer() -> Renderer<Self>;
85}
86
87/// A widget's renders on the current platform: native, drawn or composed.
88/// The first one present is used: native, then drawn, then composed. The
89/// others stay available (for headless tests, `.drawn()`, `.composed()`).
90pub struct Renderer<W: CustomWidget> {
91    native: Option<Opaque>,
92    /// The native render is the platform's own control, not built ad hoc.
93    platform_control: bool,
94    drawn: Option<DrawnFns>,
95    composed: Option<ComposeFn<W>>,
96}
97
98/// Builds the composed render from the widget's props and a way to emit
99/// its events.
100type ComposeFn<W> = Rc<dyn Fn(Composed<W>) -> AnyView>;
101
102/// What a composed render gets: the props (reactive), a way to emit the
103/// widget's events, and the accessible label the app gave the widget.
104pub 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    /// The current props. Reading them in a reactive closure tracks them.
118    pub fn props(&self) -> W::Props {
119        (self.props)()
120    }
121
122    /// Sends an event to the widget's `on_event` handlers. Call it from the
123    /// built-in widgets' handlers (a click, a submit).
124    pub fn emit(&self, event: W::Event) {
125        (self.emit)(event)
126    }
127
128    /// The accessible label the app gave the widget: put it on the control
129    /// that stands for the widget, so it's found the same way.
130    pub fn label(&self) -> Option<String> {
131        self.label.clone()
132    }
133}
134
135impl<W: CustomWidget> Renderer<W> {
136    /// Draws the widget with its [`Drawn`] implementation.
137    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    /// For backend crates: a native render that is the platform's own
145    /// control, in whatever form the backend understands. Apps use the
146    /// backend's constructor instead.
147    pub fn native(render: Opaque) -> Renderer<W> {
148        Renderer { native: Some(render), platform_control: true, drawn: None, composed: None }
149    }
150
151    /// For backend crates: a render built ad hoc from the platform's widgets,
152    /// where the platform has no such control. It's rendered like a native
153    /// one, but [`is_native`](Renderer::is_native) says no.
154    pub fn ad_hoc(render: Opaque) -> Renderer<W> {
155        Renderer { native: Some(render), platform_control: false, drawn: None, composed: None }
156    }
157
158    /// Keeps the drawn render too: headless tests lay the widget out with
159    /// it, and `Custom::drawn` can pick it.
160    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    /// Composes the widget from built-in widgets: the tier for widgets the
169    /// canvas can't draw.
170    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    /// Keeps a composed render too, for `Custom::composed`.
180    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    /// Whether the widget is the platform's own control here (rather than
186    /// built ad hoc, drawn or composed as a stand-in).
187    pub fn is_native(&self) -> bool {
188        self.native.is_some() && self.platform_control
189    }
190}
191
192/// The drawn tier, type-erased.
193#[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
214/// Everything about one custom widget instance that is fixed at build time.
215struct 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    /// Draw it even where a native render exists.
222    force_drawn: bool,
223}
224
225/// The props of a custom widget, as carried by [`Prop::Custom`]: the value
226/// plus the widget's type-erased definition (semantics and renders).
227#[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    /// The same widget with other props, e.g. read back from a native view.
247    pub fn with_props(&self, props: AnyValue) -> CustomProps {
248        CustomProps { props, definition: self.definition.clone() }
249    }
250
251    /// Whether the widget is drawn (by the core's display list) rather than
252    /// rendered natively.
253    pub fn is_drawn(&self) -> bool {
254        self.definition.drawn.is_some() && (self.definition.force_drawn || self.definition.native.is_none())
255    }
256
257    /// The native render, unless the widget is drawn.
258    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    /// The event an accessibility action stands for, if any.
267    pub fn action(&self, action: &A11yAction) -> Option<AnyValue> {
268        (self.definition.action)(&self.props, action)
269    }
270
271    /// Size from the drawn render, if the widget has one.
272    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
304/// A custom widget in the view tree: `Custom::<Rating>::new(props)`, or
305/// `Rating::view(props)` through [`CustomView`].
306///
307/// `P` is the props: `Value<W::Props>`, or `()` for a `<Rating …>` tag in
308/// `view!` whose `props=…` isn't set yet. Only a widget with props is a
309/// [`View`].
310pub 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    /// Props are usually reactive: `move || RatingProps { value: rating.get(), .. }`.
320    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    /// Sets the props; usually reactive: `move || RatingProps { … }`.
333    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    /// Uses the drawn render even where a native one exists.
339    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    /// Uses the composed render even where another one exists. Panics at
349    /// build time if the widget has none.
350    pub fn composed(mut self) -> Custom<W, P> {
351        self.force_composed = true;
352        self
353    }
354
355    /// Called with each event the widget emits.
356    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
397/// The composed tier: a plain container around what the render builds. The
398/// app's accessible label goes to the render (onto the control that stands
399/// for the widget); styles, test id and handlers stay on the container.
400fn 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    // Events go to the container's handlers, the widget's `on_event` ones.
413    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
426/// `Rating::view(props)`: shorthand for `Custom::<Rating>::new(props)`.
427pub trait CustomView: Render {
428    fn view(props: impl IntoValue<Self::Props>) -> Custom<Self> {
429        Custom::new(props)
430    }
431
432    /// `<Rating props=… @event=…/>` in `view!`: the widget before its props.
433    #[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 {}