mitsuami-appkit 2.3.0

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
//! Applying the core's commands: the tree, frames, focus and scrolling.

use mitsuami_core::a11y::A11yProps;
use mitsuami_core::{ButtonStyle, Command, NodeId, Size, WidgetKind};
use objc2::Message;
use objc2::rc::Retained;
use objc2_app_kit::{NSAccessibility, NSApplication, NSBezelStyle, NSView, NSWindowOrderingMode};
use objc2_foundation::{NSNotificationCenter, NSPoint, NSRect, NSSize};

use crate::document_tabs::Place;
use crate::sidebar::Split;
use crate::toolbar::Toolbar;

use super::scrolling::scroll_to;
use super::windows::{in_full_screen, post_empty_event};
use super::{State, Widget, key, ns, violation};

impl State {
    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")),
        }
    }

    /// The view a node's children are in: a header's own (see `header`).
    fn children_view(&self, id: NodeId, command: &Command) -> Retained<NSView> {
        match self.nodes.get(&id).and_then(|n| n.header.as_ref()) {
            Some(header) => Retained::into_super(header.content.clone()),
            None => self.view(id, command),
        }
    }

    /// Runs the node's raw settings, if the app gave any, after its props:
    /// what they set wins.
    fn run_tweak(&self, id: NodeId) {
        let node = &self.nodes[&id];
        if let Some(run) = node.tweak.as_ref().and_then(|tweak| tweak.downcast_ref::<crate::tweak::TweakFn>()) {
            match &node.widget {
                // The table or text view, not the scroll view around it.
                Widget::List(list) => run(&list.table),
                Widget::Sidebar(sidebar) => run(&sidebar.table),
                Widget::TextArea(area) => run(&area.text),
                Widget::DocumentTabs(tabs) => run(&tabs.strip),
                // The box, not the layout host its children are in.
                Widget::Group { frame, .. } => run(frame),
                widget => run(widget.view()),
            }
        }
    }

    /// Puts document tabs in their window's chrome, unless the app asked
    /// for a strip: in a band under the title and toolbar, or in the
    /// title's row; and back in the content when they stop asking or leave
    /// the window. A window's chrome has one strip: the one there stays,
    /// and others are strips in the content.
    pub(super) fn place_document_tabs(&mut self) {
        let mut all: Vec<(NodeId, bool)> = self
            .nodes
            .iter()
            .filter_map(|(id, node)| match &node.widget {
                Widget::DocumentTabs(tabs) => Some((*id, tabs.placed().is_none())),
                _ => None,
            })
            .collect();
        all.sort();
        all.sort_by_key(|(_, unplaced)| *unplaced);
        let mut taken: Vec<NodeId> = Vec::new();
        for (id, _) in all {
            let Some(Widget::DocumentTabs(tabs)) = self.nodes.get(&id).map(|n| &n.widget) else { continue };
            let target = tabs
                .wanted()
                .zip(self.window_node_of(id))
                .filter(|(_, window)| !taken.contains(window))
                .map(|(place, window)| (window, place));
            if let Some((window, _)) = target {
                taken.push(window);
            }
            if tabs.placed() != target {
                self.move_document_tabs(id, target);
            }
        }
    }

    /// The window node a node is in.
    fn window_node_of(&self, id: NodeId) -> Option<NodeId> {
        let mut at = self.nodes.get(&id)?.parent;
        while let Some(parent) = at {
            let node = self.nodes.get(&parent)?;
            if matches!(node.widget, Widget::Window { .. }) {
                return Some(parent);
            }
            at = node.parent;
        }
        None
    }

    /// Moves document tabs out of the chrome they're in and into
    /// `target`'s. As with a header or a toolbar, each window's content
    /// keeps its size: the window grows by the chrome the tabs take, and
    /// shrinks by what they give back.
    fn move_document_tabs(&mut self, id: NodeId, target: Option<(NodeId, Place)>) {
        let mtm = self.mtm;
        let animate = self.options.show_windows;
        let Some(Widget::DocumentTabs(tabs)) = self.nodes.get(&id).map(|n| &n.widget) else { return };
        let had = tabs.placed();
        let row = tabs.row.clone();
        if let Some((window_id, place)) = had
            && let Some(Widget::Window { window, host, _delegate, toolbar, split }) =
                self.nodes.get_mut(&window_id).map(|n| &mut n.widget)
        {
            let size = host.frame().size;
            if place == Place::Row
                && let Some(bar) = toolbar
            {
                bar.set_tabs(mtm, None);
                if bar.is_empty() && split.is_none() {
                    window.setToolbar(None);
                    *toolbar = None;
                }
            }
            let (window, delegate) = (window.clone(), _delegate.clone());
            if let Some(Widget::DocumentTabs(tabs)) = self.nodes.get(&id).map(|n| &n.widget) {
                tabs.place(None);
            }
            window.layoutIfNeeded();
            window.setContentSize(delegate.at_least_min(&window, Size::new(size.width as f32, size.height as f32)));
        } else if let Some(Widget::DocumentTabs(tabs)) = self.nodes.get(&id).map(|n| &n.widget) {
            tabs.place(None);
        }
        let Some((window_id, place)) = target else { return };
        let Some(Widget::Window { window, host, _delegate, .. }) =
            self.nodes.get_mut(&window_id).map(|n| &mut n.widget)
        else {
            return;
        };
        let size = host.frame().size;
        crate::sidebar::content_under_bar(mtm, window, host);
        _delegate.set_detail(Some(host));
        let (window, delegate) = (window.clone(), _delegate.clone());
        if let Some(Widget::DocumentTabs(tabs)) = self.nodes.get(&id).map(|n| &n.widget) {
            tabs.place(Some((window_id, &window, place)));
        }
        if place == Place::Row
            && let Some(Widget::Window { toolbar, .. }) = self.nodes.get_mut(&window_id).map(|n| &mut n.widget)
        {
            toolbar.get_or_insert_with(|| Toolbar::new(mtm, &window, window_id, animate)).set_tabs(mtm, Some(&row));
        }
        window.layoutIfNeeded();
        window.setContentSize(delegate.at_least_min(&window, Size::new(size.width as f32, size.height as f32)));
    }

    /// The toolbar item a node is a child of.
    pub(super) fn toolbar_item_of(&self, id: NodeId) -> Option<NodeId> {
        self.nodes.get(&id)?.parent.filter(|p| self.nodes.get(p).is_some_and(|n| n.kind == WidgetKind::ToolbarItem))
    }

    /// The item shows its button as its view (see `toolbar`).
    pub(super) fn toolbar_adopted(&self, item: NodeId) -> bool {
        let window = self.nodes[&item].parent.and_then(|w| self.nodes.get(&w));
        matches!(window.map(|w| &w.widget), Some(Widget::Window { toolbar: Some(toolbar), .. }) if toolbar.adopted(item))
    }

    fn release_toolbar_item(&mut self, item: NodeId) {
        if let Some(window) = self.nodes[&item].parent
            && let Some(Widget::Window { toolbar: Some(toolbar), .. }) =
                self.nodes.get_mut(&window).map(|n| &mut n.widget)
        {
            toolbar.release(item);
        }
    }

    /// The toolbar item a node is in, as its child or its grandchild (a
    /// button in a row of them).
    pub(super) fn toolbar_item_above(&self, id: NodeId) -> Option<NodeId> {
        self.toolbar_item_of(id).or_else(|| self.toolbar_item_of(self.nodes.get(&id)?.parent?))
    }

    /// A node's children, in no particular order.
    fn children_of(&self, id: NodeId) -> &[NodeId] {
        self.children.get(&id).map_or(&[], |c| c.as_slice())
    }

    /// Records a child's parent both ways: a toolbar item looks down its
    /// tree on every change, which a scan of every node made slow.
    fn attach(&mut self, child: NodeId, parent: NodeId) {
        self.nodes.get_mut(&child).unwrap().parent = Some(parent);
        self.children.entry(parent).or_default().push(child);
    }

    fn detach(&mut self, child: NodeId) {
        let Some(parent) = self.nodes.get_mut(&child).and_then(|n| n.parent.take()) else { return };
        if let Some(siblings) = self.children.get_mut(&parent) {
            siblings.retain(|c| *c != child);
            if siblings.is_empty() {
                self.children.remove(&parent);
            }
        }
    }

    /// A node's children, in order.
    fn ordered_children(&self, id: NodeId) -> Vec<NodeId> {
        let by_view = self.by_view.borrow();
        let node = &self.nodes[&id];
        let view: &NSView = node.header.as_ref().map_or(node.widget.view(), |h| &h.content);
        view.subviews().iter().filter_map(|v| by_view.get(&key(&v)).copied()).collect()
    }

    /// A node or any node in it takes input: a toolbar item with none (a
    /// label, a progress bar) has no capsule.
    fn has_control(&self, id: NodeId) -> bool {
        let Some(node) = self.nodes.get(&id) else { return false };
        match node.kind {
            WidgetKind::Container | WidgetKind::ToolbarItem => {
                self.children_of(id).iter().any(|c| self.has_control(*c))
            }
            WidgetKind::Text
            | WidgetKind::Progress
            | WidgetKind::Spinner
            | WidgetKind::Separator
            | WidgetKind::Image
            | WidgetKind::Icon
            | WidgetKind::FileIcon => false,
            _ => true,
        }
    }

    /// An item whose only child is a button or a search field shows the
    /// control itself, as AppKit's toolbars have them; one whose only
    /// child is a row of two or more buttons shows them as one segmented
    /// control; any other shows its host, in a capsule only if there's a
    /// control in it.
    fn sync_toolbar_item(&mut self, item: NodeId) {
        enum Shown {
            Button(Retained<objc2_app_kit::NSButton>, bool),
            Field(Retained<objc2_app_kit::NSSearchField>),
            Group(Vec<Retained<objc2_app_kit::NSButton>>),
            Host(bool),
        }
        let Some(window) = self.nodes[&item].parent else { return };
        let shown = match *self.children_of(item) {
            [only_id] => {
                let only = &self.nodes[&only_id];
                let bordered = only.button_style != Some(ButtonStyle::Borderless);
                match &only.widget {
                    Widget::Button(button) => Shown::Button(button.clone(), bordered),
                    Widget::MenuButton { popup, .. } => Shown::Button(popup.clone().into_super(), bordered),
                    Widget::Host(_) if only.kind == WidgetKind::Container => {
                        let row = self.ordered_children(only_id);
                        let buttons: Vec<_> = row
                            .iter()
                            .filter_map(|c| match (&self.nodes[c].kind, &self.nodes[c].widget) {
                                (WidgetKind::Button, Widget::Button(button)) => Some(button.clone()),
                                _ => None,
                            })
                            .collect();
                        if buttons.len() >= 2 && buttons.len() == row.len() {
                            Shown::Group(buttons)
                        } else {
                            Shown::Host(self.has_control(item))
                        }
                    }
                    widget => match widget.view().downcast_ref::<objc2_app_kit::NSSearchField>() {
                        Some(field) => Shown::Field(field.retain()),
                        None => Shown::Host(self.has_control(item)),
                    },
                }
            }
            _ => Shown::Host(self.has_control(item)),
        };
        let mtm = self.mtm;
        let Some(Widget::Window { toolbar: Some(toolbar), .. }) = self.nodes.get_mut(&window).map(|n| &mut n.widget)
        else {
            return;
        };
        match shown {
            Shown::Button(button, bordered) => toolbar.adopt_button(item, &button, bordered),
            Shown::Field(field) => toolbar.adopt_field(item, &field),
            Shown::Group(buttons) => toolbar.adopt_group(mtm, item, buttons),
            Shown::Host(glass) => toolbar.show_host(item, glass),
        }
    }

    pub(super) 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);
                }
                self.load_file_icon(*id);
                self.run_tweak(*id);
            }
            Command::SetProp { id, prop } => {
                self.set_prop(*id, prop, command);
                // A toolbar's button keeps the toolbar's bezel, and a
                // group's segment shows its button.
                if let Some(item) = self.toolbar_item_above(*id) {
                    self.sync_toolbar_item(item);
                }
                self.run_tweak(*id);
            }
            Command::Insert { parent, child, index } => {
                let parent_view = self.children_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.attach(*child, *parent);
                    return;
                }
                if self.nodes[child].kind == WidgetKind::Sidebar {
                    let (mtm, animate) = (self.mtm, self.options.show_windows);
                    let Widget::Sidebar(sidebar) = &self.nodes[child].widget else { unreachable!() };
                    let scroll = sidebar.scroll.clone();
                    let shown = sidebar.shown.get();
                    let Widget::Window { window, host, _delegate, toolbar, split } =
                        &mut self.nodes.get_mut(parent).unwrap().widget
                    else {
                        violation(command, "a sidebar goes in a window")
                    };
                    if split.is_some() {
                        violation(command, "a window has one sidebar");
                    }
                    // The content keeps its size: the window grows by the
                    // sidebar. The title and toolbar items go over the
                    // content, as a unified toolbar puts them.
                    let size = host.frame().size;
                    toolbar.get_or_insert_with(|| Toolbar::new(mtm, window, *parent, animate)).set_sidebar(true);
                    let made = Split::new(mtm, window, host, *child, &scroll, self.events.clone());
                    if let Some(shown) = shown {
                        made.set_shown(shown);
                    }
                    *split = Some(made);
                    _delegate.set_detail(Some(host));
                    let (window, delegate) = (window.clone(), _delegate.clone());
                    self.attach(*child, *parent);
                    // Again, now that it's in the window's split view,
                    // which its props came before: a width it sets is in
                    // the window's.
                    self.run_tweak(*child);
                    window.setContentSize(
                        delegate.at_least_min(&window, Size::new(size.width as f32, size.height as f32)),
                    );
                    return;
                }
                if self.nodes[child].kind == WidgetKind::ToolbarItem {
                    // Items come after the window's content, and before its sidebar.
                    let content = self
                        .children_of(*parent)
                        .iter()
                        .filter(|c| !matches!(self.nodes[c].kind, WidgetKind::ToolbarItem | WidgetKind::Sidebar))
                        .count();
                    let (mtm, animate) = (self.mtm, self.options.show_windows);
                    let Widget::Window { window, host, _delegate, toolbar, split } =
                        &mut self.nodes.get_mut(parent).unwrap().widget
                    else {
                        violation(command, "toolbar items go in windows")
                    };
                    let Some(index) = index.checked_sub(content) else {
                        violation(command, "toolbar items go after the window's content")
                    };
                    // The first item: the content goes under the bar, and
                    // keeps its size, as beside a sidebar.
                    if toolbar.is_none() && split.is_none() {
                        let size = host.frame().size;
                        *toolbar = Some(Toolbar::new(mtm, window, *parent, animate));
                        crate::sidebar::content_under_bar(mtm, window, host);
                        _delegate.set_detail(Some(host));
                        window.setContentSize(
                            _delegate.at_least_min(window, Size::new(size.width as f32, size.height as f32)),
                        );
                    }
                    toolbar.get_or_insert_with(|| Toolbar::new(mtm, window, *parent, animate)).insert(
                        mtm,
                        *child,
                        &child_view,
                        index,
                    );
                    self.attach(*child, *parent);
                    self.sync_toolbar_item(*child);
                    return;
                }
                // A popover isn't in its parent's view: it points at it.
                if let Widget::Popover(popover) = &self.nodes[child].widget {
                    if !matches!(self.nodes[parent].widget, Widget::Host(_) | Widget::Group { .. }) {
                        violation(command, "a popover goes in a container");
                    }
                    popover.set_anchor(Some(&parent_view));
                    self.attach(*child, *parent);
                    return;
                }
                if let Widget::Tabs(tabs) = &self.nodes[parent].widget {
                    tabs.insert(self.mtm, *child, child_view, *index);
                    self.attach(*child, *parent);
                    return;
                }
                if let Widget::SplitView(split) = &self.nodes[parent].widget {
                    split.insert(self.mtm, *child, &child_view, *index);
                    self.attach(*child, *parent);
                    return;
                }
                if let Widget::List(list) = &self.nodes[parent].widget {
                    let Some(row) = self.nodes[child].row else {
                        violation(command, "a List's children are row hosts, a Table's cell hosts")
                    };
                    list.insert(row, self.nodes[child].column.unwrap_or(0), *child, child_view);
                    self.attach(*child, *parent);
                    return;
                }
                // Back in its host first, among the children it's placed.
                let item = (self.nodes[parent].kind == WidgetKind::ToolbarItem).then_some(*parent);
                if let Some(item) = item {
                    self.release_toolbar_item(item);
                }
                // A transparent surface's backdrop isn't a sibling: it
                // stays just under its surface.
                let siblings: Vec<_> =
                    parent_view.subviews().iter().filter(|v| !crate::surface::is_backdrop(v)).collect();
                // A group's box is behind its children.
                let index = &(index + usize::from(matches!(self.nodes[parent].widget, Widget::Group { .. })));
                if *index >= siblings.len() {
                    parent_view.addSubview(&child_view);
                } else {
                    let before = crate::surface::lowest(siblings[*index].clone());
                    parent_view.addSubview_positioned_relativeTo(
                        &child_view,
                        NSWindowOrderingMode::Below,
                        Some(&before),
                    );
                }
                self.attach(*child, *parent);
                // A button in a row of them changes the group.
                if let Some(item) = item.or_else(|| self.toolbar_item_of(*parent)) {
                    self.sync_toolbar_item(item);
                }
            }
            Command::Remove { parent, child } => {
                if self.nodes.get(child).and_then(|n| n.parent) != Some(*parent) {
                    violation(command, "not a child of this parent");
                }
                let (row, column) = (self.nodes[child].row, self.nodes[child].column.unwrap_or(0));
                if let Widget::Window { window, host, _delegate, toolbar, split } =
                    &mut self.nodes.get_mut(parent).unwrap().widget
                    && split.as_ref().is_some_and(|s| s.sidebar == *child)
                {
                    // The window loses the sidebar, and the content keeps
                    // its size.
                    let size = host.frame().size;
                    split.take().unwrap().remove(window, host);
                    _delegate.set_detail(None);
                    if let Some(bar) = toolbar {
                        bar.set_sidebar(false);
                        if bar.is_empty() {
                            window.setToolbar(None);
                            *toolbar = None;
                        } else {
                            // Still a toolbar: the content stays under it.
                            crate::sidebar::content_under_bar(self.mtm, window, host);
                            _delegate.set_detail(Some(host));
                        }
                    }
                    window.setContentSize(
                        _delegate.at_least_min(window, Size::new(size.width as f32, size.height as f32)),
                    );
                    self.detach(*child);
                    return;
                }
                if let Widget::Popover(popover) = &self.nodes[child].widget {
                    popover.set_anchor(None);
                    self.detach(*child);
                    return;
                }
                let item = (self.nodes[parent].kind == WidgetKind::ToolbarItem).then_some(*parent);
                if let Some(item) = item {
                    self.release_toolbar_item(item);
                }
                if let Widget::SplitView(split) = &self.nodes[parent].widget {
                    split.remove(*child, self.nodes[child].widget.view());
                }
                match &mut self.nodes.get_mut(parent).unwrap().widget {
                    Widget::Window { toolbar: Some(toolbar), .. } if toolbar.contains(*child) => toolbar.remove(*child),
                    Widget::Scroll(scroll) => scroll.setDocumentView(None),
                    Widget::List(list) => list.remove(row.expect("inserted with a row"), column),
                    Widget::Tabs(tabs) => tabs.remove(*child),
                    // Taken out with its host, above.
                    Widget::SplitView(_) => {}
                    _ => self.view(*child, command).removeFromSuperview(),
                }
                self.detach(*child);
                if let Some(item) = item.or_else(|| self.toolbar_item_of(*parent)) {
                    self.sync_toolbar_item(item);
                }
            }
            Command::Destroy { id } => {
                if !self.nodes.contains_key(id) {
                    violation(command, "node does not exist");
                }
                // Document tabs out of their window's chrome.
                if matches!(self.nodes[id].widget, Widget::DocumentTabs(_)) {
                    self.move_document_tabs(*id, None);
                }
                // Out of its parent's children, if it wasn't removed first
                // (a sidebar destroyed with its window).
                self.detach(*id);
                self.children.remove(id);
                let mut node = self.nodes.remove(id).unwrap();
                self.by_view.borrow_mut().remove(&key(node.widget.view()));
                self.pending_show.retain(|w| w != id);
                // A dialog still waiting for it goes up without it, once
                // this commit is over.
                let (waiting, kept) = std::mem::take(&mut self.on_shown).into_iter().partition(|(w, _)| w == id);
                self.on_shown = kept;
                for (_, run) in waiting {
                    super::windows::soon(run);
                }
                self.focus_orders.remove(id);
                if let Some(target) = &node._target {
                    unsafe { NSNotificationCenter::defaultCenter().removeObserver(target) };
                }
                // A tracking area doesn't retain its owner, and the view may
                // outlive the node (the app's native view, a surface).
                if let Some((_, area)) = &node.hover {
                    node.widget.view().removeTrackingArea(area);
                }
                if let Some((_, recognizer)) = &node.double_click {
                    node.widget.view().removeGestureRecognizer(recognizer);
                }
                // Out of its window's title bar.
                if let Some(header) = &node.header {
                    let host = header.window.get().and_then(|w| match self.nodes.get(&w).map(|n| &n.widget) {
                        Some(Widget::Window { host, .. }) => Some(host.clone()),
                        _ => None,
                    });
                    header.detach(node.widget.view(), host.as_deref().map(|h| &**h));
                }
                match &mut node.widget {
                    Widget::Window { window, _delegate, split, .. } => {
                        // Out of the sheet, or of the modal loop, first.
                        if let Some(parent) = window.sheetParent() {
                            parent.endSheet(window);
                        }
                        let app = NSApplication::sharedApplication(self.mtm);
                        if app.modalWindow().is_some_and(|m| std::ptr::eq(&*m, &**window)) {
                            // `stopModal` only works from an event handler;
                            // this runs in a tick. The empty event makes the
                            // loop notice.
                            app.abortModal();
                            post_empty_event(&app);
                        }
                        _delegate.stop_observing_focus(window);
                        // Its sidebar was destroyed without a Remove: the
                        // split's item outlives the node, with the window.
                        if let Some(split) = split.take() {
                            split.detach();
                        }
                        window.setDelegate(None);
                        window.close();
                    }
                    Widget::Sidebar(sidebar) => {
                        sidebar.detach();
                        sidebar.scroll.removeFromSuperview();
                    }
                    Widget::List(list) => {
                        list.detach();
                        list.scroll.removeFromSuperview();
                    }
                    // The colour panel is the well's while it's active: it
                    // goes with it, as the other platforms' pickers go with
                    // their window. Otherwise it stayed open over nothing.
                    Widget::ColorWell(well) => {
                        if well.isActive() {
                            well.deactivate();
                            objc2_app_kit::NSColorPanel::sharedColorPanel(self.mtm).orderOut(None);
                        }
                        well.removeFromSuperview();
                    }
                    // The app's handle may keep it: it just stops showing.
                    Widget::GpuSurface(view) => {
                        view.detach();
                        view.removeFromSuperview();
                    }
                    widget => widget.view().removeFromSuperview(),
                }
            }
            Command::SetFrame { id, frame } => {
                let rect = NSRect::new(
                    NSPoint::new(frame.x() as f64, frame.y() as f64),
                    NSSize::new(frame.width() as f64, frame.height() as f64),
                );
                if let Some(Widget::List(list)) = self.nodes.get(id).map(|n| &n.widget) {
                    list.set_frame(rect);
                    return;
                }
                // A popover is where the platform shows it, at this size.
                if let Some(Widget::Popover(popover)) = self.nodes.get(id).map(|n| &n.widget) {
                    popover.set_size(rect.size);
                    return;
                }
                // A toolbar item is where the toolbar puts it, at this size.
                if let Some(window) =
                    self.nodes.get(id).filter(|n| n.kind == WidgetKind::ToolbarItem).and_then(|n| n.parent)
                    && let Some(Widget::Window { toolbar: Some(toolbar), .. }) =
                        self.nodes.get_mut(&window).map(|n| &mut n.widget)
                {
                    toolbar.set_size(*id, rect.size.width, rect.size.height);
                    return;
                }
                // A row fills its cell, and the table makes the row as high;
                // a table's cell sits centred in its cell, and the table
                // makes the row as high as its highest.
                // A toolbar's control is the toolbar's to size and place.
                if self.toolbar_item_of(*id).is_some_and(|item| self.toolbar_adopted(item)) {
                    return;
                }
                let parent = self.nodes.get(id).and_then(|n| n.parent).map(|p| &self.nodes[&p].widget);
                // A page is where its tab view puts it, at this size.
                if let Some(Widget::Tabs(tabs)) = parent {
                    tabs.set_page_size(*id, rect.size);
                    return;
                }
                if let Some(Widget::List(list)) = parent {
                    self.view(*id, command).setFrame(rect);
                    if let Some(row) = self.nodes[id].row {
                        list.set_host_height(row, self.nodes[id].column.unwrap_or(0), frame.height());
                    }
                    return;
                }
                let view = self.view(*id, command);
                let rect = NSRect::new(
                    NSPoint::new(frame.x() as f64, frame.y() as f64),
                    NSSize::new(frame.width() as f64, frame.height() as f64),
                );
                // A separator is its line: its alignment insets follow its
                // frame's shape, so a vertical one set through them while
                // it's still horizontal would land 2pt off each end.
                if matches!(self.nodes[id].widget, Widget::Separator(_)) {
                    view.setFrame(rect);
                    return;
                }
                // A view given no room (hidden, or squeezed out) shows
                // nothing: a control's frame for an empty alignment rect is
                // its bezel's size, so it would still draw.
                let empty = frame.width() <= 0.0 || frame.height() <= 0.0;
                if view.isHidden() != empty {
                    view.setHidden(empty);
                }
                // A tab view keeps its frame while it has no room: macOS 26's
                // tab strip (SwiftUI's segmented control) laid its tabs out
                // for the frame it had then, and came back with them
                // narrower once it had room again.
                if let Widget::Tabs(tabs) = &self.nodes[id].widget {
                    tabs.parked.set(empty.then_some(rect));
                    if empty {
                        // As a split's pane, its host still goes where
                        // the core put it.
                        if let Some(Widget::SplitView(split)) = parent {
                            split.place_host(*id, rect);
                        }
                        return;
                    }
                }
                // AppKit's push button is one height; one the layout makes
                // taller is its flexible push button, which takes any height
                // (an icon tab in a rail, a tall action button).
                // Buttons are made `Automatic`, which AppKit draws as a push.
                if let Widget::Button(b) = &self.nodes[id].widget
                    && b.isBordered()
                    && matches!(
                        b.bezelStyle(),
                        NSBezelStyle::Automatic | NSBezelStyle::Push | NSBezelStyle::FlexiblePush
                    )
                {
                    let tall = rect.size.height > b.intrinsicContentSize().height + 0.5;
                    if tall {
                        b.setBezelStyle(NSBezelStyle::FlexiblePush);
                    } else if b.bezelStyle() == NSBezelStyle::FlexiblePush {
                        b.setBezelStyle(NSBezelStyle::Automatic);
                    }
                }
                // Layout places what the user sees, the alignment rect, as
                // Auto Layout does; controls draw their bezels inset from
                // their frames (a push button by 7pt a side before macOS 26).
                // A log at its end stays there as it's resized: the clip
                // view keeps its offset, or cuts it short.
                let following = match &self.nodes[id].widget {
                    Widget::TextArea(area) => area.follows_end && area.at_end(),
                    _ => false,
                };
                // A split's pane is in a host of its own.
                match parent {
                    Some(Widget::SplitView(split)) => split.place(*id, &view, rect),
                    _ => view.setFrame(view.frameForAlignmentRect(rect)),
                }
                if following && let Widget::TextArea(area) = &self.nodes[id].widget {
                    area.scroll_to_end();
                }
                // The split or a pane moved: the divider follows.
                for widget in [Some(&self.nodes[id].widget), parent].into_iter().flatten() {
                    if let Widget::SplitView(split) = widget {
                        split.panes_moved();
                    }
                }
            }
            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());
                // A field's error is its help while it has one.
                let node = self.nodes.get_mut(id).expect("a node");
                node.help = description.clone();
                let help = node.error.clone().flatten().or(description.clone());
                view.setAccessibilityHelp(help.as_deref().map(ns).as_deref());
                if *hidden {
                    view.setAccessibilityElement(false);
                }
            }
            // AppKit would resize a window in full screen, and below its
            // minimum: it keeps the screen's size, and its minimum. A
            // locked height is the user's limit, not the app's.
            Command::SetWindowSize { id, size } => match self.nodes.get(id).map(|n| &n.widget) {
                Some(Widget::Window { window, _delegate, .. }) => {
                    if !in_full_screen(window) {
                        window.setContentSize(_delegate.at_least_min(window, *size));
                    }
                }
                _ => 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.key_view().setNextKeyView(None) };
                    }
                }
                let views: Vec<Retained<NSView>> = order
                    .iter()
                    .map(|id| match self.nodes.get(id) {
                        Some(node) => node.widget.key_view(),
                        None => violation(command, &format!("node {id} does not exist")),
                    })
                    .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)),
                Some(Widget::List(list)) => scroll_to(&list.scroll, NSPoint::new(offset.x as f64, offset.y as f64)),
                _ => violation(command, "not a ScrollView, List or Table"),
            },
            Command::ScrollToRow { id, row } => match self.nodes.get(id).map(|n| &n.widget) {
                Some(Widget::List(list)) => list.scroll_to_row(*row),
                _ => violation(command, "not a List"),
            },
            Command::Focus { id } => {
                let Some(node) = self.nodes.get(id) else { violation(command, "node does not exist") };
                let view = node.widget.key_view();
                if let Some(window) = view.window() {
                    window.makeFirstResponder(Some(&view));
                }
            }
            Command::SelectText { id, range } => {
                let Some(node) = self.nodes.get(id) else { violation(command, "node does not exist") };
                super::selection::select(&node.widget, range.clone());
            }
        }
    }
}