Skip to main content

mitsuami_appkit/
custom.rs

1//! Escape hatches on AppKit: native renders for custom widgets, raw native
2//! views in the shared tree, and the rasterizer for drawn widgets.
3
4use std::any::Any;
5use std::cell::RefCell;
6use std::fmt;
7use std::marker::PhantomData;
8use std::rc::Rc;
9
10use mitsuami_core::a11y::{A11yAction, ActionError};
11use mitsuami_core::draw::{DrawOp, PathElement};
12use mitsuami_core::reactive::{IntoValue, Value};
13use mitsuami_core::{
14    AnyValue, Color, CustomWidget, DisplayList, Element, ElementBuilder, EventSink, MeasureRequest, NodeId, Opaque,
15    Prop, Renderer, Shape, Size, Ui, UiEvent, View, WidgetKind,
16};
17use objc2::rc::Retained;
18use objc2::runtime::AnyObject;
19use objc2::{DowncastTarget, MainThreadMarker, Message, sel};
20use objc2_app_kit::{NSBezierPath, NSColor, NSControl, NSView};
21use objc2_foundation::{NSPoint, NSRect, NSSize};
22
23use crate::classes::ClosureTarget;
24
25/// Sends events from native callbacks to the widget's handlers. Cheap to
26/// clone; keep one in closures that outlive creation.
27#[derive(Clone)]
28pub struct Emitter {
29    events: EventSink,
30    id: NodeId,
31}
32
33impl Emitter {
34    pub(crate) fn new(events: EventSink, id: NodeId) -> Emitter {
35        Emitter { events, id }
36    }
37
38    /// Queues an event. Handlers run on the next turn of the run loop, never
39    /// inside the native callback.
40    pub fn emit<E: Any + PartialEq + fmt::Debug>(&self, event: E) {
41        self.events.emit(self.id, UiEvent::Custom(AnyValue::new(event)));
42    }
43}
44
45/// What a native render or native view gets while its view is created.
46pub struct AppKitCx<'a> {
47    mtm: MainThreadMarker,
48    emitter: Emitter,
49    targets: &'a mut Vec<Retained<ClosureTarget>>,
50}
51
52impl<'a> AppKitCx<'a> {
53    pub(crate) fn new(
54        mtm: MainThreadMarker,
55        id: NodeId,
56        events: EventSink,
57        targets: &'a mut Vec<Retained<ClosureTarget>>,
58    ) -> AppKitCx<'a> {
59        AppKitCx { mtm, emitter: Emitter::new(events, id), targets }
60    }
61
62    pub fn mtm(&self) -> MainThreadMarker {
63        self.mtm
64    }
65
66    pub fn emitter(&self) -> Emitter {
67        self.emitter.clone()
68    }
69
70    pub fn emit<E: Any + PartialEq + fmt::Debug>(&self, event: E) {
71        self.emitter.emit(event);
72    }
73
74    /// Runs `handler` when the control sends its action (a click, a new
75    /// value). The target lives as long as the node.
76    pub fn on_action<C>(&mut self, control: &C, handler: impl Fn(&C) + 'static)
77    where
78        C: Message + DowncastTarget + AsRef<NSControl>,
79    {
80        let target = ClosureTarget::new(self.mtm, move |sender| {
81            if let Some(control) = sender.downcast_ref::<C>() {
82                handler(control);
83            }
84        });
85        let control: &NSControl = control.as_ref();
86        let target_obj: &AnyObject = target.as_ref();
87        // SAFETY: the node keeps the target alive as long as the control.
88        unsafe {
89            control.setTarget(Some(target_obj));
90            control.setAction(Some(sel!(fire:)));
91        }
92        self.targets.push(target);
93    }
94}
95
96/// A custom widget's AppKit render: one per widget, next to its shared
97/// definition (e.g. `rating/macos.rs`). Hand it to the widget's `Render`
98/// impl with [`native`].
99///
100/// Custom widgets are controlled: when the user changes the view, emit an
101/// event; the app answers with new props, and `update` shows them.
102pub trait NativeRender: CustomWidget {
103    type View: Message + DowncastTarget + AsRef<NSView>;
104
105    fn create(props: &Self::Props, cx: &mut AppKitCx) -> Retained<Self::View>;
106
107    fn update(view: &Self::View, old: &Self::Props, new: &Self::Props);
108
109    /// Intrinsic size. `None` uses the view's `intrinsicContentSize`.
110    fn measure(view: &Self::View, props: &Self::Props, request: &MeasureRequest) -> Option<Size> {
111        let _ = (view, props, request);
112        None
113    }
114
115    /// Props as the view shows them, so tests can catch a view that
116    /// doesn't show what it was given. The default trusts the last props.
117    fn read(view: &Self::View, props: &Self::Props) -> Self::Props {
118        let _ = view;
119        props.clone()
120    }
121
122    /// Carries out an accessibility action on the view. The default,
123    /// `Unsupported`, lets the shared `CustomWidget::action` decide.
124    fn perform(
125        view: &Self::View,
126        props: &Self::Props,
127        action: &A11yAction,
128        emitter: &Emitter,
129    ) -> Result<(), ActionError> {
130        let _ = (view, props, action, emitter);
131        Err(ActionError::Unsupported)
132    }
133}
134
135/// The renderer for a widget whose AppKit render is AppKit's own control.
136pub fn native<W: NativeRender>() -> Renderer<W> {
137    Renderer::native(erased::<W>())
138}
139
140/// The renderer for a widget AppKit has no control for, built ad hoc from
141/// AppKit views the way Mac apps build it. Not labelled native.
142pub fn ad_hoc<W: NativeRender>() -> Renderer<W> {
143    Renderer::ad_hoc(erased::<W>())
144}
145
146fn erased<W: NativeRender>() -> Opaque {
147    let render: Rc<dyn ErasedRender> = Rc::new(RenderImpl::<W>(PhantomData));
148    Opaque::new("appkit render", render)
149}
150
151/// [`NativeRender`] with the types erased, as the backend holds it.
152pub(crate) trait ErasedRender {
153    fn create(&self, props: &AnyValue, cx: &mut AppKitCx) -> Retained<NSView>;
154    fn update(&self, view: &NSView, old: &AnyValue, new: &AnyValue);
155    fn measure(&self, view: &NSView, props: &AnyValue, request: &MeasureRequest) -> Option<Size>;
156    fn read(&self, view: &NSView, props: &AnyValue) -> AnyValue;
157    fn perform(
158        &self,
159        view: &NSView,
160        props: &AnyValue,
161        action: &A11yAction,
162        emitter: &Emitter,
163    ) -> Result<(), ActionError>;
164}
165
166struct RenderImpl<W>(PhantomData<fn() -> W>);
167
168impl<W: NativeRender> RenderImpl<W> {
169    fn props(props: &AnyValue) -> &W::Props {
170        props.downcast_ref().unwrap_or_else(|| panic!("{}: props of another type: {props:?}", W::NAME))
171    }
172
173    fn view(view: &NSView) -> &W::View {
174        view.downcast_ref().unwrap_or_else(|| panic!("{}: the node's view is not the render's", W::NAME))
175    }
176}
177
178impl<W: NativeRender> ErasedRender for RenderImpl<W> {
179    fn create(&self, props: &AnyValue, cx: &mut AppKitCx) -> Retained<NSView> {
180        let view = W::create(Self::props(props), cx);
181        let view: &NSView = (*view).as_ref();
182        view.retain()
183    }
184
185    fn update(&self, view: &NSView, old: &AnyValue, new: &AnyValue) {
186        W::update(Self::view(view), Self::props(old), Self::props(new));
187    }
188
189    fn measure(&self, view: &NSView, props: &AnyValue, request: &MeasureRequest) -> Option<Size> {
190        W::measure(Self::view(view), Self::props(props), request)
191    }
192
193    fn read(&self, view: &NSView, props: &AnyValue) -> AnyValue {
194        AnyValue::new(W::read(Self::view(view), Self::props(props)))
195    }
196
197    fn perform(
198        &self,
199        view: &NSView,
200        props: &AnyValue,
201        action: &A11yAction,
202        emitter: &Emitter,
203    ) -> Result<(), ActionError> {
204        W::perform(Self::view(view), Self::props(props), action, emitter)
205    }
206}
207
208type Factory = Box<dyn FnOnce(&mut AppKitCx) -> Retained<NSView>>;
209type TypedFactory<V> = Box<dyn FnOnce(&mut AppKitCx) -> Retained<V>>;
210type Measure = Rc<dyn Fn(&NSView, &MeasureRequest) -> Size>;
211type Apply = Rc<dyn Fn(&NSView)>;
212/// Reads one `update` source (tracked) and returns how to apply its value.
213type Snapshot = Box<dyn Fn() -> Apply>;
214
215/// How to create a native view.
216pub(crate) struct NativeViewSpec {
217    pub(crate) create: RefCell<Option<Factory>>,
218    pub(crate) measure: Option<Measure>,
219}
220
221/// A native view's `Prop::Native`: how to create it, and every `update`
222/// with its current value. When any value changes, the whole payload is
223/// sent again and every update re-applied.
224#[derive(Clone)]
225pub(crate) struct NativePayload {
226    pub(crate) spec: Rc<NativeViewSpec>,
227    pub(crate) updates: Vec<Apply>,
228}
229
230impl NativePayload {
231    pub(crate) fn apply(&self, view: &NSView) {
232        for update in &self.updates {
233            update(view);
234        }
235    }
236}
237
238/// Any `NSView` in the shared tree. It takes part in layout like other
239/// leaves; the core sees `WidgetKind::Native`.
240///
241/// ```ignore
242/// NativeView::appkit(|cx| {
243///     let stepper = NSStepper::new(cx.mtm());
244///     let emitter = cx.emitter();
245///     cx.on_action(&*stepper, move |s| emitter.emit(s.doubleValue()));
246///     stepper
247/// })
248/// .update(value, |stepper, value| stepper.setDoubleValue(*value))
249/// .on_event(move |value: &f64| value_signal.set(*value))
250/// ```
251///
252/// Headless tests show it as an empty box: give it a size, or test it natively.
253pub struct NativeView<V> {
254    element: Element,
255    create: TypedFactory<V>,
256    measure: Option<Measure>,
257    updates: Vec<Snapshot>,
258}
259
260impl<V: Message + DowncastTarget + AsRef<NSView>> NativeView<V> {
261    /// `create` runs once, when the backend creates the node.
262    pub fn appkit(create: impl FnOnce(&mut AppKitCx) -> Retained<V> + 'static) -> NativeView<V> {
263        NativeView {
264            element: Element::new(WidgetKind::Native),
265            create: Box::new(create),
266            measure: None,
267            updates: Vec::new(),
268        }
269    }
270
271    /// Intrinsic size. Without it, the view's `intrinsicContentSize` (or
272    /// zero where it has none: size it with styles).
273    pub fn measure(mut self, measure: impl Fn(&V, &MeasureRequest) -> Size + 'static) -> NativeView<V> {
274        self.measure = Some(Rc::new(move |view: &NSView, request: &MeasureRequest| match view.downcast_ref::<V>() {
275            Some(view) => measure(view, request),
276            None => Size::ZERO,
277        }));
278        self
279    }
280
281    /// Calls `apply` with the view and the value, now and whenever the
282    /// value changes. Values are usually signals or closures.
283    pub fn update<T: Clone + 'static>(
284        mut self,
285        value: impl IntoValue<T>,
286        apply: impl Fn(&V, &T) + 'static,
287    ) -> NativeView<V> {
288        let value = value.into_value();
289        let apply = Rc::new(apply);
290        self.updates.push(Box::new(move || {
291            let value = value.get();
292            let apply = apply.clone();
293            Rc::new(move |view: &NSView| {
294                if let Some(view) = view.downcast_ref::<V>() {
295                    apply(view, &value);
296                }
297            })
298        }));
299        self
300    }
301
302    /// Called with each event of type `E` the view emits (see [`Emitter`]).
303    pub fn on_event<E: 'static>(mut self, handler: impl Fn(&E) + 'static) -> NativeView<V> {
304        self.element.on(move |event| {
305            if let UiEvent::Custom(value) = event
306                && let Some(event) = value.downcast_ref::<E>()
307            {
308                handler(event);
309            }
310        });
311        self
312    }
313}
314
315impl<V> ElementBuilder for NativeView<V> {
316    fn element(&mut self) -> &mut Element {
317        &mut self.element
318    }
319}
320
321impl<V: Message + DowncastTarget + AsRef<NSView>> View for NativeView<V> {
322    fn build(self, ui: &Ui) -> NodeId {
323        let NativeView { mut element, create, measure, updates } = self;
324        let create: Factory = Box::new(move |cx| {
325            let view = create(cx);
326            let view: &NSView = (*view).as_ref();
327            view.retain()
328        });
329        let spec = Rc::new(NativeViewSpec { create: RefCell::new(Some(create)), measure });
330        let payload = move || NativePayload { spec: spec.clone(), updates: updates.iter().map(|u| u()).collect() };
331        element.prop(Value::Dynamic(Rc::new(payload)), |payload| Prop::Native(Opaque::new("appkit view", payload)));
332        element.build(ui)
333    }
334}
335
336// ------------------------------------------------------------- drawn tier
337
338fn ns_rect(r: &mitsuami_core::Rect) -> NSRect {
339    NSRect::new(NSPoint::new(r.x() as f64, r.y() as f64), NSSize::new(r.width() as f64, r.height() as f64))
340}
341
342fn ns_point(p: mitsuami_core::Point) -> NSPoint {
343    NSPoint::new(p.x as f64, p.y as f64)
344}
345
346pub(crate) fn ns_color(color: Color) -> Retained<NSColor> {
347    match color {
348        Color::Label => NSColor::labelColor(),
349        Color::SecondaryLabel => NSColor::secondaryLabelColor(),
350        Color::Accent => NSColor::controlAccentColor(),
351        Color::Separator => NSColor::separatorColor(),
352        Color::ControlBackground => NSColor::controlBackgroundColor(),
353        Color::WindowBackground => NSColor::windowBackgroundColor(),
354        Color::Error => NSColor::systemRedColor(),
355        Color::Warning => NSColor::systemOrangeColor(),
356        Color::Success => NSColor::systemGreenColor(),
357        Color::Rgba(r, g, b, a) => {
358            let c = |v: u8| v as f64 / 255.0;
359            NSColor::colorWithSRGBRed_green_blue_alpha(c(r), c(g), c(b), c(a))
360        }
361    }
362}
363
364fn bezier(shape: &Shape) -> Retained<NSBezierPath> {
365    match shape {
366        Shape::Rect(r) => NSBezierPath::bezierPathWithRect(ns_rect(r)),
367        Shape::RoundedRect(r, radius) => {
368            NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(ns_rect(r), *radius as f64, *radius as f64)
369        }
370        Shape::Ellipse(r) => NSBezierPath::bezierPathWithOvalInRect(ns_rect(r)),
371        Shape::Path(path) => {
372            let bezier = NSBezierPath::new();
373            for element in path.elements() {
374                // A line or curve with no point to start from raises an
375                // exception, which aborts the app from `drawRect:`: it starts
376                // where cairo starts it, at its first point.
377                match *element {
378                    PathElement::LineTo(p) | PathElement::CurveTo { c1: p, .. } if bezier.isEmpty() => {
379                        bezier.moveToPoint(ns_point(p))
380                    }
381                    _ => {}
382                }
383                match *element {
384                    PathElement::MoveTo(p) => bezier.moveToPoint(ns_point(p)),
385                    PathElement::LineTo(p) => bezier.lineToPoint(ns_point(p)),
386                    PathElement::CurveTo { c1, c2, to } => {
387                        bezier.curveToPoint_controlPoint1_controlPoint2(ns_point(to), ns_point(c1), ns_point(c2))
388                    }
389                    PathElement::Close if bezier.isEmpty() => {}
390                    PathElement::Close => bezier.closePath(),
391                }
392            }
393            bezier
394        }
395    }
396}
397
398/// Draws a display list into the current (flipped) view. Semantic colors
399/// resolve against the view's appearance, so dark mode just works.
400pub(crate) fn rasterize(drawing: &DisplayList) {
401    for op in drawing.ops() {
402        match op {
403            DrawOp::Fill { shape, color } => {
404                ns_color(*color).setFill();
405                bezier(shape).fill();
406            }
407            DrawOp::Stroke { shape, color, width } => {
408                ns_color(*color).setStroke();
409                let path = bezier(shape);
410                path.setLineWidth(*width as f64);
411                path.stroke();
412            }
413        }
414    }
415}