mitsuami-appkit 2.4.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
//! Reading back what the native widgets show, for the mirror check.

use mitsuami_core::backend::NativeState;
use mitsuami_core::{
    ButtonStyle, Color, HorizontalAlign, ImageFit, NodeId, Orientation, Point, Prop, Rect, ScrollAxes, Truncation,
    WidgetKind,
};
use objc2_app_kit::{
    NSAccessibility, NSCellImagePosition, NSColor, NSColorSpace, NSControlStateValueMixed, NSControlStateValueOn,
    NSFontDescriptorSymbolicTraits, NSImageScaling, NSLineBreakMode, NSTextAlignment, NSTextContent, NSTitlePosition,
    NSView, NSWindowStyleMask,
};
use objc2_foundation::NSObjectProtocol;

use super::fonts::font_weight;
use super::menus::pull_down_title;
use super::props::input_purpose;
use super::{State, Widget, key};

pub(super) fn native_state(state: &State, id: NodeId) -> Option<NativeState> {
    let node = state.nodes.get(&id)?;
    let mut props = Vec::new();
    // Kept: what the list under the field shows.
    props.extend(node.suggestions.as_ref().map(|list| Prop::Suggestions(list.items())));
    if node.search_on_return
        && let Widget::Field(field) = &node.widget
        && let Some(search) = field.downcast_ref::<objc2_app_kit::NSSearchField>()
    {
        props.push(Prop::SearchOnReturn(search.sendsWholeSearchString()));
    }
    let checked = |s: isize| Prop::Checked(s == NSControlStateValueOn);
    match &node.widget {
        Widget::Window { window, _delegate, .. } => {
            props.push(Prop::Title(window.title().to_string()));
            props.push(Prop::FullScreen(_delegate.full_screen(window)));
            props.push(Prop::MinSize(_delegate.min_size(window)));
            props.push(Prop::HeightFollowsContent(_delegate.height_locked(window)));
            props.push(Prop::Maximized(_delegate.zoomed(window)));
            props.push(Prop::Resizable(window.styleMask().contains(NSWindowStyleMask::Resizable)));
            props.extend(node.modal.map(|(owner, modality)| Prop::Modal { owner, modality }));
        }
        Widget::Label(l) => {
            props.push(Prop::Text(l.stringValue().to_string()));
            props.push(Prop::Selectable(l.isSelectable()));
            let lines = l.maximumNumberOfLines();
            props.push(Prop::MaxLines((lines > 0).then_some(lines as u32)));
            // Wrapping, it shows only the end cut off.
            if let Some(given) = node.truncation {
                props.push(Prop::Truncation(match l.lineBreakMode() {
                    NSLineBreakMode::ByTruncatingHead => Truncation::Start,
                    NSLineBreakMode::ByTruncatingMiddle => Truncation::Middle,
                    _ => given,
                }));
            }
            if let Some(font) = l.font() {
                if node.weight.is_some() {
                    props.push(Prop::FontWeight(font_weight(&font)));
                }
                if node.italic.is_some() {
                    let italic = font.fontDescriptor().symbolicTraits();
                    props.push(Prop::Italic(italic.contains(NSFontDescriptorSymbolicTraits::TraitItalic)));
                }
            }
            // The colour it shows, if it's the one given; else what it is.
            if let (Some(sent), Some(shown)) = (node.text_color, l.textColor()) {
                let given = crate::custom::ns_color(sent);
                props.push(Prop::TextColor(if shown.isEqual(Some(&given)) { sent } else { rgba(&shown) }));
            }
            if node.align {
                let align = l.alignment();
                props.push(Prop::TextAlign(if align == NSTextAlignment::Center {
                    HorizontalAlign::Center
                } else if align == NSTextAlignment::Right {
                    HorizontalAlign::Right
                } else {
                    HorizontalAlign::Left
                }));
            }
        }
        Widget::Field(f) => {
            props.push(Prop::Value(f.stringValue().to_string()));
            if let Some(p) = f.placeholderString() {
                props.push(Prop::Placeholder(p.to_string()));
            }
            props.push(Prop::ReadOnly(!f.isEditable()));
            if node.kind == WidgetKind::TextInput {
                props.push(Prop::InputPurpose(input_purpose(f.contentType().as_deref())));
            }
        }
        Widget::TextArea(area) => {
            props.push(Prop::LineWrap(area.line_wrap()));
            props.push(Prop::Value(area.text.string().to_string()));
            props.extend(area.placeholder.clone().map(Prop::Placeholder));
            props.push(Prop::ReadOnly(area.read_only()));
            props.push(Prop::Enabled(area.text.isSelectable()));
            props.push(Prop::Lines(area.lines));
            props.push(Prop::FollowsEnd(area.follows_end));
        }
        Widget::SplitButton(button) => {
            props.push(Prop::Label(button.title()));
            props.extend(node.icon.clone().map(Prop::Icon));
            props.extend(node.vector_icon.clone().map(Prop::VectorIcon));
            if node.icon_only.is_some() {
                props.push(Prop::IconOnly(button.icon_only()));
            }
            if let Some(menu) = button.menu() {
                props.push(Prop::Menu(crate::services::context_menu_entries(&menu, &button.sent)));
            }
        }
        Widget::MenuButton { popup, sent, opener, .. } => {
            props.push(Prop::Label(pull_down_title(&node.widget)));
            // Kept: AppKit can't give back the app's function.
            if let Some(opener) = opener {
                props.push(Prop::MenuOnOpen(Some(opener.on_open())));
            }
            props.extend(node.icon.clone().map(Prop::Icon));
            props.extend(node.vector_icon.clone().map(Prop::VectorIcon));
            if node.icon_only.is_some() {
                props.push(Prop::IconOnly(popup.imagePosition() == NSCellImagePosition::ImageOnly));
            }
            if let Some(menu) = popup.menu() {
                let mut entries = crate::services::context_menu_entries(&menu, sent);
                // The title item.
                if !entries.is_empty() {
                    entries.remove(0);
                }
                props.push(Prop::Menu(entries));
            }
        }
        Widget::Group { frame, .. } => {
            let titled = frame.titlePosition() != NSTitlePosition::NoTitle;
            props.push(Prop::Title(if titled { frame.title().to_string() } else { String::new() }));
        }
        Widget::Button(b) => {
            props.push(Prop::Label(b.title().to_string()));
            if node.kind == WidgetKind::ToggleButton {
                props.push(checked(b.state()));
            }
            props.extend(node.icon.clone().map(Prop::Icon));
            props.extend(node.vector_icon.clone().map(Prop::VectorIcon));
            if node.icon_only.is_some() {
                props.push(Prop::IconOnly(b.imagePosition() == NSCellImagePosition::ImageOnly));
            }
            // Drawn into its image: AppKit can't give it back.
            props.extend(node.text_color.map(Prop::TextColor));
        }
        Widget::Icon(view) => {
            if let Some(label) = view.accessibilityLabel() {
                props.push(Prop::Label(label.to_string()));
            }
            props.extend(node.icon.clone().map(Prop::Icon));
            props.extend(node.vector_icon.clone().map(Prop::VectorIcon));
            props.extend(node.icon_size.map(Prop::IconSize));
            if let (Some(sent), Some(shown)) = (node.text_color, view.contentTintColor()) {
                let given = crate::custom::ns_color(sent);
                props.push(Prop::TextColor(if shown.isEqual(Some(&given)) { sent } else { rgba(&shown) }));
            }
        }
        Widget::FileIcon(view) => {
            if let Some(label) = view.accessibilityLabel() {
                props.push(Prop::Label(label.to_string()));
            }
            props.extend(node.file.clone().map(Prop::File));
            props.extend(node.icon_size.map(Prop::IconSize));
            props.extend(node.thumbnail.map(Prop::Thumbnail));
            props.extend(node.file_lookup.map(Prop::FileLookup));
        }
        Widget::Checkbox(b) => {
            props.push(Prop::Label(b.title().to_string()));
            let mixed = b.state() == NSControlStateValueMixed;
            props.push(if mixed { Prop::Checked(node.checked) } else { checked(b.state()) });
            if node.mixed.is_some() {
                props.push(Prop::Mixed(mixed));
            }
        }
        Widget::Switch(s) => {
            if let Some(label) = s.accessibilityLabel() {
                props.push(Prop::Label(label.to_string()));
            }
            props.push(checked(s.state()));
        }
        Widget::RadioGroup(group) => {
            if let Some(label) = group.stack.accessibilityLabel() {
                props.push(Prop::Label(label.to_string()));
            }
            props.push(Prop::Options(group.options()));
            props.push(Prop::SelectedIndex(group.selected()));
            props.push(Prop::Enabled(group.is_enabled()));
        }
        Widget::Select(p) => {
            if let Some(label) = p.accessibilityLabel() {
                props.push(Prop::Label(label.to_string()));
            }
            props.push(Prop::Options(p.itemTitles().iter().map(|t| t.to_string()).collect()));
            let index = p.indexOfSelectedItem();
            props.push(Prop::SelectedIndex((index >= 0).then_some(index as usize)));
        }
        Widget::Slider { slider, step } => {
            if let Some(label) = slider.accessibilityLabel() {
                props.push(Prop::Label(label.to_string()));
            }
            props.push(Prop::Range { min: slider.minValue(), max: slider.maxValue() });
            props.push(Prop::Step(*step));
            props.push(Prop::Number(slider.doubleValue()));
            if node.orientation.is_some() {
                props.push(Prop::Orientation(if slider.isVertical() {
                    Orientation::Vertical
                } else {
                    Orientation::Horizontal
                }));
            }
        }
        Widget::ColorWell(well) => {
            if let Some(label) = well.accessibilityLabel() {
                props.push(Prop::Label(label.to_string()));
            }
            props.push(Prop::ColorValue(super::opaque(&well.color())));
        }
        Widget::NumberInput(n) => {
            if let Some(label) = n.field().accessibilityLabel() {
                props.push(Prop::Label(label.to_string()));
            }
            let stepper = n.stepper();
            props.push(Prop::Range { min: stepper.minValue(), max: stepper.maxValue() });
            props.push(Prop::Step(Some(stepper.increment())));
            props.push(Prop::WrapAround(stepper.valueWraps()));
            // What the field shows, which is the stepper's number.
            props.extend(n.field().stringValue().to_string().parse().ok().map(Prop::Number));
        }
        Widget::Progress(p) => {
            if let Some(label) = p.accessibilityLabel() {
                props.push(Prop::Label(label.to_string()));
            }
            props.push(Prop::Progress((!p.isIndeterminate()).then(|| p.doubleValue())));
        }
        Widget::Spinner { indicator, running } => {
            if let Some(label) = indicator.accessibilityLabel() {
                props.push(Prop::Label(label.to_string()));
            }
            props.push(Prop::Running(*running));
        }
        // AppKit reads it from the frame's shape: keep the app's.
        Widget::Separator(_) => props.extend(node.orientation.map(Prop::Orientation)),
        Widget::Image(view) => {
            if let Some(label) = view.accessibilityLabel() {
                props.push(Prop::Label(label.to_string()));
            }
            props.extend(node.image.clone().map(Prop::Image));
            if node.fit.is_some() {
                props.push(Prop::ImageFit(match view.imageScaling() {
                    NSImageScaling::ScaleAxesIndependently => ImageFit::Stretch,
                    _ => ImageFit::Contain,
                }));
            }
        }
        Widget::GpuSurface(view) => {
            if let Some(label) = view.accessibilityLabel() {
                props.push(Prop::Label(label.to_string()));
            }
            props.push(Prop::TakesInput(view.takes_input()));
            props.push(Prop::PointerLock(view.pointer_locked()));
            props.push(Prop::KeyboardGrab(view.keyboard_grabbed()));
            props.push(Prop::Cursor(view.cursor()));
            // None of these reads back from AppKit: kept as set.
            props.push(Prop::TextInput(view.text_input()));
            props.push(Prop::InputMethod(view.input_method()));
            props.push(Prop::TextCursor(view.text_cursor()));
            props.push(Prop::Transparent(view.transparent()));
        }
        Widget::Scroll(scroll) => {
            let shown = (scroll.hasHorizontalScroller(), scroll.hasVerticalScroller());
            // Hidden scrollers leave only the node to say which axes scroll.
            props.push(Prop::ScrollAxes(match shown {
                (true, true) => ScrollAxes::Both,
                (true, false) => ScrollAxes::Horizontal,
                (false, true) => ScrollAxes::Vertical,
                (false, false) => node.scroll_axes,
            }));
            props.push(Prop::ScrollBars(shown != (false, false)));
        }
        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::List(list) => {
            if node.kind == WidgetKind::Table {
                props.push(Prop::Columns(list.columns()));
                props.push(Prop::Sort(list.sort()));
            }
            match node.kind {
                WidgetKind::Tree => {
                    props.push(Prop::TreeRows(list.tree_rows()));
                    props.extend(list.tree_loading().map(Prop::TreeLoading));
                }
                _ => props.push(Prop::Rows(list.rows())),
            }
            props.extend(list.estimate().map(Prop::EstimatedRowHeight));
            props.push(Prop::SelectionMode(list.mode()));
            props.extend(list.style().map(Prop::ListStyle));
            props.push(Prop::Selected(list.selected()));
            props.extend(list.row_files().map(Prop::RowFiles));
            props.extend(list.moves().map(Prop::RowMoves));
        }
        // Shown or not as the platform shows it, while the core wants it.
        Widget::Popover(popover) => props.push(Prop::PopoverShown(popover.wanted() && popover.shown())),
        Widget::Host(_) => props.extend(node.row.map(|row| match node.column {
            Some(column) => Prop::Cell(mitsuami_core::CellKey { row, column }),
            None => Prop::Row(row),
        })),
        Widget::Sidebar(sidebar) => {
            props.push(Prop::Sections(sidebar.sections()));
            props.push(Prop::SelectedIndex(sidebar.selected()));
            // As the split shows it, or the app wants it before there's one.
            let split = node.parent.and_then(|p| state.nodes.get(&p)).and_then(|p| match &p.widget {
                Widget::Window { split: Some(split), .. } => Some(split),
                _ => None,
            });
            props.extend(
                match split {
                    Some(split) => Some(!split.collapsed()),
                    None => sidebar.shown.get(),
                }
                .map(Prop::SidebarShown),
            );
        }
        Widget::DocumentTabs(tabs) => {
            props.push(Prop::TabTitles(tabs.titles()));
            props.push(Prop::SelectedIndex(tabs.selected()));
            props.extend(tabs.closable().map(Prop::TabsClosable));
            props.extend(tabs.reorderable().map(Prop::TabsReorderable));
            props.extend(tabs.new_tab().map(Prop::NewTabButton));
            props.extend(tabs.style().map(Prop::DocumentTabsStyle));
            props.push(Prop::Enabled(tabs.enabled()));
        }
        Widget::Tabs(tabs) => {
            props.push(Prop::TabTitles(tabs.titles()));
            props.push(Prop::SelectedIndex(tabs.selected()));
            props.extend(node.tab_icons.clone().map(Prop::TabIcons));
        }
        // Where the divider is shows in the panes' frames; the position
        // and least sizes are kept as given.
        Widget::SplitView(split) => {
            props.push(Prop::Orientation(if split.view.isVertical() {
                Orientation::Horizontal
            } else {
                Orientation::Vertical
            }));
            props.extend(split.state.position().map(Prop::Number));
            props.push(Prop::PaneMinimums(split.state.minimums()));
            props.push(Prop::PanesShown(split.shown()));
        }
    }
    if node.file_drop
        && let Widget::Host(host) | Widget::Group { host, .. } = &node.widget
    {
        props.push(Prop::FileDrop(host.file_drop()));
    }
    match &node.widget {
        Widget::Host(host) | Widget::Group { host, .. } => props.extend(host.keys().map(Prop::Keys)),
        Widget::List(list) => props.extend(list.keys().map(Prop::Keys)),
        Widget::Field(_) => props.extend(node._target.as_ref().and_then(|t| t.keys()).map(Prop::Keys)),
        _ => {}
    }
    if let Some(control) = node.widget.control() {
        props.push(Prop::Enabled(control.isEnabled()));
    }
    props.extend(node.text_style.map(Prop::TextStyle));
    props.extend(node.role.map(Prop::ButtonRole));
    // Prominence as the button shows it; the rest as the core sent it.
    let prominent = match &node.widget {
        Widget::Button(b) if node.kind == WidgetKind::Button => Some(super::props::is_prominent(b)),
        Widget::MenuButton { popup, .. } => Some(super::props::is_prominent(popup)),
        _ => None,
    };
    props.extend(node.button_style.map(|style| match (style, prominent) {
        (_, Some(true)) => Prop::ButtonStyle(ButtonStyle::Prominent),
        (ButtonStyle::Prominent, Some(false)) => Prop::ButtonStyle(ButtonStyle::Bordered),
        _ => Prop::ButtonStyle(style),
    }));
    props.extend(node.tabs_style.map(Prop::TabsStyle));
    props.extend(node.tweak.clone().map(Prop::Tweak));
    let view = node.widget.view();
    props.push(Prop::LayoutDirection(match view.userInterfaceLayoutDirection() {
        objc2_app_kit::NSUserInterfaceLayoutDirection::RightToLeft => mitsuami_core::LayoutDirection::RightToLeft,
        _ => mitsuami_core::LayoutDirection::LeftToRight,
    }));
    props.push(Prop::Tooltip(view.toolTip().map(|t| t.to_string()).unwrap_or_default()));
    if let Some((_, area)) = &node.hover {
        props.push(Prop::Hover(view.trackingAreas().iter().any(|a| *a == **area)));
    }
    props.extend(node.header.as_ref().map(|h| Prop::Header(h.on.get())));
    props.extend(node.header_edge.map(Prop::HeaderEdge));
    props.extend(node.sidebar_pane.map(Prop::SidebarPane));
    if node.click_through
        && let Widget::Host(host) = &node.widget
    {
        props.push(Prop::ClickThrough(host.click_through()));
    }
    if let Some((_, recognizer)) = &node.click {
        props.push(Prop::Click(view.gestureRecognizers().iter().any(|r| *r == ***recognizer)));
    }
    if let Some((_, recognizer)) = &node.double_click {
        props.push(Prop::DoubleClick(view.gestureRecognizers().iter().any(|r| *r == ***recognizer)));
    }
    // Kept: AppKit has no error state for a field.
    if let Some(error) = &node.error {
        props.push(Prop::Error(error.clone()));
    }
    // Kept: AppKit can't give back the app's function.
    if let Some((opener, _)) = &node.menu_on_open {
        props.push(Prop::ContextMenuOnOpen(Some(opener.on_open())));
    }
    if let Some((sent, _)) = &node.context_menu {
        props.push(Prop::ContextMenu(match (&node.widget, view.menu()) {
            (Widget::Select(_) | Widget::MenuButton { .. } | Widget::SplitButton(_), _) => sent.clone(),
            (_, Some(menu)) => crate::services::context_menu_entries(&menu, sent),
            (_, None) => Vec::new(),
        }));
    }
    let f = match node.widget {
        // Placed by its frame (see `SetFrame`).
        Widget::Separator(_) => view.frame(),
        // Hidden where the core gave it no room, keeping its frame (see
        // `SetFrame`).
        _ => view.alignmentRectForFrame(view.frame()),
    };
    // A split's pane is in a host of its own (see `SplitView::place`).
    let f = match node.parent.and_then(|p| state.nodes.get(&p)).map(|p| &p.widget) {
        Some(Widget::SplitView(split)) => split.placed(id, view).unwrap_or(f),
        _ => f,
    };
    // Hidden where the core gave it no room, keeping its frame (see
    // `SetFrame`).
    let f = match &node.widget {
        Widget::Tabs(tabs) => tabs.parked.get().unwrap_or(f),
        _ => f,
    };
    let mut frame = Rect::new(f.origin.x as f32, f.origin.y as f32, f.size.width as f32, f.size.height as f32);
    // A row is where the table put it, and so is a cell.
    if let (Some(row), Some(Widget::List(list))) =
        (node.row, node.parent.and_then(|p| state.nodes.get(&p)).map(|p| &p.widget))
    {
        frame = match node.column {
            Some(column) => list.cell_rect(row, column, view),
            None => list.row_rect(row),
        }
        .unwrap_or(frame);
    }
    // So is a page, by its tab view; one not shown isn't anywhere.
    if let Some(Widget::Tabs(tabs)) = node.parent.and_then(|p| state.nodes.get(&p)).map(|p| &p.widget) {
        frame = tabs.page_frame(id).unwrap_or(frame);
    }
    // A toolbar's button is its item, all of it.
    if let Some(item) = state.toolbar_item_of(id)
        && let Some(Widget::Window { toolbar: Some(toolbar), .. }) =
            state.nodes[&item].parent.and_then(|w| state.nodes.get(&w)).map(|w| &w.widget)
        && let Some(size) = toolbar.adopted_size(item)
    {
        frame = Rect::new(0.0, 0.0, size.width as f32, size.height as f32);
    }
    // So is a toolbar item, by the toolbar; an empty one isn't shown.
    if let Some(Widget::Window { host, toolbar: Some(toolbar), .. }) = node
        .parent
        .filter(|_| node.kind == WidgetKind::ToolbarItem)
        .and_then(|p| state.nodes.get(&p))
        .map(|p| &p.widget)
    {
        let f = toolbar.frame(id, host).unwrap_or(crate::classes::zero_rect());
        frame = Rect::new(f.origin.x as f32, f.origin.y as f32, f.size.width as f32, f.size.height as f32);
    }
    // A popover is where the platform shows it, by its parent; hidden,
    // it isn't shown.
    if let Widget::Popover(popover) = &node.widget {
        let f = popover.frame().unwrap_or(crate::classes::zero_rect());
        frame = Rect::new(f.origin.x as f32, f.origin.y as f32, f.size.width as f32, f.size.height as f32);
    }
    // A sidebar is where the split put it, beside the content (so at
    // negative x), and full height; collapsed, it isn't shown.
    if let Some(Widget::Window { host, split: Some(split), .. }) =
        node.parent.filter(|_| node.kind == WidgetKind::Sidebar).and_then(|p| state.nodes.get(&p)).map(|p| &p.widget)
    {
        let f = if split.collapsed() {
            crate::classes::zero_rect()
        } else {
            view.convertRect_toView(view.bounds(), Some(host))
        };
        frame = Rect::new(f.origin.x as f32, f.origin.y as f32, f.size.width as f32, f.size.height as f32);
    }
    let by_view = state.by_view.borrow();
    let (children, scroll_offset) = match &node.widget {
        Widget::List(list) => {
            let origin = crate::classes::scrolled(&list.scroll.contentView());
            (list.children(), Some(Point::new(origin.x as f32, origin.y as f32)))
        }
        Widget::TextArea(area) => {
            let origin = crate::classes::scrolled(&area.scroll.contentView());
            (Vec::new(), Some(Point::new(origin.x as f32, origin.y as f32)))
        }
        Widget::Tabs(tabs) => (tabs.ids(), None),
        // Each pane is in a host of its own (see `SplitView::insert`).
        Widget::SplitView(split) => (
            split
                .view
                .subviews()
                .iter()
                .flat_map(|host| {
                    host.subviews().iter().filter_map(|v| by_view.get(&key(&v)).copied()).collect::<Vec<_>>()
                })
                .collect(),
            None,
        ),
        Widget::Scroll(scroll) => {
            let origin = crate::classes::scrolled(&scroll.contentView());
            (
                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)),
            )
        }
        _ => {
            let parent: &NSView = node.header.as_ref().map_or(view, |h| &h.content);
            let mut children: Vec<NodeId> =
                parent.subviews().iter().filter_map(|v| by_view.get(&key(&v)).copied()).collect();
            if let Widget::Window { toolbar: Some(toolbar), .. } = &node.widget {
                children.extend(toolbar.ids());
            }
            if let Widget::Window { split: Some(split), .. } = &node.widget {
                children.push(split.sidebar);
            }
            // Popovers point at their parent, after what it shows, in the
            // order they came.
            let mut popovers: Vec<NodeId> = state
                .nodes
                .iter()
                .filter(|(_, n)| n.parent == Some(id) && matches!(n.widget, Widget::Popover(_)))
                .map(|(c, _)| *c)
                .collect();
            popovers.sort_by_key(|c| c.raw());
            children.extend(popovers);
            // An item's button is its view, not in its host.
            if node.kind == WidgetKind::ToolbarItem
                && let Some(Widget::Window { toolbar: Some(toolbar), .. }) =
                    node.parent.and_then(|w| state.nodes.get(&w)).map(|w| &w.widget)
                && let Some(button) = toolbar.adopted_view(id)
            {
                children.extend(by_view.get(&key(button)).copied());
            }
            (children, None)
        }
    };
    Some(NativeState {
        kind: node.kind,
        props,
        frame,
        parent: node.parent,
        children,
        focused: focused(&node.widget),
        scroll_offset,
        viewport_insets: match &node.widget {
            Widget::Scroll(scroll) => Some(crate::classes::viewport_insets(scroll)),
            _ => None,
        },
        selection: super::selection::selection(&node.widget, focused(&node.widget)),
    })
}

fn focused(widget: &Widget) -> bool {
    let view = widget.key_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(),
        Widget::NumberInput(n) => n.field().currentEditor().is_some(),
        Widget::RadioGroup(group) => group.has_focus(&responder),
        _ => std::ptr::eq(&*responder as *const _ as *const NSView, &*view as *const NSView),
    }
}

/// A colour as sRGB components, for reporting one that isn't the given one.
pub(crate) fn rgba(color: &NSColor) -> Color {
    let Some(color) = color.colorUsingColorSpace(&NSColorSpace::sRGBColorSpace()) else {
        return Color::Rgba(0, 0, 0, 0);
    };
    let c = |v: f64| (v * 255.0).round().clamp(0.0, 255.0) as u8;
    Color::Rgba(c(color.redComponent()), c(color.greenComponent()), c(color.blueComponent()), c(color.alphaComponent()))
}