mitsuami-appkit 0.0.1

AppKit (macOS) backend for mitsuami
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
//! The [`Backend`] implementation.

use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;

use mitsuami_core::a11y::{A11yAction, A11yProps, ActionError};
use mitsuami_core::backend::{
    AvailableSpace, Backend, CaptureError, EventSink, FontSizes, Image, Key, MeasureRequest, NativeState,
    PlatformMetrics, SyntheticInput,
};
use mitsuami_core::units::SpacingScale;
use mitsuami_core::{
    ButtonVariant, Command, CustomProps, EventValue, NodeId, Opaque, Point, Prop, Rect, ScrollAxes, Size, TextStyle,
    UiEvent, WidgetKind, find_prop,
};
use objc2::rc::Retained;
use objc2::runtime::{AnyObject, ProtocolObject};
use objc2::{MainThreadMarker, MainThreadOnly, Message, msg_send, sel};
use objc2_app_kit::{
    NSAccessibility, NSAppearance, NSAppearanceCustomization, NSAppearanceNameAqua, NSAppearanceNameDarkAqua,
    NSApplication, NSBackingStoreType, NSBitmapFormat, NSButton, NSControl, NSControlStateValueOff,
    NSControlStateValueOn, NSEvent, NSEventModifierFlags, NSEventType, NSFont, NSFontTextStyle, NSFontTextStyleBody,
    NSFontTextStyleCallout, NSFontTextStyleCaption1, NSFontTextStyleHeadline, NSFontTextStyleLargeTitle,
    NSFontTextStyleTitle1, NSFontWeightRegular, NSScreen, NSScrollView, NSStandardKeyBindingResponding, NSSwitch,
    NSTextField, NSView, NSViewBoundsDidChangeNotification, NSWindow, NSWindowOrderingMode, NSWindowStyleMask,
    NSWorkspace,
};
use objc2_foundation::{NSArray, NSDictionary, NSNotificationCenter, NSPoint, NSRange, NSRect, NSSize, NSString};

use crate::classes::{ActionTarget, ClosureTarget, DrawnView, HostView, ViewMap, WindowDelegate};
use crate::custom::{AppKitCx, Emitter, ErasedRender, NativePayload};

/// How the backend behaves; apps and tests want different things.
#[derive(Clone, Debug)]
pub struct BackendOptions {
    /// Order windows front once their first layout is applied. Tests keep
    /// windows offscreen: layout, events and capture all work without it.
    pub show_windows: bool,
    /// Keep a log of applied commands (for tests).
    pub record_commands: bool,
    /// Force the light appearance, so captures are comparable across
    /// machines regardless of system settings.
    pub force_light_appearance: bool,
    /// Use a private pasteboard instead of the system clipboard (tests).
    pub private_clipboard: bool,
}

impl Default for BackendOptions {
    fn default() -> Self {
        BackendOptions {
            show_windows: true,
            record_commands: false,
            force_light_appearance: false,
            private_clipboard: false,
        }
    }
}

enum Widget {
    Window {
        window: Retained<NSWindow>,
        host: Retained<HostView>,
        _delegate: Retained<WindowDelegate>,
    },
    Host(Retained<HostView>),
    Label(Retained<NSTextField>),
    Field(Retained<NSTextField>),
    Button(Retained<NSButton>),
    Checkbox(Retained<NSButton>),
    Switch(Retained<NSSwitch>),
    Scroll(Retained<NSScrollView>),
    /// A custom widget with an AppKit render, and the props it last got.
    Custom {
        view: Retained<NSView>,
        render: Rc<dyn ErasedRender>,
        props: CustomProps,
    },
    /// A drawn custom widget.
    Drawn {
        view: Retained<DrawnView>,
        props: CustomProps,
    },
    /// A native view from app code, and the last `Prop::Native` it got.
    Native {
        view: Retained<NSView>,
        measure: Option<NativeMeasure>,
        last: Opaque,
    },
}

type NativeMeasure = Rc<dyn Fn(&NSView, &MeasureRequest) -> Size>;

impl Widget {
    fn view(&self) -> &NSView {
        match self {
            Widget::Window { host, .. } => host,
            Widget::Host(v) => v,
            Widget::Label(v) | Widget::Field(v) => v,
            Widget::Button(v) | Widget::Checkbox(v) => v,
            Widget::Switch(v) => v,
            Widget::Scroll(v) => v,
            Widget::Custom { view, .. } | Widget::Native { view, .. } => view,
            Widget::Drawn { view, .. } => view,
        }
    }

    fn control(&self) -> Option<&NSControl> {
        match self {
            Widget::Label(v) | Widget::Field(v) => Some(v),
            Widget::Button(v) | Widget::Checkbox(v) => Some(v),
            Widget::Switch(v) => Some(v),
            Widget::Window { .. }
            | Widget::Host(_)
            | Widget::Scroll(_)
            | Widget::Custom { .. }
            | Widget::Drawn { .. }
            | Widget::Native { .. } => None,
        }
    }
}

struct Node {
    kind: WidgetKind,
    widget: Widget,
    /// Controls only hold weak references to their target and delegate.
    _target: Option<Retained<ActionTarget>>,
    /// Action targets of native renders and native views.
    _targets: Vec<Retained<ClosureTarget>>,
    parent: Option<NodeId>,
    /// Props AppKit can't report back faithfully.
    text_style: Option<TextStyle>,
    variant: Option<ButtonVariant>,
}

struct State {
    mtm: MainThreadMarker,
    options: BackendOptions,
    nodes: HashMap<NodeId, Node>,
    /// Native view (by address) → node. Shared with window delegates, which
    /// resolve the first responder; only ever borrowed briefly.
    by_view: ViewMap,
    events: EventSink,
    log: Vec<Command>,
    pending_show: Vec<NodeId>,
    /// The key view chain last built for each window.
    focus_orders: HashMap<NodeId, Vec<NodeId>>,
}

pub struct AppKitBackend {
    state: Rc<RefCell<State>>,
}

/// Shared access to an [`AppKitBackend`] after it was moved into a `Ui`.
#[derive(Clone)]
pub struct AppKitHandle {
    state: Rc<RefCell<State>>,
}

fn ns(s: &str) -> Retained<NSString> {
    NSString::from_str(s)
}

fn key(view: &NSView) -> usize {
    view as *const NSView as usize
}

fn font(style: TextStyle) -> Retained<NSFont> {
    let text_style: &NSFontTextStyle = unsafe {
        match style {
            TextStyle::LargeTitle => NSFontTextStyleLargeTitle,
            TextStyle::Title => NSFontTextStyleTitle1,
            TextStyle::Headline => NSFontTextStyleHeadline,
            TextStyle::Body => NSFontTextStyleBody,
            TextStyle::Callout => NSFontTextStyleCallout,
            TextStyle::Caption => NSFontTextStyleCaption1,
            TextStyle::Monospace => {
                let size = font(TextStyle::Body).pointSize();
                return NSFont::monospacedSystemFontOfSize_weight(size, NSFontWeightRegular);
            }
        }
    };
    unsafe { NSFont::preferredFontForTextStyle_options(text_style, &NSDictionary::new()) }
}

fn metrics(mtm: MainThreadMarker) -> PlatformMetrics {
    let size = |style| font(style).pointSize() as f32;
    let appearance = NSApplication::sharedApplication(mtm).effectiveAppearance();
    let candidates = unsafe { [NSAppearanceNameAqua, NSAppearanceNameDarkAqua] };
    let names = NSArray::from_slice(&candidates);
    let dark = appearance
        .bestMatchFromAppearancesWithNames(&names)
        .is_some_and(|name| &*name == unsafe { NSAppearanceNameDarkAqua });
    let workspace = NSWorkspace::sharedWorkspace();
    PlatformMetrics {
        scale_factor: NSScreen::mainScreen(mtm).map_or(1.0, |s| s.backingScaleFactor() as f32),
        // The macOS HIG favours tight spacing; 20pt is the standard window margin.
        spacing: SpacingScale { xs: 4.0, sm: 6.0, md: 8.0, lg: 12.0, xl: 20.0 },
        font_sizes: FontSizes {
            large_title: size(TextStyle::LargeTitle),
            title: size(TextStyle::Title),
            headline: size(TextStyle::Headline),
            body: size(TextStyle::Body),
            callout: size(TextStyle::Callout),
            caption: size(TextStyle::Caption),
            monospace: size(TextStyle::Monospace),
        },
        dark_mode: dark,
        high_contrast: workspace.accessibilityDisplayShouldIncreaseContrast(),
        reduced_motion: workspace.accessibilityDisplayShouldReduceMotion(),
    }
}

fn violation(command: &Command, problem: &str) -> ! {
    panic!("appkit backend: protocol violation in {command:?}: {problem}")
}

impl AppKitBackend {
    pub fn new(mtm: MainThreadMarker, options: BackendOptions) -> AppKitBackend {
        AppKitBackend {
            state: Rc::new(RefCell::new(State {
                mtm,
                options,
                nodes: HashMap::new(),
                by_view: ViewMap::default(),
                events: EventSink::default(),
                log: Vec::new(),
                pending_show: Vec::new(),
                focus_orders: HashMap::new(),
            })),
        }
    }

    pub fn handle(&self) -> AppKitHandle {
        AppKitHandle { state: self.state.clone() }
    }
}

impl AppKitHandle {
    pub fn command_log(&self) -> Vec<Command> {
        self.state.borrow().log.clone()
    }

    pub fn take_command_log(&self) -> Vec<Command> {
        std::mem::take(&mut self.state.borrow_mut().log)
    }

    /// Number of live native nodes.
    pub fn node_count(&self) -> usize {
        self.state.borrow().nodes.len()
    }

    /// Resizes a window's content like the user would; the window delegate
    /// reports it back as a `WindowResized` event.
    pub fn resize_window(&self, window: NodeId, size: Size) {
        let window = self.ns_window(window);
        if let Some(window) = window {
            window.setContentSize(NSSize::new(size.width as f64, size.height as f64));
        }
    }

    /// Orders front windows whose first layout has been applied.
    pub fn show_pending_windows(&self) {
        let pending = std::mem::take(&mut self.state.borrow_mut().pending_show);
        for id in pending {
            if let Some(window) = self.ns_window(id) {
                window.center();
                window.makeKeyAndOrderFront(None);
            }
        }
    }

    /// Escape hatch: the native window of a window node.
    pub fn ns_window(&self, id: NodeId) -> Option<Retained<NSWindow>> {
        match &self.state.borrow().nodes.get(&id)?.widget {
            Widget::Window { window, .. } => Some(window.clone()),
            _ => None,
        }
    }

    /// Escape hatch: the native view of any node (a window's content view).
    pub fn ns_view(&self, id: NodeId) -> Option<Retained<NSView>> {
        let state = self.state.borrow();
        let view = state.nodes.get(&id)?.widget.view();
        Some(view.retain())
    }
}

impl mitsuami_core::TestHooks for AppKitHandle {
    fn name(&self) -> &'static str {
        "appkit"
    }

    fn resize_window(&self, window: NodeId, size: Size) {
        AppKitHandle::resize_window(self, window, size);
    }

    fn take_command_log(&self) -> Vec<Command> {
        AppKitHandle::take_command_log(self)
    }

    fn node_count(&self) -> usize {
        AppKitHandle::node_count(self)
    }
}

impl State {
    fn create(&mut self, id: NodeId, kind: WidgetKind, command: &Command) {
        let mtm = self.mtm;
        let target = matches!(
            kind,
            WidgetKind::Button
                | WidgetKind::Checkbox
                | WidgetKind::Switch
                | WidgetKind::TextInput
                | WidgetKind::ScrollView
        )
        .then(|| ActionTarget::new(mtm, id, kind, self.events.clone()));
        let action = Some(sel!(fire:));
        let mut targets = Vec::new();
        let target_obj: Option<&AnyObject> = target.as_deref().map(|t| t.as_ref());
        let widget = match kind {
            WidgetKind::Window => {
                let style = NSWindowStyleMask::Titled
                    | NSWindowStyleMask::Closable
                    | NSWindowStyleMask::Miniaturizable
                    | NSWindowStyleMask::Resizable;
                let window = unsafe {
                    NSWindow::initWithContentRect_styleMask_backing_defer(
                        NSWindow::alloc(mtm),
                        NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(400.0, 300.0)),
                        style,
                        NSBackingStoreType::Buffered,
                        false,
                    )
                };
                unsafe { window.setReleasedWhenClosed(false) };
                // The core owns the Tab order (reading order, not geometry)
                // and sends it with SetFocusOrder.
                window.setAutorecalculatesKeyViewLoop(false);
                let host = HostView::new(mtm, true);
                window.setContentView(Some(&host));
                let delegate = WindowDelegate::new(mtm, id, self.events.clone(), self.by_view.clone());
                window.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
                delegate.observe_focus(&window);
                if self.options.force_light_appearance {
                    window.setAppearance(NSAppearance::appearanceNamed(unsafe { NSAppearanceNameAqua }).as_deref());
                }
                if self.options.show_windows {
                    self.pending_show.push(id);
                }
                Widget::Window { window, host, _delegate: delegate }
            }
            WidgetKind::Container => Widget::Host(HostView::new(mtm, false)),
            WidgetKind::Custom(_) => {
                let Command::Create { props, .. } = command else { unreachable!() };
                let Some(custom) = find_prop!(props, Custom) else {
                    violation(command, "a custom widget needs its Prop::Custom")
                };
                match custom.native() {
                    Some(native) => {
                        let Some(render) = native.downcast_ref::<Rc<dyn ErasedRender>>().cloned() else {
                            violation(command, "the native render is not an AppKit one")
                        };
                        let mut cx = AppKitCx::new(mtm, id, self.events.clone(), &mut targets);
                        let view = render.create(custom.props(), &mut cx);
                        Widget::Custom { view, render, props: custom }
                    }
                    None => Widget::Drawn { view: DrawnView::new(mtm, id, self.events.clone()), props: custom },
                }
            }
            WidgetKind::Native => {
                let Command::Create { props, .. } = command else { unreachable!() };
                let Some(opaque) = find_prop!(props, Native) else {
                    violation(command, "a native view needs its Prop::Native")
                };
                let Some(payload) = opaque.downcast_ref::<NativePayload>() else {
                    violation(command, "the native view is not an AppKit one")
                };
                let Some(create) = payload.spec.create.borrow_mut().take() else {
                    violation(command, "this native view was already created")
                };
                let measure = payload.spec.measure.clone();
                let mut cx = AppKitCx::new(mtm, id, self.events.clone(), &mut targets);
                let view = create(&mut cx);
                payload.apply(&view);
                Widget::Native { view, measure, last: opaque }
            }
            WidgetKind::Text => {
                let label = NSTextField::wrappingLabelWithString(&ns(""), mtm);
                label.setSelectable(false);
                Widget::Label(label)
            }
            WidgetKind::Button => {
                Widget::Button(unsafe { NSButton::buttonWithTitle_target_action(&ns(""), target_obj, action, mtm) })
            }
            WidgetKind::Checkbox => {
                Widget::Checkbox(unsafe { NSButton::checkboxWithTitle_target_action(&ns(""), target_obj, action, mtm) })
            }
            WidgetKind::Switch => {
                let switch = NSSwitch::new(mtm);
                unsafe {
                    switch.setTarget(target_obj);
                    switch.setAction(action);
                }
                Widget::Switch(switch)
            }
            WidgetKind::TextInput => {
                // No target-action: submit comes from the delegate (Return
                // only), edits from `controlTextDidChange:`.
                let field = NSTextField::textFieldWithString(&ns(""), mtm);
                if let Some(target) = &target {
                    // SAFETY: the node keeps the target alive as long as the field.
                    unsafe { field.setDelegate(Some(ProtocolObject::from_ref(&**target))) };
                }
                Widget::Field(field)
            }
            WidgetKind::ScrollView => {
                let scroll = NSScrollView::initWithFrame(NSScrollView::alloc(mtm), crate::classes::zero_rect());
                scroll.setDrawsBackground(false);
                scroll.setAutohidesScrollers(true);
                let clip = scroll.contentView();
                clip.setPostsBoundsChangedNotifications(true);
                if let Some(target) = &target {
                    // SAFETY: the target is removed as an observer when the node is destroyed.
                    unsafe {
                        NSNotificationCenter::defaultCenter().addObserver_selector_name_object(
                            target,
                            sel!(scrolled:),
                            Some(NSViewBoundsDidChangeNotification),
                            Some(&clip),
                        );
                    }
                }
                Widget::Scroll(scroll)
            }
            WidgetKind::Fragment => violation(command, "fragments are core-only"),
        };
        // The core assumes new nodes start with a zero frame and only sends
        // frames that differ; AppKit controls come with their own.
        if !matches!(widget, Widget::Window { .. }) {
            widget.view().setFrame(crate::classes::zero_rect());
        }
        self.by_view.borrow_mut().insert(key(widget.view()), id);
        self.nodes.insert(
            id,
            Node { kind, widget, _target: target, _targets: targets, parent: None, text_style: None, variant: None },
        );
    }

    fn set_prop(&mut self, id: NodeId, prop: &Prop, command: &Command) {
        let Some(node) = self.nodes.get_mut(&id) else { violation(command, "node does not exist") };
        match (prop, &mut node.widget) {
            (Prop::Title(t), Widget::Window { window, .. }) => window.setTitle(&ns(t)),
            (Prop::Text(t), Widget::Label(l)) => l.setStringValue(&ns(t)),
            (Prop::Label(t), Widget::Button(b) | Widget::Checkbox(b)) => b.setTitle(&ns(t)),
            (Prop::Label(t), Widget::Switch(s)) => s.setAccessibilityLabel(Some(&ns(t))),
            (Prop::Value(t), Widget::Field(f)) => {
                // Don't disturb the caret when the field already shows it.
                if f.stringValue().to_string() != *t {
                    f.setStringValue(&ns(t));
                }
            }
            (Prop::Placeholder(t), Widget::Field(f)) => f.setPlaceholderString(Some(&ns(t))),
            (Prop::Checked(c), Widget::Checkbox(b)) => {
                b.setState(if *c { NSControlStateValueOn } else { NSControlStateValueOff })
            }
            (Prop::Checked(c), Widget::Switch(s)) => {
                s.setState(if *c { NSControlStateValueOn } else { NSControlStateValueOff })
            }
            (Prop::Enabled(e), w) if w.control().is_some() => w.control().unwrap().setEnabled(*e),
            (Prop::TextStyle(style), w) if w.control().is_some() => {
                w.control().unwrap().setFont(Some(&font(*style)));
                node.text_style = Some(*style);
            }
            (Prop::ScrollAxes(axes), Widget::Scroll(scroll)) => {
                scroll.setHasVerticalScroller(axes.vertical());
                scroll.setHasHorizontalScroller(axes.horizontal());
            }
            (Prop::Variant(variant), Widget::Button(b)) => {
                b.setKeyEquivalent(&ns(if *variant == ButtonVariant::Primary { "\r" } else { "" }));
                b.setHasDestructiveAction(*variant == ButtonVariant::Destructive);
                b.setBordered(*variant != ButtonVariant::Plain);
                node.variant = Some(*variant);
            }
            (Prop::Custom(new), Widget::Custom { view, render, props }) => {
                if props != new {
                    render.update(view, props.props(), new.props());
                    *props = new.clone();
                }
            }
            (Prop::Custom(new), Widget::Drawn { props, .. }) => *props = new.clone(),
            (Prop::Drawing(drawing), Widget::Drawn { view, .. }) => view.set_drawing(drawing.clone()),
            (Prop::Native(opaque), Widget::Native { view, last, .. }) => {
                // The creating payload was applied on creation.
                if opaque != last
                    && let Some(payload) = opaque.downcast_ref::<NativePayload>()
                {
                    payload.apply(view);
                }
                *last = opaque.clone();
            }
            _ => {}
        }
    }

    fn view(&self, id: NodeId, command: &Command) -> Retained<NSView> {
        match self.nodes.get(&id) {
            Some(node) => node.widget.view().retain(),
            None => violation(command, &format!("node {id} does not exist")),
        }
    }

    fn apply(&mut self, command: &Command) {
        match command {
            Command::Create { id, kind, props } => {
                if self.nodes.contains_key(id) {
                    violation(command, "node already exists");
                }
                self.create(*id, *kind, command);
                for prop in props {
                    self.set_prop(*id, prop, command);
                }
            }
            Command::SetProp { id, prop } => self.set_prop(*id, prop, command),
            Command::Insert { parent, child, index } => {
                let parent_view = self.view(*parent, command);
                let child_view = self.view(*child, command);
                if self.nodes[child].parent.is_some() {
                    violation(command, "child is still attached");
                }
                if let Widget::Scroll(scroll) = &self.nodes[parent].widget {
                    if scroll.documentView().is_some() {
                        violation(command, "a ScrollView has a single native child (its content)");
                    }
                    scroll.setDocumentView(Some(&child_view));
                    self.nodes.get_mut(child).unwrap().parent = Some(*parent);
                    return;
                }
                let siblings = parent_view.subviews();
                if *index >= siblings.len() {
                    parent_view.addSubview(&child_view);
                } else {
                    let before = siblings.objectAtIndex(*index);
                    parent_view.addSubview_positioned_relativeTo(
                        &child_view,
                        NSWindowOrderingMode::Below,
                        Some(&before),
                    );
                }
                self.nodes.get_mut(child).unwrap().parent = Some(*parent);
            }
            Command::Remove { parent, child } => {
                if self.nodes.get(child).and_then(|n| n.parent) != Some(*parent) {
                    violation(command, "not a child of this parent");
                }
                match &self.nodes[parent].widget {
                    Widget::Scroll(scroll) => scroll.setDocumentView(None),
                    _ => self.view(*child, command).removeFromSuperview(),
                }
                self.nodes.get_mut(child).unwrap().parent = None;
            }
            Command::Destroy { id } => {
                let Some(node) = self.nodes.remove(id) else { violation(command, "node does not exist") };
                self.by_view.borrow_mut().remove(&key(node.widget.view()));
                self.pending_show.retain(|w| w != id);
                self.focus_orders.remove(id);
                if let Some(target) = &node._target {
                    unsafe { NSNotificationCenter::defaultCenter().removeObserver(target) };
                }
                match &node.widget {
                    Widget::Window { window, _delegate, .. } => {
                        _delegate.stop_observing_focus(window);
                        window.setDelegate(None);
                        window.close();
                    }
                    widget => widget.view().removeFromSuperview(),
                }
            }
            Command::SetFrame { id, frame } => {
                let view = self.view(*id, command);
                view.setFrame(NSRect::new(
                    NSPoint::new(frame.x() as f64, frame.y() as f64),
                    NSSize::new(frame.width() as f64, frame.height() as f64),
                ));
            }
            Command::SetA11y { id, a11y } => {
                let view = self.view(*id, command);
                let A11yProps { label, description, hidden, .. } = a11y;
                view.setAccessibilityLabel(label.as_deref().map(ns).as_deref());
                view.setAccessibilityHelp(description.as_deref().map(ns).as_deref());
                if *hidden {
                    view.setAccessibilityElement(false);
                }
            }
            Command::SetWindowSize { id, size } => match self.nodes.get(id).map(|n| &n.widget) {
                Some(Widget::Window { window, .. }) => {
                    window.setContentSize(NSSize::new(size.width as f64, size.height as f64))
                }
                _ => violation(command, "not a window"),
            },
            Command::SetFocusOrder { window, order } => {
                let ns_window = match self.nodes.get(window).map(|n| &n.widget) {
                    Some(Widget::Window { window, .. }) => window.clone(),
                    _ => violation(command, "not a window"),
                };
                // Unlink the previous chain, then link the new one as a loop.
                // AppKit still skips views that can't take focus right now
                // (disabled, or not reachable under the user's keyboard
                // navigation setting).
                for old in self.focus_orders.remove(window).unwrap_or_default() {
                    if let Some(node) = self.nodes.get(&old) {
                        unsafe { node.widget.view().setNextKeyView(None) };
                    }
                }
                let views: Vec<Retained<NSView>> = order.iter().map(|id| self.view(*id, command)).collect();
                for (i, view) in views.iter().enumerate() {
                    let next = &views[(i + 1) % views.len()];
                    unsafe { view.setNextKeyView(Some(next)) };
                }
                ns_window.setInitialFirstResponder(views.first().map(|v| &**v));
                self.focus_orders.insert(*window, order.clone());
            }
            Command::ScrollTo { id, offset } => match self.nodes.get(id).map(|n| &n.widget) {
                Some(Widget::Scroll(scroll)) => scroll_to(scroll, NSPoint::new(offset.x as f64, offset.y as f64)),
                _ => violation(command, "not a ScrollView"),
            },
            Command::Focus { id } => {
                let view = self.view(*id, command);
                if let Some(window) = view.window() {
                    window.makeFirstResponder(Some(&view));
                }
            }
        }
    }
}

/// Scrolls like the user would, so the clip view reports the change.
fn scroll_to(scroll: &NSScrollView, origin: NSPoint) {
    let clip = scroll.contentView();
    clip.scrollToPoint(origin);
    scroll.reflectScrolledClipView(&clip);
}

fn focused(widget: &Widget) -> bool {
    let view = widget.view();
    let Some(responder) = view.window().and_then(|w| w.firstResponder()) else { return false };
    match widget {
        // While editing, the window's field editor is first responder.
        Widget::Field(field) => field.currentEditor().is_some(),
        _ => std::ptr::eq(&*responder as *const _ as *const NSView, view as *const NSView),
    }
}

fn ceil_size(size: NSSize) -> Size {
    Size::new(size.width.ceil() as f32, size.height.ceil() as f32)
}

/// The object assistive technology acts on for a view: the view itself, or
/// for views that aren't accessibility elements (an `NSStepper`), their
/// single accessibility child (its cell), as VoiceOver finds it.
fn a11y_element(view: &NSView) -> Retained<AnyObject> {
    let mut element: Retained<AnyObject> = view.retain().into();
    loop {
        let is_element: bool = unsafe { msg_send![&*element, isAccessibilityElement] };
        let children: Option<Retained<NSArray<AnyObject>>> = unsafe { msg_send![&*element, accessibilityChildren] };
        match children {
            Some(children) if !is_element && children.len() == 1 => element = children.objectAtIndex(0),
            _ => return element,
        }
    }
}

/// `intrinsicContentSize`, with "no intrinsic size" (-1) as zero.
fn intrinsic(view: &NSView) -> Size {
    let size = view.intrinsicContentSize();
    ceil_size(NSSize::new(size.width.max(0.0), size.height.max(0.0)))
}

impl Backend for AppKitBackend {
    fn init(&mut self, events: EventSink) {
        self.state.borrow_mut().events = events;
    }

    fn metrics(&self) -> PlatformMetrics {
        metrics(self.state.borrow().mtm)
    }

    fn apply(&mut self, batch: &[Command]) {
        let mut state = self.state.borrow_mut();
        for command in batch {
            if state.options.record_commands {
                state.log.push(command.clone());
            }
            state.apply(command);
        }
    }

    fn measure(&mut self, id: NodeId, request: MeasureRequest) -> Size {
        let state = self.state.borrow();
        let Some(node) = state.nodes.get(&id) else { return Size::ZERO };
        let natural = match &node.widget {
            Widget::Label(label) => {
                // TODO: min-content (longest word) — until then text never
                // shrinks below its single-line width in flex rows.
                let width = request.known_width.map(f64::from).or(match request.available_width {
                    AvailableSpace::Definite(w) => Some(w as f64),
                    AvailableSpace::MinContent | AvailableSpace::MaxContent => None,
                });
                let bounds = NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(width.unwrap_or(1.0e7), 1.0e7));
                match label.cell() {
                    Some(cell) => ceil_size(cell.cellSizeForBounds(bounds)),
                    None => Size::ZERO,
                }
            }
            Widget::Field(field) => {
                let intrinsic = field.intrinsicContentSize();
                Size::new(
                    if intrinsic.width > 0.0 { intrinsic.width.ceil() as f32 } else { 200.0 },
                    intrinsic.height.ceil() as f32,
                )
            }
            Widget::Button(v) | Widget::Checkbox(v) => ceil_size(v.intrinsicContentSize()),
            Widget::Switch(v) => ceil_size(v.intrinsicContentSize()),
            Widget::Custom { view, render, props } => {
                render.measure(view, props.props(), &request).unwrap_or_else(|| intrinsic(view))
            }
            Widget::Native { view, measure, .. } => match measure {
                Some(measure) => measure(view, &request),
                None => intrinsic(view),
            },
            // Measured by the core.
            Widget::Drawn { .. } | Widget::Window { .. } | Widget::Host(_) | Widget::Scroll(_) => Size::ZERO,
        };
        Size::new(request.known_width.unwrap_or(natural.width), request.known_height.unwrap_or(natural.height))
    }

    fn perform(&mut self, id: NodeId, action: &A11yAction) -> Result<(), ActionError> {
        let (widget_view, control_enabled, kind, events, custom) = {
            let state = self.state.borrow();
            let node = state.nodes.get(&id).ok_or(ActionError::UnknownNode)?;
            let custom = match &node.widget {
                Widget::Custom { render, props, .. } => Some((render.clone(), props.props().clone())),
                _ => None,
            };
            let enabled = node.widget.control().map(|c| c.isEnabled());
            (node.widget.view().retain(), enabled, node.kind, state.events.clone(), custom)
        };
        if control_enabled == Some(false) {
            return Err(ActionError::Disabled);
        }
        if let Some((render, props)) = custom {
            return render.perform(&widget_view, &props, action, &Emitter::new(events, id));
        }
        // No state borrow below: AppKit calls back into our targets.
        match (action, kind) {
            (A11yAction::Activate, WidgetKind::Button | WidgetKind::Checkbox | WidgetKind::Switch) => {
                // The press action assistive technology uses. Its return
                // value is unreliable for windows that aren't on screen (it
                // reports NO after pressing), so it is ignored.
                let _: bool = unsafe { msg_send![&*widget_view, accessibilityPerformPress] };
            }
            // Native views: whatever their accessibility element does.
            // Return values are ignored for the same reason as above.
            (A11yAction::Activate, WidgetKind::Native) => {
                let _: bool = unsafe { msg_send![&*a11y_element(&widget_view), accessibilityPerformPress] };
            }
            (A11yAction::Increment, WidgetKind::Native) => {
                let _: bool = unsafe { msg_send![&*a11y_element(&widget_view), accessibilityPerformIncrement] };
            }
            (A11yAction::Decrement, WidgetKind::Native) => {
                let _: bool = unsafe { msg_send![&*a11y_element(&widget_view), accessibilityPerformDecrement] };
            }
            (A11yAction::SetValue(text), WidgetKind::TextInput) => {
                let field: &NSTextField = widget_view.downcast_ref().ok_or(ActionError::Unsupported)?;
                field.setStringValue(&ns(text));
                // Programmatic edits don't notify the delegate; assistive
                // technology edits are user edits, so report one.
                events.emit(id, UiEvent::Changed(EventValue::Text(text.clone())));
            }
            (A11yAction::Focus, _) => {
                let window = widget_view.window().ok_or(ActionError::Unsupported)?;
                if !window.makeFirstResponder(Some(&widget_view)) {
                    return Err(ActionError::Unsupported);
                }
                // The window delegate reports the focus change.
            }
            (A11yAction::ScrollIntoView, _) => {}
            _ => return Err(ActionError::Unsupported),
        }
        Ok(())
    }

    fn synthesize(&mut self, id: NodeId, input: &SyntheticInput) -> Result<(), ActionError> {
        if let SyntheticInput::Click(point) = input {
            // Drawn widgets only: native controls track the mouse in a
            // loop of their own, waiting for real events.
            let view = match self.state.borrow().nodes.get(&id).map(|n| &n.widget) {
                Some(Widget::Drawn { view, .. }) => view.clone(),
                Some(_) => return Err(ActionError::Unsupported),
                None => return Err(ActionError::UnknownNode),
            };
            let window = view.window().ok_or(ActionError::Unsupported)?;
            let location = view.convertPoint_toView(NSPoint::new(point.x as f64, point.y as f64), None);
            for (kind, up) in [(NSEventType::LeftMouseDown, false), (NSEventType::LeftMouseUp, true)] {
                let event = NSEvent::mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure(
                    kind,
                    location,
                    NSEventModifierFlags::empty(),
                    0.0,
                    window.windowNumber(),
                    None,
                    0,
                    1,
                    if up { 0.0 } else { 1.0 },
                )
                .ok_or(ActionError::Unsupported)?;
                if up { view.mouseUp(&event) } else { view.mouseDown(&event) }
            }
            return Ok(());
        }
        if let SyntheticInput::Scroll { dx, dy } = input {
            let scroll = match self.state.borrow().nodes.get(&id).map(|n| &n.widget) {
                Some(Widget::Scroll(scroll)) => scroll.clone(),
                Some(_) => return Err(ActionError::Unsupported),
                None => return Err(ActionError::UnknownNode),
            };
            let clip = scroll.contentView();
            let visible = clip.bounds();
            let content = scroll.documentView().map_or(visible.size, |d| d.frame().size);
            let clamp = |v: f64, content: f64, visible: f64, on: bool| {
                if on { v.clamp(0.0, (content - visible).max(0.0)) } else { 0.0 }
            };
            let origin = NSPoint::new(
                clamp(visible.origin.x + *dx as f64, content.width, visible.size.width, scroll.hasHorizontalScroller()),
                clamp(visible.origin.y + *dy as f64, content.height, visible.size.height, scroll.hasVerticalScroller()),
            );
            scroll_to(&scroll, origin);
            return Ok(());
        }
        let SyntheticInput::Key(key) = input else { unreachable!() };
        let (view, kind) = {
            let state = self.state.borrow();
            let node = state.nodes.get(&id).ok_or(ActionError::UnknownNode)?;
            if node.widget.control().is_some_and(|c| !c.isEnabled()) {
                return Err(ActionError::Disabled);
            }
            (node.widget.view().retain(), node.kind)
        };
        match (kind, key) {
            (WidgetKind::TextInput, Key::Char(_) | Key::Backspace | Key::Enter | Key::Tab) => {
                // Drive the field editor, the object that receives real
                // keystrokes: text goes through `insertText:`, and editing
                // keys through `doCommandBySelector:`, which is what
                // `interpretKeyEvents:` does, delegate hooks included.
                let window = view.window().ok_or(ActionError::Unsupported)?;
                let field: &NSTextField = view.downcast_ref().ok_or(ActionError::Unsupported)?;
                let just_focused = field.currentEditor().is_none();
                if just_focused {
                    window.makeFirstResponder(Some(&view));
                }
                let editor = field.currentEditor().ok_or(ActionError::Unsupported)?;
                if just_focused {
                    // Focusing selects everything; typing should append, as
                    // after clicking past the end of the text.
                    let end = editor.string().length();
                    editor.setSelectedRange(NSRange::new(end, 0));
                }
                let command = match key {
                    Key::Char(c) => {
                        let text = ns(&c.to_string());
                        let _: () = unsafe { msg_send![&*editor, insertText: &*text] };
                        return Ok(());
                    }
                    Key::Backspace => sel!(deleteBackward:),
                    Key::Enter => sel!(insertNewline:),
                    _ => sel!(insertTab:),
                };
                unsafe { editor.doCommandBySelector(command) };
                Ok(())
            }
            (WidgetKind::Button, Key::Enter | Key::Char(' '))
            | (WidgetKind::Checkbox | WidgetKind::Switch, Key::Char(' ')) => self.perform(id, &A11yAction::Activate),
            _ => Err(ActionError::Unsupported),
        }
    }

    fn native_state(&self, id: NodeId) -> Option<NativeState> {
        let state = self.state.borrow();
        let node = state.nodes.get(&id)?;
        let mut props = Vec::new();
        let checked = |s: isize| Prop::Checked(s == NSControlStateValueOn);
        match &node.widget {
            Widget::Window { window, .. } => props.push(Prop::Title(window.title().to_string())),
            Widget::Label(l) => props.push(Prop::Text(l.stringValue().to_string())),
            Widget::Field(f) => {
                props.push(Prop::Value(f.stringValue().to_string()));
                if let Some(p) = f.placeholderString() {
                    props.push(Prop::Placeholder(p.to_string()));
                }
            }
            Widget::Button(b) => props.push(Prop::Label(b.title().to_string())),
            Widget::Checkbox(b) => {
                props.push(Prop::Label(b.title().to_string()));
                props.push(checked(b.state()));
            }
            Widget::Switch(s) => {
                if let Some(label) = s.accessibilityLabel() {
                    props.push(Prop::Label(label.to_string()));
                }
                props.push(checked(s.state()));
            }
            Widget::Scroll(scroll) => {
                props.push(Prop::ScrollAxes(match (scroll.hasHorizontalScroller(), scroll.hasVerticalScroller()) {
                    (true, true) => ScrollAxes::Both,
                    (true, false) => ScrollAxes::Horizontal,
                    _ => ScrollAxes::Vertical,
                }))
            }
            Widget::Custom { view, render, props: last } => {
                props.push(Prop::Custom(last.with_props(render.read(view, last.props()))))
            }
            Widget::Drawn { view, props: last } => {
                props.push(Prop::Custom(last.clone()));
                props.push(Prop::Drawing(view.drawing()));
            }
            Widget::Native { last, .. } => props.push(Prop::Native(last.clone())),
            Widget::Host(_) => {}
        }
        if let Some(control) = node.widget.control() {
            props.push(Prop::Enabled(control.isEnabled()));
        }
        props.extend(node.text_style.map(Prop::TextStyle));
        props.extend(node.variant.map(Prop::Variant));
        let view = node.widget.view();
        let f = view.frame();
        let by_view = state.by_view.borrow();
        let (children, scroll_offset) = match &node.widget {
            Widget::Scroll(scroll) => {
                let origin = scroll.contentView().bounds().origin;
                (
                    scroll.documentView().and_then(|d| by_view.get(&key(&d)).copied()).into_iter().collect(),
                    Some(Point::new(origin.x as f32, origin.y as f32)),
                )
            }
            _ => (view.subviews().iter().filter_map(|v| by_view.get(&key(&v)).copied()).collect(), None),
        };
        Some(NativeState {
            kind: node.kind,
            props,
            frame: Rect::new(f.origin.x as f32, f.origin.y as f32, f.size.width as f32, f.size.height as f32),
            parent: node.parent,
            children,
            focused: focused(&node.widget),
            scroll_offset,
        })
    }

    fn services(&self) -> Box<dyn mitsuami_core::services::Services> {
        let state = self.state.borrow();
        Box::new(crate::services::AppKitServices::new(state.mtm, self.handle(), state.options.private_clipboard))
    }

    fn capture(&mut self, id: NodeId, reply: mitsuami_core::services::Reply<Result<Image, CaptureError>>) {
        // Drawing into a bitmap is synchronous on AppKit: answer right away.
        reply(self.capture_now(id));
    }
}

impl AppKitBackend {
    fn capture_now(&self, id: NodeId) -> Result<Image, CaptureError> {
        let view = {
            let state = self.state.borrow();
            state.nodes.get(&id).ok_or(CaptureError::UnknownNode)?.widget.view().retain()
        };
        let bounds = view.bounds();
        let rep = view
            .bitmapImageRepForCachingDisplayInRect(bounds)
            .ok_or_else(|| CaptureError::Failed("no bitmap for view".into()))?;
        view.cacheDisplayInRect_toBitmapImageRep(bounds, &rep);
        let (width, height) = (rep.pixelsWide() as usize, rep.pixelsHigh() as usize);
        let (samples, bits, row) = (rep.samplesPerPixel() as usize, rep.bitsPerSample(), rep.bytesPerRow() as usize);
        if bits != 8 || !(samples == 3 || samples == 4) {
            return Err(CaptureError::Failed(format!("unsupported bitmap: {samples} samples × {bits} bits")));
        }
        let alpha_first = rep.bitmapFormat().contains(NSBitmapFormat::AlphaFirst);
        let data = rep.bitmapData();
        if data.is_null() {
            return Err(CaptureError::Failed("bitmap has no data".into()));
        }
        let bytes = unsafe { std::slice::from_raw_parts(data, row * height) };
        let mut rgba = Vec::with_capacity(width * height * 4);
        for y in 0..height {
            for x in 0..width {
                let p = &bytes[y * row + x * samples..][..samples];
                let [r, g, b, a] = match (samples, alpha_first) {
                    (4, true) => [p[1], p[2], p[3], p[0]],
                    (4, false) => [p[0], p[1], p[2], p[3]],
                    _ => [p[0], p[1], p[2], 255],
                };
                rgba.extend_from_slice(&[r, g, b, a]);
            }
        }
        let scale = if bounds.size.width > 0.0 { width as f32 / bounds.size.width as f32 } else { 1.0 };
        Ok(Image { width: width as u32, height: height as u32, scale_factor: scale, rgba })
    }
}