ferrokit 0.15.1

Native macOS GUI framework for Rust: every view a real AppKit control (NSTableView, NSOutlineView, NSTextView), updated in place by fine-grained signals
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
//! A native outline (`NSOutlineView`) over a tree from signals, and the
//! source-list sidebar built on it.
//!
//! Each item gets a stable Objective-C object, reused by id when the tree
//! changes, so AppKit keeps expansion and selection across updates.

use std::cell::RefCell;
use std::collections::HashMap;
use std::hash::{DefaultHasher, Hash, Hasher};
use std::rc::{Rc, Weak};

use objc2::rc::Retained;
use objc2::runtime::{AnyObject, NSObject, NSObjectProtocol, ProtocolObject};
use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send};
use objc2_app_kit::{
    NSControlTextEditingDelegate, NSImage, NSImageView, NSOutlineView, NSOutlineViewDataSource, NSOutlineViewDelegate,
    NSScrollView, NSTableCellView, NSTableColumn, NSTableViewStyle, NSTextField, NSUserInterfaceItemIdentification, NSView,
};
use objc2_foundation::{NSIndexSet, NSInteger, NSNotification, NSString};

use crate::signal::{Effect, Signal, untrack};
use crate::view::{Cx, Identifiable, Kind, Node, Size, View};

/// One item of a tree, with its children.
#[derive(Debug, Clone)]
pub struct TreeNode<T> {
    /// The item.
    pub value: T,
    /// Its children (empty for a leaf).
    pub children: Vec<TreeNode<T>>,
}

impl<T> TreeNode<T> {
    /// A leaf.
    pub fn leaf(value: T) -> Self {
        TreeNode { value, children: Vec::new() }
    }

    /// An item with children.
    pub fn branch(value: T, children: Vec<TreeNode<T>>) -> Self {
        TreeNode { value, children }
    }
}

struct Entry {
    key: u64,
    title: String,
    /// An SF Symbol and its colour.
    icon: Option<(String, Option<crate::Color>)>,
    /// A count or short word at the row's end.
    badge: Option<String>,
    /// The text of each extra column (see `Outline::column`).
    columns: Vec<String>,
    children: Vec<usize>,
    expandable: bool,
}

#[derive(Default)]
struct State {
    entries: Vec<Entry>,
    roots: Vec<usize>,
    /// The object AppKit sees for each entry (index-aligned).
    items: Vec<Retained<OutlineItem>>,
    /// Item objects by key, kept across rebuilds (stable identity).
    by_key: HashMap<u64, Retained<OutlineItem>>,
    group_roots: bool,
    on_select: Option<Box<dyn Fn(Option<usize>)>>,
    /// An item whose children load on demand was expanded (see
    /// `Outline::lazy_children`).
    on_expand: Option<Rc<dyn Fn(usize)>>,
    /// Set while the outline changes selection itself (no callback).
    quiet: bool,
}

define_class!(
    // AppKit's handle for one tree item: the index of its entry.
    #[unsafe(super(NSObject))]
    #[thread_kind = MainThreadOnly]
    #[name = "FerrokitOutlineItem"]
    #[ivars = std::cell::Cell<usize>]
    struct OutlineItem;
);

impl OutlineItem {
    fn new(mtm: MainThreadMarker, index: usize) -> Retained<Self> {
        let this = Self::alloc(mtm).set_ivars(std::cell::Cell::new(index));
        // SAFETY: NSObject's designated initialiser.
        unsafe { msg_send![super(this), init] }
    }
}

define_class!(
    // Data source and delegate for one outline view.
    #[unsafe(super(NSObject))]
    #[thread_kind = MainThreadOnly]
    #[name = "FerrokitOutlineSource"]
    #[ivars = RefCell<Weak<RefCell<State>>>]
    struct Source;

    unsafe impl NSObjectProtocol for Source {}
    unsafe impl NSControlTextEditingDelegate for Source {}

    unsafe impl NSOutlineViewDataSource for Source {
        #[unsafe(method(outlineView:numberOfChildrenOfItem:))]
        fn count(&self, _ov: &NSOutlineView, item: Option<&AnyObject>) -> NSInteger {
            crate::failure::guard("an outline (count)", 0, || {
                self.with(|s| match index_of(item) {
                    None => s.roots.len(),
                    Some(i) => s.entries.get(i).map_or(0, |e| e.children.len()),
                }) as NSInteger
            })
        }

        #[unsafe(method_id(outlineView:child:ofItem:))]
        fn child(&self, _ov: &NSOutlineView, index: NSInteger, item: Option<&AnyObject>) -> Retained<AnyObject> {
            // An item AppKit asks for that isn't there (the tree changed
            // under it) is an empty one, not a panic inside AppKit.
            let found = crate::failure::guard("an outline (child)", None, || {
                let state = self.ivars().borrow().upgrade()?;
                let s = state.borrow();
                let list = match index_of(item) {
                    None => &s.roots,
                    Some(i) => &s.entries.get(i)?.children,
                };
                s.items.get(*list.get(index as usize)?).cloned()
            });
            match found {
                Some(item) => Retained::into_super(Retained::into_super(item)),
                None => Retained::into_super(NSObject::new()),
            }
        }

        #[unsafe(method(outlineView:isItemExpandable:))]
        fn expandable(&self, _ov: &NSOutlineView, item: &AnyObject) -> bool {
            crate::failure::guard("an outline (expandable)", false, || {
                self.with(|s| index_of(Some(item)).and_then(|i| s.entries.get(i)).is_some_and(|e| e.expandable))
            })
        }
    }

    unsafe impl NSOutlineViewDelegate for Source {
        #[unsafe(method_id(outlineView:viewForTableColumn:item:))]
        fn view_for(&self, ov: &NSOutlineView, column: Option<&NSTableColumn>, item: &AnyObject) -> Option<Retained<NSView>> {
            crate::failure::guard("an outline (view_for)", None, || {
                // An extra column's cell: its text ("column.2", "column-right.3").
                let extra = column.and_then(|c| {
                    let id = c.identifier().to_string();
                    let (kind, n) = id.split_once('.')?;
                    Some((kind == "column-right", n.parse::<usize>().ok()?))
                });
                if let Some((right, n)) = extra {
                    let text = self.with(|s| index_of(Some(item)).and_then(|i| s.entries.get(i)).and_then(|e| e.columns.get(n).cloned()));
                    text.map(|t| column_cell(ov, &t, right))
                } else {
                    self.tree_cell(ov, item)
                }
            })
        }

        #[unsafe(method(outlineView:isGroupItem:))]
        fn is_group(&self, _ov: &NSOutlineView, item: &AnyObject) -> bool {
            crate::failure::guard("an outline (is_group)", false, || {
                self.with(|s| s.group_roots && index_of(Some(item)).is_some_and(|i| s.roots.contains(&i)))
            })
        }
        #[unsafe(method(outlineView:shouldSelectItem:))]
        fn should_select(&self, _ov: &NSOutlineView, item: &AnyObject) -> bool {
            crate::failure::guard("an outline (should_select)", false, || {
                // Section headers of a sidebar aren't selectable.
                !self.with(|s| s.group_roots && index_of(Some(item)).is_some_and(|i| s.roots.contains(&i)))
            })
        }

        #[unsafe(method(outlineViewItemWillExpand:))]
        fn will_expand(&self, notification: &NSNotification) {
            let item = notification.userInfo().and_then(|u| u.objectForKey(&NSString::from_str("NSObject")));
            let Some(index) = index_of(item.as_deref()) else { return };
            let Some(state) = self.ivars().borrow().upgrade() else { return };
            let s = state.borrow();
            // Only an item that has no children yet: load them, after
            // AppKit has expanded it (the tree is rebuilt when they arrive,
            // and stays expanded).
            if s.quiet || s.entries.get(index).is_none_or(|e| !e.children.is_empty()) {
                return;
            }
            if let Some(load) = s.on_expand.clone() {
                // By its key: the tree may be rebuilt before this runs, and
                // the same place in it be another item's.
                let (key, state) = (s.entries[index].key, state.clone());
                crate::later(move || {
                    let index = state.borrow().entries.iter().position(|e| e.key == key);
                    if let Some(index) = index {
                        crate::failure::entry("an outline's children", (), || crate::batch(|| load(index)));
                    }
                });
            }
        }

        #[unsafe(method(outlineViewSelectionDidChange:))]
        fn selection_did_change(&self, notification: &NSNotification) {
            let Some(ov) = notification.object().and_then(|o| o.downcast::<NSOutlineView>().ok()) else { return };
            let Some(state) = self.ivars().borrow().upgrade() else { return };
            if state.borrow().quiet {
                return;
            }
            let row = ov.selectedRow();
            let index = (row >= 0).then(|| ov.itemAtRow(row)).flatten().and_then(|i| index_of(Some(&i)));
            // Take the callback out while it runs: it may update the tree.
            let cb = state.borrow_mut().on_select.take();
            if let Some(cb) = &cb {
                crate::failure::entry("an outline's selection", (), || cb(index));
            }
            let mut s = state.borrow_mut();
            if s.on_select.is_none() {
                s.on_select = cb;
            }
        }
    }
);

impl Source {
    fn new(mtm: MainThreadMarker, state: &Rc<RefCell<State>>) -> Retained<Self> {
        let this = Self::alloc(mtm).set_ivars(RefCell::new(Rc::downgrade(state)));
        // SAFETY: NSObject's designated initialiser.
        unsafe { msg_send![super(this), init] }
    }

    fn tree_cell(&self, ov: &NSOutlineView, item: &AnyObject) -> Option<Retained<NSView>> {
        let found = self.with(|s| {
            index_of(Some(item)).and_then(|i| {
                s.entries.get(i).map(|e| (e.title.clone(), e.icon.clone(), e.badge.clone(), s.group_roots && s.roots.contains(&i)))
            })
        });
        found.map(|(title, icon, badge, group)| cell(ov, &title, icon.as_ref().map(|(n, c)| (n.as_str(), *c)), badge.as_deref(), group))
    }

    fn with<R: Default>(&self, f: impl FnOnce(&State) -> R) -> R {
        self.ivars().borrow().upgrade().map(|s| f(&s.borrow())).unwrap_or_default()
    }
}

fn index_of(item: Option<&AnyObject>) -> Option<usize> {
    item.and_then(|i| i.downcast_ref::<OutlineItem>()).map(|i| i.ivars().get())
}

/// The badge's label in a cell (its tag).
const BADGE_TAG: isize = 0x0bad6e;

/// A row: optional SF Symbol, a title and a badge (reused by identifier).
fn cell(ov: &NSOutlineView, title: &str, icon: Option<(&str, Option<crate::Color>)>, badge: Option<&str>, group: bool) -> Retained<NSView> {
    let mtm = MainThreadMarker::from(ov);
    let ident = NSString::from_str(if group { "group" } else if icon.is_some() { "icon" } else { "plain" });
    // SAFETY: reuse lookup by identifier; owner may be nil.
    let reused = unsafe { ov.makeViewWithIdentifier_owner(&ident, None) }.and_then(|v| v.downcast::<NSTableCellView>().ok());
    let view = reused.unwrap_or_else(|| {
        let v = NSTableCellView::new(mtm);
        v.setIdentifier(Some(&ident));
        let text = NSTextField::labelWithString(&NSString::new(), mtm);
        text.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
        if group {
            // Section headings: small, bold and secondary, as in Finder's
            // and Mail's sidebars.
            text.setFont(Some(&objc2_app_kit::NSFont::boldSystemFontOfSize(objc2_app_kit::NSFont::smallSystemFontSize())));
            text.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
        }
        v.addSubview(&text);
        // SAFETY: the cell view keeps its subviews; these are weak conveniences.
        unsafe { v.setTextField(Some(&text)) };
        // Centred in the row, whatever its height: the sidebar's rows follow
        // the user's sidebar icon size (System Settings › Appearance).
        let center = |sub: &NSView| {
            sub.setTranslatesAutoresizingMaskIntoConstraints(false);
            sub.centerYAnchor().constraintEqualToAnchor(&v.centerYAnchor()).setActive(true);
        };
        center(&text);
        if group {
            text.trailingAnchor().constraintLessThanOrEqualToAnchor_constant(&v.trailingAnchor(), -2.0).setActive(true);
        } else {
            // The badge: secondary, its digits all one width, at the end
            // (hidden while there's none).
            let badge = NSTextField::labelWithString(&NSString::new(), mtm);
            badge.setTag(BADGE_TAG);
            badge.setFont(Some(&objc2_app_kit::NSFont::monospacedDigitSystemFontOfSize_weight(objc2_app_kit::NSFont::smallSystemFontSize(), 0.0)));
            badge.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
            badge.setAlignment(objc2_app_kit::NSTextAlignment::Right);
            badge.setHidden(true);
            v.addSubview(&badge);
            center(&badge);
            badge.trailingAnchor().constraintEqualToAnchor_constant(&v.trailingAnchor(), -6.0).setActive(true);
            badge.setContentCompressionResistancePriority_forOrientation(750.0, objc2_app_kit::NSLayoutConstraintOrientation::Horizontal);
            text.trailingAnchor().constraintLessThanOrEqualToAnchor_constant(&badge.leadingAnchor(), -6.0).setActive(true);
        }
        // (Lower priority than the outline's own width.)
        text.setContentCompressionResistancePriority_forOrientation(250.0, objc2_app_kit::NSLayoutConstraintOrientation::Horizontal);
        if icon.is_some() {
            let image = NSImageView::new(mtm);
            // The icon is decoration: the title names the row. (macOS 15 and
            // 26 otherwise read an unnamed image in every row.) The view's
            // cell answers for it there, so hide both.
            objc2_app_kit::NSAccessibility::setAccessibilityElement(&*image, false);
            if let Some(cell) = image.cell() {
                // SAFETY: NSAccessibility's setter taking a BOOL.
                let () = unsafe { objc2::msg_send![&*cell, setAccessibilityElement: false] };
            }
            v.addSubview(&image);
            // SAFETY: as above.
            unsafe { v.setImageView(Some(&image)) };
            center(&image);
            image.leadingAnchor().constraintEqualToAnchor_constant(&v.leadingAnchor(), 2.0).setActive(true);
            image.widthAnchor().constraintEqualToConstant(20.0).setActive(true);
            text.leadingAnchor().constraintEqualToAnchor_constant(&image.trailingAnchor(), 6.0).setActive(true);
        } else {
            text.leadingAnchor().constraintEqualToAnchor_constant(&v.leadingAnchor(), 2.0).setActive(true);
        }
        v
    });
    // SAFETY: reading the cell's outlets on the main thread.
    if let Some(t) = unsafe { view.textField() } {
        t.setStringValue(&NSString::from_str(title));
    }
    if let Some(b) = view.viewWithTag(BADGE_TAG).and_then(|b| b.downcast::<NSTextField>().ok()) {
        b.setStringValue(&NSString::from_str(badge.unwrap_or_default()));
        b.setHidden(badge.is_none_or(str::is_empty));
    }
    if let (Some((name, tint)), Some(iv)) = (icon, unsafe { view.imageView() }) {
        iv.setImage(NSImage::imageWithSystemSymbolName_accessibilityDescription(&NSString::from_str(name), None).as_deref());
        // A reused cell keeps its last tint unless it's set every time.
        iv.setContentTintColor(tint.map(|c| c.ns()).as_deref());
    }
    Retained::into_super(view)
}

/// An extra column's cell: its text, secondary, right-aligned with digits
/// all one width for numbers (as the Finder's Size column).
fn column_cell(ov: &NSOutlineView, text: &str, right: bool) -> Retained<NSView> {
    let mtm = MainThreadMarker::from(ov);
    let ident = NSString::from_str(if right { "column-right" } else { "column" });
    // SAFETY: reuse lookup by identifier; owner may be nil.
    let reused = unsafe { ov.makeViewWithIdentifier_owner(&ident, None) }.and_then(|v| v.downcast::<NSTableCellView>().ok());
    let view = reused.unwrap_or_else(|| {
        let v = NSTableCellView::new(mtm);
        v.setIdentifier(Some(&ident));
        let field = NSTextField::labelWithString(&NSString::new(), mtm);
        field.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
        field.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
        if right {
            field.setAlignment(objc2_app_kit::NSTextAlignment::Right);
            field.setFont(Some(&objc2_app_kit::NSFont::monospacedDigitSystemFontOfSize_weight(objc2_app_kit::NSFont::systemFontSize(), 0.0)));
        }
        v.addSubview(&field);
        // SAFETY: the cell view keeps its subviews; this is a weak convenience.
        unsafe { v.setTextField(Some(&field)) };
        field.setTranslatesAutoresizingMaskIntoConstraints(false);
        field.centerYAnchor().constraintEqualToAnchor(&v.centerYAnchor()).setActive(true);
        field.leadingAnchor().constraintEqualToAnchor_constant(&v.leadingAnchor(), 2.0).setActive(true);
        field.trailingAnchor().constraintEqualToAnchor_constant(&v.trailingAnchor(), -2.0).setActive(true);
        field.setContentCompressionResistancePriority_forOrientation(250.0, objc2_app_kit::NSLayoutConstraintOrientation::Horizontal);
        v
    });
    // SAFETY: reading the cell's outlet on the main thread.
    if let Some(t) = unsafe { view.textField() } {
        t.setStringValue(&NSString::from_str(text));
    }
    Retained::into_super(view)
}

fn key_of<K: Hash>(id: &K) -> u64 {
    let mut h = DefaultHasher::new();
    id.hash(&mut h);
    h.finish()
}

type Roots<T> = Box<dyn Fn() -> Vec<TreeNode<T>>>;
/// An item's SF Symbol name, if any.
type IconFn<T> = dyn Fn(&T) -> Option<String>;
/// An item's icon colour, if it has its own.
type TintFn<T> = dyn Fn(&T) -> Option<crate::Color>;
/// An item's badge, if any.
type BadgeFn<T> = dyn Fn(&T) -> Option<String>;
/// An extra column's text for an item.
type TextFn<T> = dyn Fn(&T) -> String;
/// Whether an item has children not read yet.
type HasFn<T> = dyn Fn(&T) -> bool;
/// Lazy children: which items have them, and what loads them.
type Lazy<T> = (Rc<HasFn<T>>, Rc<dyn Fn(<T as Identifiable>::Id)>);
/// An item's symbol and colour.
type LookFn<T> = dyn Fn(&T) -> Option<(String, Option<crate::Color>)>;

/// A native outline view over a tree (see the module docs).
pub struct Outline<T: Identifiable + 'static> {
    roots: Roots<T>,
    title: Rc<dyn Fn(&T) -> String>,
    icon: Option<Rc<IconFn<T>>>,
    tint: Option<Rc<TintFn<T>>>,
    badge: Option<Rc<BadgeFn<T>>>,
    columns: Vec<OutlineColumn<T>>,
    lazy: Option<Lazy<T>>,
    selection: Option<Signal<Option<T::Id>>>,
    sidebar: bool,
    expanded: bool,
    transparent: bool,
}

/// An extra column of an outline (see [`Outline::column`]).
struct OutlineColumn<T> {
    title: String,
    width: f64,
    right: bool,
    value: Rc<TextFn<T>>,
}

impl<T: Identifiable + 'static> Outline<T> {
    /// Every item shown expanded, each time the tree changes (a plan, a
    /// document's outline: trees read whole).
    pub fn expanded(mut self) -> Self {
        self.expanded = true;
        self
    }

    /// No background of its own: the rows sit on whatever is behind the
    /// outline (a card, a tinted panel), as a sidebar's do. Without it an
    /// outline draws the system's content background, which in Dark Mode
    /// differs from a card's control background.
    pub fn transparent_background(mut self) -> Self {
        self.transparent = true;
        self
    }

    /// An SF Symbol per item (or `None`).
    pub fn icon(mut self, f: impl Fn(&T) -> Option<String> + 'static) -> Self {
        self.icon = Some(Rc::new(f));
        self
    }

    /// A colour per item's icon (or `None` for the sidebar's own), as
    /// Mail's mailboxes and Reminders' lists show theirs.
    pub fn icon_color(mut self, f: impl Fn(&T) -> Option<crate::Color> + 'static) -> Self {
        self.tint = Some(Rc::new(f));
        self
    }

    /// A badge per item (or `None`): a count or a short word at the end of
    /// its row, in secondary text, as Mail's unread counts are. It's read
    /// when the tree is, so a signal the tree reads updates it.
    pub fn badge(mut self, f: impl Fn(&T) -> Option<String> + 'static) -> Self {
        self.badge = Some(Rc::new(f));
        self
    }

    /// A column beside the tree, as the Finder's list view has (Date
    /// Modified, Kind): its title, width and each item's text. With columns
    /// the outline shows a header, and the tree's own column is titled
    /// "Name".
    pub fn column(mut self, title: &str, width: f64, value: impl Fn(&T) -> String + 'static) -> Self {
        self.columns.push(OutlineColumn { title: title.into(), width, right: false, value: Rc::new(value) });
        self
    }

    /// A column of numbers or sizes: as [`Outline::column`], right-aligned
    /// with digits all one width (the Finder's Size).
    pub fn number_column(mut self, title: &str, width: f64, value: impl Fn(&T) -> String + 'static) -> Self {
        self.columns.push(OutlineColumn { title: title.into(), width, right: true, value: Rc::new(value) });
        self
    }

    /// Items for which `has_children` is true are expandable before their
    /// children are known (a folder not read yet): expanding one calls
    /// `load` with its id, which reads them and puts them in the tree the
    /// outline shows (setting a signal it reads). Expanded items stay
    /// expanded when the tree changes.
    pub fn lazy_children(mut self, has_children: impl Fn(&T) -> bool + 'static, load: impl Fn(T::Id) + 'static) -> Self {
        self.lazy = Some((Rc::new(has_children), Rc::new(load)));
        self
    }

    /// Two-way selection by item id.
    pub fn selection(mut self, selected: &Signal<Option<T::Id>>) -> Self {
        self.selection = Some(*selected);
        self
    }
}

impl<T: Identifiable + 'static> View for Outline<T> {
    fn build(self, cx: &mut Cx) -> Node {
        let mtm = cx.mtm;
        let ov = NSOutlineView::new(mtm);
        let column = NSTableColumn::initWithIdentifier(NSTableColumn::alloc(mtm), &NSString::from_str("title"));
        ov.addTableColumn(&column);
        // SAFETY: the column was just added to this outline.
        unsafe { ov.setOutlineTableColumn(Some(&column)) };
        if self.columns.is_empty() {
            ov.setHeaderView(None);
        } else {
            column.setTitle(&NSString::from_str(&crate::t("Name")));
            column.setWidth(220.0);
            column.setMinWidth(80.0);
            for (n, c) in self.columns.iter().enumerate() {
                let kind = if c.right { "column-right" } else { "column" };
                let extra = NSTableColumn::initWithIdentifier(NSTableColumn::alloc(mtm), &NSString::from_str(&format!("{kind}.{n}")));
                extra.setTitle(&NSString::from_str(&c.title));
                extra.setWidth(c.width);
                extra.setMinWidth(40.0);
                ov.addTableColumn(&extra);
            }
            ov.setColumnAutoresizingStyle(objc2_app_kit::NSTableViewColumnAutoresizingStyle::FirstColumnOnlyAutoresizingStyle);
        }
        if self.sidebar {
            ov.setStyle(NSTableViewStyle::SourceList);
            ov.setFloatsGroupRows(false);
            // The user's sidebar icon size (small, medium, large), as in
            // Finder and Mail; the cells' fonts and symbols follow it.
            ov.setRowSizeStyle(objc2_app_kit::NSTableViewRowSizeStyle::Default);
        }
        let scroll = NSScrollView::new(mtm);
        scroll.setDocumentView(Some(&ov));
        scroll.setHasVerticalScroller(true);
        scroll.setAutohidesScrollers(true);
        if self.sidebar || self.transparent {
            scroll.setDrawsBackground(false);
        }
        if self.transparent {
            ov.setBackgroundColor(&objc2_app_kit::NSColor::clearColor());
        }

        let state = Rc::new(RefCell::new(State { group_roots: self.sidebar, ..State::default() }));
        let source = Source::new(mtm, &state);
        // SAFETY: data source and delegate are weak in AppKit; the node keeps the source.
        unsafe {
            ov.setDataSource(Some(ProtocolObject::from_ref(&*source)));
            ov.setDelegate(Some(ProtocolObject::from_ref(&*source)));
        }

        // Typed ids, index-aligned with the entries.
        let ids: Rc<RefCell<Vec<T::Id>>> = Rc::default();
        if let Some(sel) = &self.selection {
            let (sel, ids) = (*sel, ids.clone());
            state.borrow_mut().on_select = Some(Box::new(move |i| {
                sel.set(i.and_then(|i| ids.borrow().get(i).cloned()));
            }));
        }

        let lazy = self.lazy.clone();
        if let Some((_, load)) = &self.lazy {
            let (load, ids) = (load.clone(), ids.clone());
            state.borrow_mut().on_expand = Some(Rc::new(move |i| {
                let id = ids.borrow().get(i).cloned();
                if let Some(id) = id {
                    load(id);
                }
            }));
        }
        let (mut node, _) = Node::leaf(cx, Retained::into_super(scroll), (true, true), Size { w: 160.0, h: 120.0 });
        if let Kind::Leaf(l) = &node.kind {
            l.content.set(Some(Size { w: 160.0, h: 120.0 }));
        }

        // Selects the item whose id the selection signal holds (quietly);
        // used when the signal changes and after a reload, which clears
        // AppKit's selection.
        let restore: Rc<dyn Fn()> = {
            let (st, ids, ov3, sel) = (state.clone(), ids.clone(), ov.clone(), self.selection);
            Rc::new(move || {
                let Some(sel) = &sel else { return };
                let want = sel.get();
                untrack(|| {
                    let index = want.and_then(|id| ids.borrow().iter().position(|x| *x == id));
                    let item = index.and_then(|i| st.borrow().items.get(i).cloned());
                    // SAFETY: an item object this outline returned.
                    let row = item.map_or(-1, |it| unsafe { ov3.rowForItem(Some(&it)) });
                    if ov3.selectedRow() != row {
                        st.borrow_mut().quiet = true;
                        if row >= 0 {
                            ov3.selectRowIndexes_byExtendingSelection(&NSIndexSet::indexSetWithIndex(row as usize), false);
                        } else {
                            // SAFETY: nil sender.
                            unsafe { ov3.deselectAll(None) };
                        }
                        st.borrow_mut().quiet = false;
                    }
                });
            })
        };

        // Rebuild when the tree's signals change; keep item objects by id.
        let (roots_fn, title, sidebar, expanded) = (self.roots, self.title, self.sidebar, self.expanded);
        let tint = self.tint;
        let badge = self.badge;
        let columns: Vec<Rc<TextFn<T>>> = self.columns.iter().map(|c| c.value.clone()).collect();
        let has_children: Option<Rc<HasFn<T>>> = lazy.map(|(h, _)| h);
        let icon: Option<Rc<LookFn<T>>> = self.icon.map(|f| Rc::new(move |v: &T| f(v).map(|name| (name, tint.as_ref().and_then(|t| t(v))))) as Rc<LookFn<T>>);
        let (st, ids2, ov2, restore2) = (state.clone(), ids.clone(), ov.clone(), restore.clone());
        node.own(Effect::new(move || {
            let roots = roots_fn();
            untrack(|| {
                // What the user has expanded, kept through the reload. (Asked
                // before the state is borrowed: AppKit may ask the data
                // source while it answers.)
                let shown: Vec<(u64, Retained<OutlineItem>)> = {
                    let s = st.borrow();
                    s.entries.iter().zip(&s.items).map(|(e, it)| (e.key, it.clone())).collect()
                };
                let open: std::collections::HashSet<u64> = shown
                    .into_iter()
                    // SAFETY: an item object this outline returned.
                    .filter(|(_, it)| unsafe { ov2.isItemExpanded(Some(it)) })
                    .map(|(key, _)| key)
                    .collect();
                let mut s = st.borrow_mut();
                let old = std::mem::take(&mut s.by_key);
                let (mut entries, mut items, mut keys, mut typed) = (Vec::new(), Vec::new(), HashMap::new(), Vec::new());
                struct Look<'a, T> {
                    title: &'a dyn Fn(&T) -> String,
                    icon: Option<&'a LookFn<T>>,
                    badge: Option<&'a BadgeFn<T>>,
                    columns: &'a [Rc<TextFn<T>>],
                    has_children: Option<&'a HasFn<T>>,
                }
                fn walk<T: Identifiable>(n: TreeNode<T>, out: &mut Vec<Entry>, typed: &mut Vec<T::Id>, look: &Look<T>) -> usize {
                    let index = out.len();
                    let id = n.value.id();
                    out.push(Entry {
                        key: key_of(&id),
                        title: (look.title)(&n.value),
                        icon: look.icon.and_then(|f| f(&n.value)),
                        badge: look.badge.and_then(|f| f(&n.value)),
                        columns: look.columns.iter().map(|f| f(&n.value)).collect(),
                        children: Vec::new(),
                        expandable: !n.children.is_empty() || look.has_children.is_some_and(|f| f(&n.value)),
                    });
                    typed.push(id);
                    let kids: Vec<usize> = n.children.into_iter().map(|c| walk(c, out, typed, look)).collect();
                    out[index].children = kids;
                    index
                }
                let look = Look { title: &*title, icon: icon.as_deref(), badge: badge.as_deref(), columns: &columns, has_children: has_children.as_deref() };
                let root_idx: Vec<usize> = roots.into_iter().map(|r| walk(r, &mut entries, &mut typed, &look)).collect();
                for (i, e) in entries.iter().enumerate() {
                    let item = old.get(&e.key).cloned().unwrap_or_else(|| OutlineItem::new(mtm, i));
                    item.ivars().set(i);
                    keys.insert(e.key, item.clone());
                    items.push(item);
                }
                s.entries = entries;
                s.roots = root_idx;
                s.items = items;
                s.by_key = keys;
                *ids2.borrow_mut() = typed;
                s.quiet = true;
                drop(s);
                ov2.reloadData();
                // Parents come before their children (the entries are in
                // tree order), so each is expanded inside an expanded one.
                let again: Vec<_> = {
                    let s = st.borrow();
                    s.entries.iter().zip(&s.items).filter(|(e, _)| open.contains(&e.key)).map(|(_, it)| it.clone()).collect()
                };
                for it in again {
                    // SAFETY: an item object this outline returned.
                    unsafe { ov2.expandItem(Some(&it)) };
                }
                if expanded {
                    // SAFETY: nil expands every root, with its children.
                    unsafe { ov2.expandItem_expandChildren(None, true) };
                } else if sidebar {
                    // Sections start expanded: the ones new in this tree.
                    // One the user closed stays closed when the tree is
                    // rebuilt (a badge changed).
                    let roots: Vec<_> = {
                        let s = st.borrow();
                        s.roots.iter().filter(|&&i| !old.contains_key(&s.entries[i].key)).map(|&i| s.items[i].clone()).collect()
                    };
                    for r in roots {
                        // SAFETY: an item object this outline returned.
                        unsafe { ov2.expandItem(Some(&r)) };
                    }
                }
                st.borrow_mut().quiet = false;
                untrack(|| restore2());
            });
        }));

        // Selection signal → outline (quietly).
        if self.selection.is_some() {
            node.own(Effect::new(move || restore()));
        }
        node.keep(Retained::into_super(source));
        node.hold(state);
        node
    }
}

/// A native outline: `roots` (reading signals) gives the tree, `title` each
/// item's text.
pub fn outline<T: Identifiable + 'static>(
    roots: impl Fn() -> Vec<TreeNode<T>> + 'static,
    title: impl Fn(&T) -> String + 'static,
) -> Outline<T> {
    Outline { roots: Box::new(roots), title: Rc::new(title), icon: None, tint: None, badge: None, columns: Vec::new(), lazy: None, selection: None, sidebar: false, expanded: false, transparent: false }
}

/// A Mac sidebar: an outline in the source-list style whose top-level items
/// are section headers, expanded.
pub fn sidebar<T: Identifiable + 'static>(
    sections: impl Fn() -> Vec<TreeNode<T>> + 'static,
    title: impl Fn(&T) -> String + 'static,
) -> Outline<T> {
    Outline { sidebar: true, ..outline(sections, title) }
}