1use 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#[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 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
45pub 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 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 unsafe {
89 control.setTarget(Some(target_obj));
90 control.setAction(Some(sel!(fire:)));
91 }
92 self.targets.push(target);
93 }
94}
95
96pub 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 fn measure(view: &Self::View, props: &Self::Props, request: &MeasureRequest) -> Option<Size> {
111 let _ = (view, props, request);
112 None
113 }
114
115 fn read(view: &Self::View, props: &Self::Props) -> Self::Props {
118 let _ = view;
119 props.clone()
120 }
121
122 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
135pub fn native<W: NativeRender>() -> Renderer<W> {
137 Renderer::native(erased::<W>())
138}
139
140pub 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
151pub(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)>;
212type Snapshot = Box<dyn Fn() -> Apply>;
214
215pub(crate) struct NativeViewSpec {
217 pub(crate) create: RefCell<Option<Factory>>,
218 pub(crate) measure: Option<Measure>,
219}
220
221#[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
238pub 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 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 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 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 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
336fn 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 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
398pub(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}