mitsuami-appkit 2.5.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
//! Setting props on the native widgets.

use mitsuami_core::{
    ButtonRole, ButtonStyle, Command, EventSink, HorizontalAlign, ImageFit, InputPurpose, LayoutDirection, NodeId,
    Prop, Truncation, UiEvent, WidgetKind,
};
use objc2::rc::Retained;
use objc2::runtime::{NSObjectProtocol, ProtocolObject};
use objc2::{MainThreadMarker, MainThreadOnly, msg_send, sel};
use objc2_app_kit::{
    NSAccessibility, NSButton, NSColor, NSControlStateValueMixed, NSControlStateValueOff, NSControlStateValueOn,
    NSImageScaling, NSLineBreakMode, NSMenu, NSMenuItem, NSProgressIndicatorStyle, NSSlider, NSTextAlignment,
    NSTextContent, NSTextContentType, NSTextContentTypeEmailAddress, NSTextContentTypeTelephoneNumber,
    NSTextContentTypeURL, NSTextField, NSUserInterfaceLayoutDirection, NSView, NSWindowStyleMask,
};

use crate::classes::ClosureTarget;
use crate::custom::NativePayload;
use crate::services::ItemTarget;

use super::fonts::{font, label_font};
use super::group::set_group_title;
use super::images::{FILE_ICON_SIZE, icon_image, image_position, ns_image, show_file_icon};
use super::menus::{pull_down_title, show_pull_down};
use super::scrolling::set_scrollers;
use super::{State, Widget, ns, violation};

impl State {
    pub(super) fn set_prop(&mut self, id: NodeId, prop: &Prop, command: &Command) {
        let mtm = self.mtm;
        let events = self.events.clone();
        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::Title(t), Widget::Group { frame, .. }) => set_group_title(frame, t),
            // Side by side is AppKit's vertical divider.
            (Prop::Orientation(o), Widget::SplitView(split)) => split.turn(!o.vertical()),
            (Prop::Number(position), Widget::SplitView(split)) => split.set_position(*position),
            (Prop::PaneMinimums(minimums), Widget::SplitView(split)) => split.set_minimums(*minimums),
            (Prop::PanesShown(shown), Widget::SplitView(split)) => split.set_shown(*shown),
            (Prop::FileDrop(drop), Widget::Host(host) | Widget::Group { host, .. }) => {
                host.set_file_drop(drop.clone().map(|files| crate::classes::Drop {
                    id,
                    files,
                    events: events.clone(),
                    hover: Default::default(),
                }));
                node.file_drop = true;
            }
            (Prop::Keys(keys), Widget::Host(host) | Widget::Group { host, .. }) => {
                host.set_keys(Some(crate::keys::Keys { id, keys: keys.clone(), events: events.clone() }));
            }
            (Prop::Keys(keys), Widget::List(list)) => list.set_keys(keys.clone()),
            (Prop::Keys(keys), Widget::Field(_)) => {
                if let Some(target) = &node._target {
                    target.set_keys(keys.clone());
                }
            }
            (Prop::FullScreen(on), Widget::Window { window, _delegate, .. }) => _delegate.set_full_screen(window, *on),
            // AppKit's maximize is zoom: the title bar's green button with
            // Option, or a double-click on the title bar.
            (Prop::Maximized(on), Widget::Window { window, _delegate, .. }) => _delegate.set_zoomed(window, *on),
            (Prop::Frame(frame), Widget::Window { window, _delegate, .. }) => _delegate.set_frame(window, *frame),
            // A new window is centred either way: AppKit's own place for
            // one is the screen's bottom-left corner.
            (Prop::Placement(placement), Widget::Window { _delegate, .. }) => _delegate.set_placement(*placement),
            (Prop::Resizable(on), Widget::Window { window, .. }) => {
                let mask = window.styleMask();
                window.setStyleMask(if *on {
                    mask | NSWindowStyleMask::Resizable
                } else {
                    mask & !NSWindowStyleMask::Resizable
                });
            }
            (Prop::MinSize(min), Widget::Window { window, _delegate, .. }) => _delegate.set_min_size(window, *min),
            (Prop::HeightFollowsContent(on), Widget::Window { window, _delegate, .. }) => {
                _delegate.set_height_locked(window, *on)
            }
            // Acted on when the window is shown.
            (Prop::Modal { owner, modality }, Widget::Window { _delegate, .. }) => {
                _delegate.set_modal(true);
                node.modal = Some((*owner, *modality));
            }
            (Prop::Text(t), Widget::Label(l)) => l.setStringValue(&ns(t)),
            (Prop::Selectable(on), Widget::Label(l)) => l.setSelectable(*on),
            (Prop::MaxLines(lines), Widget::Label(l)) => set_line_limit(l, *lines, node.truncation.unwrap_or_default()),
            (Prop::Truncation(truncation), Widget::Label(l)) => {
                node.truncation = Some(*truncation);
                let lines = l.maximumNumberOfLines();
                set_line_limit(l, (lines > 0).then_some(lines as u32), *truncation);
            }
            (Prop::Label(t), Widget::Checkbox(b)) => b.setTitle(&ns(t)),
            // A new title puts the image back beside it: an icon shown
            // alone stays so.
            (Prop::Label(t), Widget::Button(b)) => {
                b.setTitle(&ns(t));
                if node.icon.is_some() {
                    b.setImagePosition(image_position(node.icon_only));
                }
            }
            (Prop::Label(t), Widget::Switch(s)) => s.setAccessibilityLabel(Some(&ns(t))),
            (Prop::Label(t), Widget::Select(p)) => p.setAccessibilityLabel(Some(&ns(t))),
            (Prop::Label(t), Widget::RadioGroup(group)) => group.stack.setAccessibilityLabel(Some(&ns(t))),
            (Prop::Options(options), Widget::RadioGroup(group)) => group.set_options(options),
            (Prop::SelectedIndex(index), Widget::RadioGroup(group)) => group.set_selected(*index),
            (Prop::Enabled(e), Widget::RadioGroup(group)) => group.set_enabled(*e),
            // A menu built as it opens: what was built goes into the menu
            // showing, which holds it already when AppKit asked for it.
            (Prop::Menu(entries), Widget::MenuButton { popup, sent, opener: Some(opener), .. }) => {
                *sent = entries.clone();
                if let Some(menu) = popup.menu() {
                    opener.fill(&menu, entries);
                }
            }
            (Prop::MenuOnOpen(on_open), Widget::MenuButton { popup, target, sent, opener }) => match (on_open, &opener)
            {
                (Some(on_open), Some(opener)) => opener.set(on_open.clone()),
                (Some(on_open), None) => {
                    let new = crate::classes::MenuOpener::new(mtm, on_open.clone(), target.clone(), 1);
                    if let Some(menu) = popup.menu() {
                        new.adopt(&menu, sent);
                    }
                    *opener = Some(new);
                }
                (None, _) => {
                    if opener.take().is_some()
                        && let Some(menu) = popup.menu()
                    {
                        menu.setDelegate(None);
                    }
                }
            },
            (
                Prop::Label(_) | Prop::Icon(_) | Prop::VectorIcon(_) | Prop::IconOnly(_) | Prop::Menu(_),
                Widget::MenuButton { .. },
            ) => {
                match prop {
                    Prop::Icon(name) => node.icon = Some(name.clone()),
                    Prop::VectorIcon(icon) => node.vector_icon = Some(icon.clone()),
                    Prop::IconOnly(only) => node.icon_only = Some(*only),
                    Prop::Menu(entries) => {
                        if let Widget::MenuButton { sent, .. } = &mut node.widget {
                            *sent = entries.clone();
                        }
                    }
                    _ => {}
                }
                let label = match prop {
                    Prop::Label(t) => t.clone(),
                    _ => pull_down_title(&node.widget),
                };
                let icon = icon_image(node.icon.as_deref(), node.vector_icon.clone().flatten().as_ref(), None, None);
                show_pull_down(&node.widget, &label, icon, node.icon_only);
            }
            (
                Prop::Label(_) | Prop::Icon(_) | Prop::VectorIcon(_) | Prop::IconOnly(_) | Prop::Menu(_),
                Widget::SplitButton(_),
            ) => {
                let Widget::SplitButton(button) = &mut node.widget else { unreachable!() };
                let mut title = button.title();
                match prop {
                    Prop::Label(t) => title = t.clone(),
                    Prop::Icon(name) => node.icon = Some(name.clone()),
                    Prop::VectorIcon(icon) => node.vector_icon = Some(icon.clone()),
                    Prop::IconOnly(only) => node.icon_only = Some(*only),
                    Prop::Menu(entries) => button.sent = entries.clone(),
                    _ => {}
                }
                let icon = icon_image(node.icon.as_deref(), node.vector_icon.clone().flatten().as_ref(), None, None);
                button.show(&title, icon, node.icon_only == Some(true));
            }
            // A combo button has one look: kept for the app.
            (Prop::ButtonStyle(style), Widget::SplitButton(_)) => node.button_style = Some(*style),
            (Prop::ButtonStyle(style), Widget::MenuButton { popup, .. }) => {
                popup.setBordered(*style != ButtonStyle::Borderless);
                // A borderless pull-down draws its template image in the
                // label colour, a borderless button in the secondary one
                // (85% and 55% white on dark, measured): side by side in a
                // toolbar, the pull-down looked pressed. It takes the
                // button's grey; an icon in a colour isn't a template.
                let tint = (*style == ButtonStyle::Borderless).then(objc2_app_kit::NSColor::secondaryLabelColor);
                popup.setContentTintColor(tint.as_deref());
                set_prominent(popup, *style == ButtonStyle::Prominent);
                node.button_style = Some(*style);
            }
            (Prop::Options(options), Widget::Select(p)) => {
                // Items go straight into the menu: `addItemWithTitle:`
                // drops earlier items with the same title. The chosen index
                // stays if it can, else the first option is chosen, as the
                // core does; it sends the index when that changes it.
                let chosen = p.indexOfSelectedItem();
                p.removeAllItems();
                if let Some(menu) = p.menu() {
                    for option in options {
                        let item = unsafe {
                            NSMenuItem::initWithTitle_action_keyEquivalent(
                                NSMenuItem::alloc(mtm),
                                &ns(option),
                                None,
                                &ns(""),
                            )
                        };
                        menu.addItem(&item);
                    }
                }
                let count = p.numberOfItems();
                p.selectItemAtIndex(if (0..count).contains(&chosen) {
                    chosen
                } else if count > 0 {
                    0
                } else {
                    -1
                });
            }
            (Prop::SelectedIndex(index), Widget::Select(p)) => {
                p.selectItemAtIndex(index.map_or(-1, |i| i as isize));
            }
            (Prop::Sections(sections), Widget::Sidebar(sidebar)) => sidebar.set_sections(sections.clone()),
            (Prop::SelectedIndex(index), Widget::Sidebar(sidebar)) => sidebar.set_selected(*index),
            // Applied to the window's split, once it has one.
            (Prop::SidebarShown(on), Widget::Sidebar(sidebar)) => sidebar.shown.set(Some(*on)),
            (Prop::TabTitles(titles), Widget::Tabs(tabs)) => tabs.set_titles(titles.clone()),
            // An `NSTabView` draws only titles: its items' images are for
            // a tab view controller's toolbar style. Kept for the mirror.
            (Prop::TabIcons(icons), Widget::Tabs(_)) => node.tab_icons = Some(icons.clone()),
            // One way to show tabs: the app's choice is kept, not shown.
            (Prop::TabsStyle(style), Widget::Tabs(_)) => node.tabs_style = Some(*style),
            (Prop::SelectedIndex(index), Widget::Tabs(tabs)) => tabs.set_shown(*index),
            (Prop::TabTitles(titles), Widget::DocumentTabs(tabs)) => tabs.set_titles(titles.clone()),
            (Prop::SelectedIndex(index), Widget::DocumentTabs(tabs)) => tabs.set_selected(*index),
            (Prop::TabsClosable(on), Widget::DocumentTabs(tabs)) => tabs.set_closable(*on),
            (Prop::TabsReorderable(on), Widget::DocumentTabs(tabs)) => tabs.set_reorderable(*on),
            (Prop::NewTabButton(on), Widget::DocumentTabs(tabs)) => tabs.set_new_tab(*on),
            (Prop::DocumentTabsStyle(style), Widget::DocumentTabs(tabs)) => tabs.set_style(*style),
            (Prop::Enabled(e), Widget::DocumentTabs(tabs)) => tabs.set_enabled(*e),
            (Prop::Label(t), Widget::Slider { slider, .. }) => slider.setAccessibilityLabel(Some(&ns(t))),
            (Prop::Range { min, max }, Widget::Slider { slider, step }) => {
                slider.setMinValue(*min);
                slider.setMaxValue(*max);
                set_ticks(slider, *step, node._target.as_deref());
            }
            (Prop::Step(new), Widget::Slider { slider, step }) => {
                *step = *new;
                set_ticks(slider, *new, node._target.as_deref());
            }
            (Prop::Number(n), Widget::Slider { slider, .. }) => slider.setDoubleValue(*n),
            (Prop::Orientation(o), Widget::Separator(_)) => node.orientation = Some(*o),
            (Prop::Orientation(o), Widget::Slider { slider, .. }) => {
                slider.setVertical(o.vertical());
                node.orientation = Some(*o);
            }
            (Prop::Label(t), Widget::ColorWell(well)) => well.setAccessibilityLabel(Some(&ns(t))),
            (Prop::ColorValue(color), Widget::ColorWell(well)) => well.setColor(&crate::custom::ns_color(*color)),
            (Prop::Label(t), Widget::NumberInput(n)) => {
                n.field().setAccessibilityLabel(Some(&ns(t)));
                n.stepper().setAccessibilityLabel(Some(&ns(t)));
            }
            // The stepper holds the number; the field shows it. A new range
            // may clamp the number, which the core sends again after it.
            (Prop::Range { min, max }, Widget::NumberInput(n)) => {
                n.stepper().setMinValue(*min);
                n.stepper().setMaxValue(*max);
                n.show_number();
            }
            (Prop::Step(step), Widget::NumberInput(n)) => n.stepper().setIncrement(step.unwrap_or(1.0)),
            // On by default: AppKit's stepper wraps unless it's turned off.
            (Prop::WrapAround(on), Widget::NumberInput(n)) => n.stepper().setValueWraps(*on),
            (Prop::Number(v), Widget::NumberInput(n)) => {
                n.stepper().setDoubleValue(*v);
                n.show_number();
            }
            (Prop::Enabled(e), Widget::NumberInput(n)) => n.controls().iter().for_each(|c| c.setEnabled(*e)),
            (Prop::Image(source), Widget::Image(view)) => {
                view.setImage(ns_image(source).as_deref());
                node.image = Some(source.clone());
            }
            (Prop::ImageFit(fit), Widget::Image(view)) => {
                view.setImageScaling(match fit {
                    ImageFit::Contain => NSImageScaling::ScaleProportionallyUpOrDown,
                    ImageFit::Stretch => NSImageScaling::ScaleAxesIndependently,
                });
                node.fit = Some(*fit);
            }
            (Prop::Label(t), Widget::Image(view) | Widget::Icon(view) | Widget::FileIcon(view)) => {
                view.setAccessibilityLabel(Some(&ns(t)))
            }
            (Prop::File(_) | Prop::IconSize(_) | Prop::Thumbnail(_) | Prop::FileLookup(_), Widget::FileIcon(view)) => {
                match prop {
                    Prop::File(path) => node.file = Some(path.clone()),
                    Prop::IconSize(points) => node.icon_size = Some(*points),
                    Prop::Thumbnail(on) => node.thumbnail = Some(*on),
                    Prop::FileLookup(lookup) => node.file_lookup = Some(*lookup),
                    _ => {}
                }
                // A new icon loads once its props are all in (`load_file_icon`):
                // each would read the file's icon again, and ask QuickLook again.
                if !matches!(command, Command::Create { .. }) {
                    let side = node.icon_size.unwrap_or(FILE_ICON_SIZE);
                    let lookup = node.file_lookup.unwrap_or_default();
                    show_file_icon(mtm, view, node.file.as_deref(), side, node.thumbnail == Some(true), lookup);
                }
            }
            (Prop::Icon(_) | Prop::VectorIcon(_) | Prop::IconSize(_), Widget::Icon(view)) => {
                match prop {
                    Prop::Icon(name) => node.icon = Some(name.clone()),
                    Prop::VectorIcon(icon) => node.vector_icon = Some(icon.clone()),
                    Prop::IconSize(points) => node.icon_size = Some(*points),
                    _ => {}
                }
                let vector = node.vector_icon.clone().flatten();
                view.setImage(icon_image(node.icon.as_deref(), vector.as_ref(), node.icon_size, None).as_deref());
            }
            // Tints the symbol, as a template image; images in colour keep
            // theirs.
            (Prop::TextColor(color), Widget::Icon(view)) => {
                node.text_color = Some(*color);
                view.setContentTintColor(Some(&crate::custom::ns_color(*color)));
            }
            // The button sizes the symbol for its bezel and font, before
            // its title unless it shows only the image. In a colour, the
            // image is in it: AppKit tints only borderless buttons' images,
            // and a tinted toggle looks the same pressed or not.
            (Prop::Icon(_) | Prop::VectorIcon(_) | Prop::TextColor(_), Widget::Button(b)) => {
                match prop {
                    Prop::Icon(name) => node.icon = Some(name.clone()),
                    Prop::VectorIcon(icon) => node.vector_icon = Some(icon.clone()),
                    Prop::TextColor(color) => node.text_color = Some(*color),
                    _ => {}
                }
                let vector = node.vector_icon.clone().flatten();
                b.setImage(icon_image(node.icon.as_deref(), vector.as_ref(), None, node.text_color).as_deref());
                b.setImagePosition(image_position(node.icon_only));
            }
            (Prop::IconOnly(only), Widget::Button(b)) => {
                node.icon_only = Some(*only);
                b.setImagePosition(image_position(node.icon_only));
            }
            (Prop::Label(t), Widget::GpuSurface(view)) => view.setAccessibilityLabel(Some(&ns(t))),
            (Prop::TakesInput(takes), Widget::GpuSurface(view)) => view.set_takes_input(*takes),
            (Prop::PointerLock(on), Widget::GpuSurface(view)) => view.set_pointer_lock(*on),
            (Prop::KeyboardGrab(on), Widget::GpuSurface(view)) => view.set_keyboard_grab(*on),
            (Prop::Cursor(cursor), Widget::GpuSurface(view)) => view.set_cursor(cursor),
            (Prop::TextInput(on), Widget::GpuSurface(view)) => view.set_text_input(*on),
            (Prop::InputMethod(on), Widget::GpuSurface(view)) => view.set_input_method(*on),
            (Prop::TextCursor(caret), Widget::GpuSurface(view)) => view.set_text_cursor(*caret),
            (Prop::Transparent(on), Widget::GpuSurface(view)) => view.set_transparent(*on),
            (Prop::Label(t), Widget::Progress(p) | Widget::Spinner { indicator: p, .. }) => {
                p.setAccessibilityLabel(Some(&ns(t)))
            }
            (Prop::Running(r), Widget::Spinner { indicator, running }) => {
                if *r {
                    unsafe { indicator.startAnimation(None) };
                } else {
                    unsafe { indicator.stopAnimation(None) };
                }
                *running = *r;
            }
            (Prop::Progress(progress), Widget::Progress(p)) => match progress {
                Some(fraction) => {
                    if p.isIndeterminate() {
                        unsafe { p.stopAnimation(None) };
                        p.setIndeterminate(false);
                        // Once animated, macOS 26's bar layer keeps drawing
                        // the indeterminate animation after it stops, whatever
                        // the value; setting the style again rebuilds it.
                        p.setStyle(NSProgressIndicatorStyle::Spinning);
                        p.setStyle(NSProgressIndicatorStyle::Bar);
                    }
                    p.setDoubleValue(*fraction);
                }
                None => {
                    p.setIndeterminate(true);
                    unsafe { p.startAnimation(None) };
                }
            },
            (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))),
            // AppKit has no error state for a field: VoiceOver reads the
            // message as its help, which the app shows by it.
            (Prop::Error(error), Widget::Field(_) | Widget::TextArea(_)) => {
                node.error = Some(error.clone());
                let help = error.as_ref().or(node.help.as_ref());
                node.widget.view().setAccessibilityHelp(help.map(|h| ns(h)).as_deref());
            }
            // For autofill; AppKit has no on-screen keyboard to pick.
            (Prop::InputPurpose(purpose), Widget::Field(f)) => f.setContentType(content_type(*purpose)),
            (Prop::Value(t), Widget::TextArea(area)) => area.set_string(t),
            // A text view has no placeholder: kept for the mirror.
            (Prop::Placeholder(t), Widget::TextArea(area)) => area.placeholder = Some(t.clone()),
            (Prop::ReadOnly(r), Widget::TextArea(area)) => area.set_read_only(*r),
            (Prop::Enabled(e), Widget::TextArea(area)) => area.set_enabled(*e),
            (Prop::Lines(lines), Widget::TextArea(area)) => area.lines = *lines,
            (Prop::LineWrap(on), Widget::TextArea(area)) => area.set_line_wrap(*on),
            (Prop::FollowsEnd(on), Widget::TextArea(area)) => area.set_follows_end(*on),
            // Still selectable, so its text can be copied; it takes focus
            // from a click, and from the keyboard only with Full Keyboard
            // Access.
            (Prop::ReadOnly(r), Widget::Field(f)) => f.setEditable(!r),
            (Prop::Checked(c), Widget::Checkbox(b)) => {
                node.checked = *c;
                // The mixed state shows over it.
                if b.state() != NSControlStateValueMixed {
                    b.setState(if *c { NSControlStateValueOn } else { NSControlStateValueOff })
                }
            }
            (Prop::Mixed(m), Widget::Checkbox(b)) => {
                node.mixed = Some(*m);
                // Allowed only while shown: clicks would cycle through it.
                b.setAllowsMixedState(*m);
                b.setState(match (*m, node.checked) {
                    (true, _) => NSControlStateValueMixed,
                    (false, true) => NSControlStateValueOn,
                    (false, false) => NSControlStateValueOff,
                });
            }
            (Prop::Checked(c), Widget::Button(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), Widget::Label(l)) => {
                node.text_style = Some(*style);
                l.setFont(Some(&label_font(node.text_style, node.weight, node.italic)));
            }
            (Prop::TextStyle(style), Widget::TextArea(area)) => {
                area.text.setFont(Some(&font(*style)));
                node.text_style = Some(*style);
            }
            (Prop::TextStyle(style), w) if w.control().is_some() => {
                w.control().unwrap().setFont(Some(&font(*style)));
                node.text_style = Some(*style);
            }
            // Weight and italics go on the text style's font.
            (Prop::FontWeight(weight), Widget::Label(l)) => {
                node.weight = Some(*weight);
                l.setFont(Some(&label_font(node.text_style, node.weight, node.italic)));
            }
            (Prop::Italic(italic), Widget::Label(l)) => {
                node.italic = Some(*italic);
                l.setFont(Some(&label_font(node.text_style, node.weight, node.italic)));
            }
            // Semantic colours are dynamic: they follow the appearance.
            (Prop::TextColor(color), Widget::Label(l)) => {
                node.text_color = Some(*color);
                l.setTextColor(Some(&crate::custom::ns_color(*color)));
            }
            (Prop::TextAlign(align), Widget::Label(l)) => {
                node.align = true;
                l.setAlignment(match align {
                    HorizontalAlign::Left => NSTextAlignment::Left,
                    HorizontalAlign::Center => NSTextAlignment::Center,
                    HorizontalAlign::Right => NSTextAlignment::Right,
                });
            }
            (Prop::Rows(rows), Widget::List(list)) => list.set_rows(rows.clone()),
            (Prop::TreeRows(rows), Widget::List(list)) => list.set_tree_rows(rows.clone()),
            (Prop::TreeLoading(rows), Widget::List(list)) => list.set_tree_loading(rows),
            (Prop::RowFiles(files), Widget::List(list)) => list.set_row_files(files.clone()),
            (Prop::RowMoves(moves), Widget::List(list)) => list.set_moves(*moves),
            (Prop::SelectionMode(mode), Widget::List(list)) => list.set_mode(*mode),
            (Prop::ListStyle(style), Widget::List(list)) => list.set_style(*style),
            (Prop::EstimatedRowHeight(height), Widget::List(list)) => list.set_estimate(*height),
            (Prop::Selected(rows), Widget::List(list)) => list.set_selected(rows),
            (Prop::Row(row), Widget::Host(_)) => node.row = Some(*row),
            (Prop::Cell(cell), Widget::Host(_)) => {
                node.row = Some(cell.row);
                node.column = Some(cell.column);
            }
            (Prop::Columns(columns), Widget::List(list)) => list.set_columns(mtm, columns),
            (Prop::Sort(sort), Widget::List(list)) => list.set_sort(*sort),
            (Prop::ScrollAxes(axes), Widget::Scroll(scroll)) => {
                node.scroll_axes = *axes;
                set_scrollers(scroll, node.scroll_axes, node.scroll_bars);
            }
            // A scroll view without scrollers still scrolls by wheel and
            // trackpad.
            (Prop::ScrollBars(show), Widget::Scroll(scroll)) => {
                node.scroll_bars = *show;
                set_scrollers(scroll, node.scroll_axes, node.scroll_bars);
            }
            (Prop::ButtonRole(role), Widget::Button(b)) => {
                // Return clicks the default button, Escape the cancel button.
                b.setKeyEquivalent(&ns(match role {
                    ButtonRole::Default => "\r",
                    ButtonRole::Cancel => "\u{1b}",
                    ButtonRole::Normal | ButtonRole::Destructive => "",
                }));
                b.setHasDestructiveAction(*role == ButtonRole::Destructive);
                node.role = Some(*role);
            }
            (Prop::ButtonStyle(style), Widget::Button(b)) => {
                b.setBordered(*style != ButtonStyle::Borderless);
                set_prominent(b, *style == ButtonStyle::Prominent && node.kind == WidgetKind::Button);
                node.button_style = Some(*style);
            }
            (Prop::LayoutDirection(direction), widget) => set_direction(widget, *direction),
            (Prop::Tooltip(t), widget) => {
                let text = (!t.is_empty()).then(|| ns(t));
                // On the views the pointer rests on, which cover the node's.
                match widget {
                    Widget::NumberInput(n) => {
                        n.field().setToolTip(text.as_deref());
                        n.stepper().setToolTip(text.as_deref());
                    }
                    Widget::List(list) => list.table.setToolTip(text.as_deref()),
                    Widget::TextArea(area) => area.text.setToolTip(text.as_deref()),
                    _ => {}
                }
                widget.view().setToolTip(text.as_deref());
            }
            // On the host: tracking areas are geometric, so its subviews
            // count too.
            (Prop::Hover(on), widget @ (Widget::Host(_) | Widget::Group { .. })) => {
                let view = widget.view();
                if let Some((_, area)) = node.hover.take() {
                    view.removeTrackingArea(&area);
                }
                if *on {
                    node.hover = Some(crate::classes::HoverTracker::track(mtm, view, id, events));
                }
            }
            // Placed after the batch, once laid out (`place_headers`).
            (Prop::Header(on), Widget::Host(host)) => match &node.header {
                Some(header) => header.on.set(*on),
                None => {
                    let header = crate::header::Header::new(mtm, host);
                    header.on.set(*on);
                    header.set_edge(node.header_edge.unwrap_or_default());
                    node.header = Some(header);
                }
            },
            (Prop::HeaderEdge(edge), Widget::Host(_)) => {
                node.header_edge = Some(*edge);
                if let Some(header) = &node.header {
                    header.set_edge(*edge);
                }
            }
            (Prop::SidebarPane(on), Widget::Host(_)) => node.sidebar_pane = Some(*on),
            (Prop::ClickThrough(on), Widget::Host(host)) => {
                node.click_through = true;
                host.set_click_through(*on);
            }
            // On the host, so a click on any of its subviews counts.
            (Prop::DoubleClick(on), widget @ (Widget::Host(_) | Widget::Group { .. })) => {
                let view = widget.view();
                if let Some((_, recognizer)) = node.double_click.take() {
                    view.removeGestureRecognizer(&recognizer);
                }
                if *on {
                    node.double_click = Some(crate::classes::Clicker::track(mtm, view, id, events, 2));
                }
            }
            (Prop::Click(on), widget @ (Widget::Host(_) | Widget::Group { .. })) => {
                let view = widget.view();
                if let Some((_, recognizer)) = node.click.take() {
                    view.removeGestureRecognizer(&recognizer);
                }
                if *on {
                    node.click = Some(crate::classes::Clicker::track(mtm, view, id, events, 1));
                }
            }
            (Prop::ContextMenu(entries), widget) => {
                let target = match node.context_menu.take() {
                    Some((_, target)) => target,
                    None => menu_target(mtm, id, &events),
                };
                match &node.menu_on_open {
                    // A menu built as it opens holds what was built last.
                    Some((opener, menu)) => opener.fill(menu, entries),
                    None => {
                        let menu = (!entries.is_empty()).then(|| {
                            let target = ItemTarget { object: &target, action: sel!(fire:) };
                            crate::services::context_menu(mtm, entries, target)
                        });
                        set_context_menu(widget, menu.as_deref());
                    }
                }
                node.context_menu = Some((entries.clone(), target));
            }
            (Prop::ContextMenuOnOpen(on_open), widget) => match on_open {
                // An empty menu whose delegate asks the app as AppKit opens
                // it, with what it last built in the meantime.
                Some(on_open) => {
                    if let Some((opener, _)) = &node.menu_on_open {
                        opener.set(on_open.clone());
                    } else {
                        let opener =
                            crate::classes::MenuOpener::new(mtm, on_open.clone(), menu_target(mtm, id, &events), 0);
                        let menu = NSMenu::new(mtm);
                        menu.setAutoenablesItems(false);
                        menu.setDelegate(Some(ProtocolObject::from_ref(&*opener)));
                        if let Some((entries, _)) = &node.context_menu {
                            opener.fill(&menu, entries);
                        }
                        set_context_menu(widget, Some(&menu));
                        node.menu_on_open = Some((opener, menu));
                    }
                }
                None => {
                    if node.menu_on_open.take().is_some() {
                        let menu = node.context_menu.as_ref().filter(|(entries, _)| !entries.is_empty()).map(
                            |(entries, target)| {
                                let target = ItemTarget { object: target, action: sel!(fire:) };
                                crate::services::context_menu(mtm, entries, target)
                            },
                        );
                        set_context_menu(widget, menu.as_deref());
                    }
                }
            },
            (Prop::PopoverShown(on), Widget::Popover(popover)) => popover.set_shown(*on),
            (Prop::SearchOnReturn(on), Widget::Field(field)) => {
                if let Some(search) = field.downcast_ref::<objc2_app_kit::NSSearchField>() {
                    search.setSendsWholeSearchString(*on);
                    node.search_on_return = true;
                }
            }
            // A search field's list under it, made with its first
            // suggestions; its keys reach it through the field's delegate.
            (Prop::Suggestions(list), Widget::Field(field)) if node.kind == WidgetKind::SearchInput => {
                if node.suggestions.is_none() {
                    let made = crate::suggestions::Suggestions::new(mtm, id, events.clone(), field);
                    if let Some(target) = &node._target {
                        target.set_suggestions(made.clone());
                    }
                    node.suggestions = Some(made);
                }
                if let Some(suggestions) = &node.suggestions {
                    suggestions.set(list);
                }
            }
            (Prop::Tweak(tweak), _) => node.tweak = Some(tweak.clone()),
            (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();
            }
            _ => {}
        }
        if let Prop::SidebarShown(on) = prop
            && let Some(Widget::Window { split: Some(split), .. }) =
                node.parent.and_then(|p| self.nodes.get(&p)).map(|p| &p.widget)
        {
            split.set_shown(*on);
        }
    }
}

impl State {
    /// Shows a new file icon's file, at its size, once its props are set.
    pub(super) fn load_file_icon(&self, id: NodeId) {
        let Some(node) = self.nodes.get(&id) else { return };
        if let Widget::FileIcon(view) = &node.widget {
            let side = node.icon_size.unwrap_or(FILE_ICON_SIZE);
            let lookup = node.file_lookup.unwrap_or_default();
            show_file_icon(self.mtm, view, node.file.as_deref(), side, node.thumbnail == Some(true), lookup);
        }
    }
}

/// Tick marks kept at most. More would be closer than a point on any
/// screen, so a drag couldn't stop at each anyway, and AppKit draws (and
/// lays out) every one: a step of 0.001 on 0 to 1,000,000 made a billion.
const MAX_TICKS: f64 = 4096.0;

/// AppKit's steps are tick marks, which the knob then only stops at. A
/// step finer than `MAX_TICKS` allows has none, and the action rounds to
/// it instead, as AppKit apps round a fine slider's value in theirs.
fn set_ticks(slider: &NSSlider, step: Option<f64>, target: Option<&crate::classes::ActionTarget>) {
    let range = slider.maxValue() - slider.minValue();
    let step = step.filter(|s| *s > 0.0 && range > 0.0);
    let ticks = step.map(|step| (range / step).round() + 1.0).filter(|ticks| *ticks <= MAX_TICKS);
    match ticks {
        Some(ticks) => {
            slider.setNumberOfTickMarks(ticks as isize);
            slider.setAllowsTickMarkValuesOnly(true);
        }
        None => {
            slider.setNumberOfTickMarks(0);
            slider.setAllowsTickMarkValuesOnly(false);
        }
    }
    if let Some(target) = target {
        target.set_snap(step.filter(|_| ticks.is_none()));
    }
}

/// The content type AppKit's autofill takes for a purpose.
fn content_type(purpose: InputPurpose) -> Option<&'static NSTextContentType> {
    Some(unsafe {
        match purpose {
            InputPurpose::Text => return None,
            InputPurpose::Email => NSTextContentTypeEmailAddress,
            InputPurpose::Url => NSTextContentTypeURL,
            InputPurpose::Phone => NSTextContentTypeTelephoneNumber,
        }
    })
}

/// The purpose a field's content type stands for; any other, or none, is
/// text.
pub(super) fn input_purpose(shown: Option<&NSTextContentType>) -> InputPurpose {
    [InputPurpose::Email, InputPurpose::Url, InputPurpose::Phone]
        .into_iter()
        .find(|p| shown.zip(content_type(*p)).is_some_and(|(shown, t)| shown.isEqualToString(t)))
        .unwrap_or_default()
}

/// Mirrors a widget's own drawing, and the parts it places itself. A view's
/// direction mirrors what reads it (sliders, stack views, tables, scroll
/// views' scrollers); a checkbox's box and a field's text are placed by
/// the app's direction, so they get theirs here too (see
/// `locale::set_app_locale`).
fn set_direction(widget: &Widget, direction: LayoutDirection) {
    let direction = match direction {
        LayoutDirection::LeftToRight => NSUserInterfaceLayoutDirection::LeftToRight,
        LayoutDirection::RightToLeft => NSUserInterfaceLayoutDirection::RightToLeft,
    };
    widget.view().setUserInterfaceLayoutDirection(direction);
    match widget {
        Widget::Checkbox(b) => b.setImagePosition(super::toggle_image_position(direction)),
        Widget::RadioGroup(group) => group.set_direction(direction),
        Widget::Field(f) => f.setAlignment(super::field_alignment(direction)),
        Widget::NumberInput(n) => n.set_direction(direction),
        Widget::TextArea(area) => {
            area.text.setUserInterfaceLayoutDirection(direction);
            area.text.setAlignment(super::field_alignment(direction));
        }
        Widget::List(list) => list.table.setUserInterfaceLayoutDirection(direction),
        Widget::Sidebar(sidebar) => sidebar.table.setUserInterfaceLayoutDirection(direction),
        // Its tabs and buttons are placed from its direction.
        Widget::DocumentTabs(tabs) => tabs.strip.setNeedsLayout(true),
        // Its title is laid out again only when the box is: a title set
        // just before kept the old side, cut at the old width.
        Widget::Group { frame, .. } => {
            frame.setUserInterfaceLayoutDirection(direction);
            frame.setNeedsLayout(true);
        }
        _ => {}
    }
}

/// 0 is AppKit's "no limit". A truncating line-break mode makes a label
/// one line, so only a single line has its start or middle cut off; more
/// lines wrap at words, and the cell cuts off the end of the last one it
/// shows, the only truncation AppKit wraps with.
fn set_line_limit(label: &NSTextField, lines: Option<u32>, truncation: Truncation) {
    label.setMaximumNumberOfLines(lines.map_or(0, |n| n as isize));
    label.setLineBreakMode(match (lines, truncation) {
        (Some(1), Truncation::Start) => NSLineBreakMode::ByTruncatingHead,
        (Some(1), Truncation::Middle) => NSLineBreakMode::ByTruncatingMiddle,
        _ => NSLineBreakMode::ByWordWrapping,
    });
    if let Some(cell) = label.cell() {
        cell.setTruncatesLastVisibleLine(lines.is_some());
    }
}

/// A button filled with the accent colour, without being the default
/// button: macOS 26's primary tint prominence, and before it the accent
/// colour as its bezel's, as apps tinted one then.
pub(super) fn set_prominent(button: &NSButton, on: bool) {
    if button.respondsToSelector(sel!(setTintProminence:)) {
        // `NSTintProminence`: automatic 0, primary 2.
        let prominence: isize = if on { 2 } else { 0 };
        let _: () = unsafe { msg_send![button, setTintProminence: prominence] };
    } else {
        button.setBezelColor(on.then(NSColor::controlAccentColor).as_deref());
    }
}

/// Whether a button shows as `set_prominent` makes it.
pub(super) fn is_prominent(button: &NSButton) -> bool {
    if button.respondsToSelector(sel!(tintProminence)) {
        let prominence: isize = unsafe { msg_send![button, tintProminence] };
        prominence == 2
    } else {
        button.bezelColor().is_some_and(|c| c.isEqual(Some(&NSColor::controlAccentColor())))
    }
}

/// The target of a context menu's items: reports the one chosen.
fn menu_target(mtm: MainThreadMarker, id: NodeId, events: &EventSink) -> Retained<ClosureTarget> {
    let events = events.clone();
    ClosureTarget::new(mtm, move |sender| {
        if let Some(item) = sender.downcast_ref::<NSMenuItem>() {
            events.emit(id, UiEvent::ContextMenuItem(item.tag() as u32));
        }
    })
}

/// Gives a widget's views its context menu. AppKit shows a view's menu on
/// a right-click or a Control-click, and a view without one passes the
/// click up to its superview: children show their container's. It's on
/// the views the pointer rests on, as tooltips are. A pop-up button's
/// menu is its options, which a right-click shows too: it keeps the menu
/// on the node.
fn set_context_menu(widget: &Widget, menu: Option<&NSMenu>) {
    let set = |view: &NSView| unsafe { view.setMenu(menu) };
    match widget {
        Widget::Select(_) | Widget::MenuButton { .. } | Widget::SplitButton(_) => return,
        Widget::NumberInput(n) => {
            set(n.field());
            set(n.stepper());
        }
        Widget::List(list) => set(&list.table),
        _ => {}
    }
    set(widget.view());
}