Skip to main content

ferrokit_core/
table.rs

1//! A real `NSTableView` (in its `NSScrollView`) backed by a typed Rust model.
2//!
3//! AppKit pulls cell values lazily, during its own layout and scrolling, so
4//! the data lives in the model rather than in the host's view code. The model
5//! is a cheap handle (`Clone`, main thread only); the native view is created
6//! once and updated in place, and removed when the last handle is dropped.
7//!
8//! User actions (selection, activation, sorting, checkbox toggles, column
9//! moves and resizes, drops, pastes) are queued on the model and announced
10//! with [`crate::request_redraw`]; the host's table widget drains them.
11//!
12//! ⌘C copies the selected rows as tab-separated text. Dragging rows out,
13//! reordering by drag, file drops and pasting are opt-in
14//! ([`TableModel::set_row_drag`], [`TableModel::set_reorderable`],
15//! [`TableModel::set_file_drop`], [`TableModel::set_pastes`]).
16
17use std::cell::{Cell, Ref, RefCell};
18use std::collections::VecDeque;
19use std::rc::{Rc, Weak};
20
21use objc2::rc::Retained;
22use objc2::runtime::{AnyObject, NSObject, NSObjectProtocol, ProtocolObject};
23use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel};
24use objc2_app_kit::{
25    NSButton, NSControl, NSControlStateValueOff, NSControlStateValueOn, NSControlTextEditingDelegate, NSDragOperation,
26    NSDraggingInfo, NSEvent, NSLineBreakMode, NSMenuItem, NSPasteboard, NSPasteboardItem, NSPasteboardTypeFileURL,
27    NSPasteboardTypeString, NSPasteboardTypeTabularText, NSPasteboardWriting, NSResponder, NSScrollView, NSTableColumn,
28    NSTableColumnResizingOptions, NSTableView, NSTableViewDataSource, NSTableViewDelegate, NSTableViewDropOperation,
29    NSTableViewStyle, NSTextAlignment, NSTextField, NSUserInterfaceItemIdentification, NSView,
30};
31use objc2_foundation::{
32    NSArray, NSIndexSet, NSInteger, NSMutableIndexSet, NSNotification, NSSortDescriptor, NSString, NSURL,
33};
34
35use crate::ViewId;
36use crate::host::mtm;
37use crate::kept::{UiCell, UiLocal};
38
39/// A cell's value.
40#[derive(Debug, Clone, PartialEq)]
41pub enum Value {
42    /// Text, shown as is and sorted in natural order.
43    Text(String),
44    /// A number, right-aligned and sorted numerically.
45    Number(f64),
46    /// A checkbox.
47    Bool(bool),
48}
49
50#[derive(Debug, Clone, Copy, PartialEq)]
51enum Kind {
52    Text,
53    Number { decimals: usize },
54    Check,
55    /// A bar from 0 to 1 (the value is a number).
56    Progress,
57    /// A date (the value is seconds since 1970; not finite: none).
58    Date { time: bool },
59}
60
61/// A small image shown before a cell's text (see [`Column::icon`]).
62#[derive(Debug, Clone, PartialEq)]
63pub enum CellImage {
64    /// An SF Symbol by name.
65    Symbol(String),
66    /// The Finder's icon for a file or folder.
67    FileIcon(std::path::PathBuf),
68}
69
70type IconFn<T> = Box<dyn Fn(&T) -> Option<CellImage>>;
71
72/// A row's group (see [`TableModel::set_group_by`]).
73pub type GroupKey<T> = Box<dyn Fn(&T) -> String>;
74
75/// A column: an id (stable, used for sorting and saved state), a title, and
76/// how to get the cell value from a row.
77pub struct Column<T> {
78    id: String,
79    title: String,
80    width: f64,
81    min_width: f64,
82    kind: Kind,
83    sortable: bool,
84    editable: bool,
85    fit: bool,
86    icon: Option<IconFn<T>>,
87    value: Box<dyn Fn(&T) -> Value>,
88}
89
90impl<T> Column<T> {
91    fn new(id: &str, title: &str, kind: Kind, value: Box<dyn Fn(&T) -> Value>) -> Self {
92        Self { id: id.into(), title: title.into(), width: 120.0, min_width: 40.0, kind, sortable: true, editable: false, fit: false, icon: None, value }
93    }
94
95    /// A text column.
96    pub fn text(id: &str, title: &str, value: impl Fn(&T) -> String + 'static) -> Self {
97        Self::new(id, title, Kind::Text, Box::new(move |row| Value::Text(value(row))))
98    }
99
100    /// A right-aligned number column, sorted numerically.
101    pub fn number(id: &str, title: &str, value: impl Fn(&T) -> f64 + 'static) -> Self {
102        Self::new(id, title, Kind::Number { decimals: 0 }, Box::new(move |row| Value::Number(value(row))))
103    }
104
105    /// A checkbox column. Clicking a checkbox emits [`TableEvent::Toggle`];
106    /// the model doesn't change the row itself.
107    pub fn check(id: &str, title: &str, value: impl Fn(&T) -> bool + 'static) -> Self {
108        Self::new(id, title, Kind::Check, Box::new(move |row| Value::Bool(value(row)))).width(60.0)
109    }
110
111    /// A progress bar from 0 to 1 (values outside are clamped). Sorted and
112    /// copied as the number; VoiceOver reads it as a percentage.
113    pub fn progress(id: &str, title: &str, value: impl Fn(&T) -> f64 + 'static) -> Self {
114        Self::new(id, title, Kind::Progress, Box::new(move |row| Value::Number(value(row).clamp(0.0, 1.0)))).width(100.0)
115    }
116
117    /// A date column: shown in the user's format and language ("12 Mar
118    /// 2024", "Today", "Yesterday"), sorted by date, oldest first;
119    /// `None` shows nothing and sorts before every date. Copied as shown.
120    /// [`with_time`](Self::with_time) adds the time.
121    pub fn date(id: &str, title: &str, value: impl Fn(&T) -> Option<std::time::SystemTime> + 'static) -> Self {
122        Self::new(
123            id,
124            title,
125            Kind::Date { time: false },
126            Box::new(move |row| {
127                let secs = value(row).map_or(f64::NEG_INFINITY, |t| match t.duration_since(std::time::UNIX_EPOCH) {
128                    Ok(d) => d.as_secs_f64(),
129                    Err(e) => -e.duration().as_secs_f64(),
130                });
131                Value::Number(secs)
132            }),
133        )
134        .width(150.0)
135    }
136
137    /// Shows a date column's time too ("Today at 09:41").
138    pub fn with_time(mut self) -> Self {
139        if let Kind::Date { .. } = self.kind {
140            self.kind = Kind::Date { time: true };
141        }
142        self
143    }
144
145    /// Shows an image before each cell's text (a text or number column),
146    /// e.g. a file's icon before its name. `None` leaves the space empty.
147    pub fn icon(mut self, image: impl Fn(&T) -> Option<CellImage> + 'static) -> Self {
148        self.icon = Some(Box::new(image));
149        self
150    }
151
152    /// Sizes the column to its widest content (and its title) whenever the
153    /// rows change. With many rows, the longest values are measured.
154    pub fn fit(mut self) -> Self {
155        self.fit = true;
156        self
157    }
158
159    /// Initial width in points (default 120).
160    pub fn width(mut self, width: f64) -> Self {
161        self.width = width;
162        self
163    }
164
165    /// Smallest width the user can drag the column to.
166    pub fn min_width(mut self, min_width: f64) -> Self {
167        self.min_width = min_width;
168        self
169    }
170
171    /// Decimal places shown for a number column (default 0).
172    pub fn decimals(mut self, decimals: usize) -> Self {
173        if let Kind::Number { .. } = self.kind {
174            self.kind = Kind::Number { decimals };
175        }
176        self
177    }
178
179    /// Lets the user edit this column's text or number cells (double-click,
180    /// or Return on the selected row's cell). Finishing an edit (Return, Tab
181    /// or a click elsewhere; not Escape) emits [`TableEvent::Edit`]; the model doesn't change the row: apply it with
182    /// [`TableModel::update_row`]. No effect on checkbox columns.
183    pub fn editable(mut self, editable: bool) -> Self {
184        self.editable = editable;
185        self
186    }
187
188    /// Whether a header click sorts by this column (default true).
189    pub fn sortable(mut self, sortable: bool) -> Self {
190        self.sortable = sortable;
191        self
192    }
193}
194
195fn display(kind: Kind, value: &Value) -> String {
196    match (kind, value) {
197        (_, Value::Text(s)) => s.clone(),
198        (Kind::Date { time }, Value::Number(n)) => format_date(*n, time),
199        (Kind::Number { decimals }, Value::Number(n)) => format!("{n:.decimals$}"),
200        (_, Value::Number(n)) => n.to_string(),
201        (_, Value::Bool(b)) => if *b { "Yes".into() } else { "No".into() },
202    }
203}
204
205thread_local! {
206    /// The date formatters (date only, date and time), made once: making
207    /// one is slow, and a table formats every visible cell.
208    static DATE_FORMATS: UiCell<[Option<Retained<objc2_foundation::NSDateFormatter>>; 2]> = const { UiCell::new([None, None]) };
209}
210
211/// `secs` since 1970 in the user's date format, relative where it can be
212/// ("Today"); empty when not finite (no date).
213fn format_date(secs: f64, time: bool) -> String {
214    use objc2_foundation::{NSDate, NSDateFormatter, NSDateFormatterStyle};
215    if !secs.is_finite() {
216        return String::new();
217    }
218    let formatter = DATE_FORMATS.with_borrow_mut(|f| {
219        f[time as usize]
220            .get_or_insert_with(|| {
221                let f = NSDateFormatter::new();
222                f.setDateStyle(NSDateFormatterStyle::MediumStyle);
223                f.setTimeStyle(if time { NSDateFormatterStyle::ShortStyle } else { NSDateFormatterStyle::NoStyle });
224                f.setDoesRelativeDateFormatting(true);
225                f
226            })
227            .clone()
228    });
229    formatter.stringFromDate(&NSDate::dateWithTimeIntervalSince1970(secs)).to_string()
230}
231
232/// Group header slots in `order` carry this bit (and the group's index).
233const HEADER: usize = 1 << (usize::BITS - 1);
234
235/// The table's sort: a column id and a direction.
236#[derive(Debug, Clone, PartialEq, Eq)]
237pub struct Sort {
238    /// The column id.
239    pub column: String,
240    /// Ascending (A→Z, 0→9) or descending.
241    pub ascending: bool,
242}
243
244/// A column's place and width, as the user arranged them (for saving).
245#[derive(Debug, Clone, PartialEq)]
246pub struct ColumnState {
247    /// The column id.
248    pub id: String,
249    /// Width in points.
250    pub width: f64,
251}
252
253/// Something the user did in the table. Row indices are model indices
254/// (positions in the rows given to [`TableModel::set_rows`]), whatever the sort.
255#[derive(Debug, Clone, PartialEq)]
256#[non_exhaustive]
257pub enum TableEvent {
258    /// The selected rows changed.
259    Selection(Vec<usize>),
260    /// Double-click or Return on a row.
261    Activate(usize),
262    /// The user clicked a column header. With built-in sorting on (the
263    /// default) the rows are already shown in the new order.
264    Sort(Sort),
265    /// A checkbox cell was clicked. The model doesn't change the row: apply
266    /// it with [`TableModel::update_row`].
267    Toggle {
268        /// The row (model index).
269        row: usize,
270        /// The column id.
271        column: String,
272        /// The checkbox's new state.
273        value: bool,
274    },
275    /// Columns were moved or resized; read [`TableModel::column_state`].
276    ColumnsChanged,
277    /// The user finished editing a cell of an [`Column::editable`] column.
278    /// The model doesn't change the row: apply it with
279    /// [`TableModel::update_row`].
280    Edit {
281        /// The row (model index).
282        row: usize,
283        /// The column id.
284        column: String,
285        /// The text the user entered.
286        value: String,
287    },
288    /// The user dragged rows to a new place (see
289    /// [`TableModel::set_reorderable`]). The model doesn't move them: apply
290    /// it with [`TableModel::move_rows`].
291    RowsMoved {
292        /// The dragged rows (model indices).
293        rows: Vec<usize>,
294        /// The row they were dropped above (model index), or `None` for the end.
295        before: Option<usize>,
296    },
297    /// Files were dropped on the table (see [`TableModel::set_file_drop`]).
298    FilesDropped {
299        /// The files' paths.
300        paths: Vec<std::path::PathBuf>,
301        /// The row they were dropped above (model index), or `None` for the end.
302        before: Option<usize>,
303    },
304    /// The user pasted (⌘V) text (see [`TableModel::set_pastes`]); rows
305    /// copied from a table arrive as tab-separated lines.
306    Paste(String),
307    /// The user pressed a bare key the table handles (see
308    /// [`TableModel::set_keys`]) with rows selected.
309    Key {
310        /// The key.
311        key: TableKey,
312        /// The selected rows (model indices).
313        rows: Vec<usize>,
314    },
315}
316
317/// Which transfers a table takes part in (see the `set_…` methods on
318/// [`TableModel`]).
319#[derive(Debug, Clone, Default)]
320struct Transfer {
321    drag: bool,
322    reorder: bool,
323    /// Bare keys reported as [`TableEvent::Key`].
324    keys: Vec<TableKey>,
325    /// File drops: `None` off; `Some(extensions)`, any file if empty.
326    files: Option<Vec<String>>,
327    pastes: bool,
328}
329
330/// The pasteboard type carrying a dragged row's model index (only read back
331/// by the table it came from).
332fn row_type() -> Retained<NSString> {
333    NSString::from_str("dev.ferrokit.table-row")
334}
335
336/// Type-erased view of a model for the Objective-C data source.
337trait Data {
338    fn count(&self) -> usize;
339    fn cell(&self, view_row: usize, column: &str) -> Option<(Kind, Value)>;
340    fn editable(&self, column: &str) -> bool;
341    fn title(&self, column: &str) -> Option<String>;
342    fn model_row(&self, view_row: usize) -> Option<usize>;
343    fn sort_changed(&self, sort: Option<Sort>);
344    fn push(&self, event: TableEvent);
345    fn quiet(&self) -> bool;
346    fn transfer(&self) -> Transfer;
347    fn sorted(&self) -> bool;
348    /// Tab-separated text of rows (view positions), columns in `columns` order.
349    fn rows_text(&self, view_rows: &[usize], columns: &[String]) -> String;
350    /// The title of the group header shown at `view_row`, if it is one.
351    fn group_title(&self, view_row: usize) -> Option<String>;
352    /// The cell's image (an [`Column::icon`] column).
353    fn icon(&self, view_row: usize, column: &str) -> Option<CellImage>;
354    /// Whether the column has icons.
355    fn has_icon(&self, column: &str) -> bool;
356}
357
358struct SourceIvars {
359    data: RefCell<Option<Weak<dyn Data>>>,
360    /// Cell views created (not reused), for diagnostics.
361    created: Cell<usize>,
362}
363
364define_class!(
365    // Data source, delegate and action target for one table.
366    #[unsafe(super(NSObject))]
367    #[thread_kind = MainThreadOnly]
368    #[name = "FerrokitCoreTableSource"]
369    #[ivars = SourceIvars]
370    struct Source;
371
372    unsafe impl NSObjectProtocol for Source {}
373    unsafe impl NSControlTextEditingDelegate for Source {}
374
375    unsafe impl NSTableViewDataSource for Source {
376        #[unsafe(method(numberOfRowsInTableView:))]
377        fn number_of_rows(&self, _table: &NSTableView) -> NSInteger {
378            self.data().map_or(0, |d| d.count() as NSInteger)
379        }
380
381        #[unsafe(method(tableView:sortDescriptorsDidChange:))]
382        fn sort_descriptors_did_change(&self, table: &NSTableView, _old: &NSArray<NSSortDescriptor>) {
383            let sort = table.sortDescriptors().firstObject().and_then(|d| {
384                Some(Sort { column: d.key()?.to_string(), ascending: d.ascending() })
385            });
386            if let Some(data) = self.data() {
387                data.sort_changed(sort);
388            }
389        }
390
391        #[unsafe(method_id(tableView:pasteboardWriterForRow:))]
392        fn writer_for_row(&self, table: &NSTableView, row: NSInteger) -> Option<Retained<ProtocolObject<dyn NSPasteboardWriting>>> {
393            self.row_writer(table, row)
394        }
395
396        #[unsafe(method(tableView:validateDrop:proposedRow:proposedDropOperation:))]
397        fn validate_drop(
398            &self,
399            table: &NSTableView,
400            info: &ProtocolObject<dyn NSDraggingInfo>,
401            row: NSInteger,
402            _operation: NSTableViewDropOperation,
403        ) -> NSDragOperation {
404            let operation = match self.dropped(table, info) {
405                Some(Dropped::Rows(_)) => NSDragOperation::Move,
406                Some(Dropped::Files(_)) => NSDragOperation::Copy,
407                None => return NSDragOperation::None,
408            };
409            // Between rows, never onto one.
410            table.setDropRow_dropOperation(row, NSTableViewDropOperation::Above);
411            operation
412        }
413
414        #[unsafe(method(tableView:acceptDrop:row:dropOperation:))]
415        fn accept_drop(
416            &self,
417            table: &NSTableView,
418            info: &ProtocolObject<dyn NSDraggingInfo>,
419            row: NSInteger,
420            _operation: NSTableViewDropOperation,
421        ) -> bool {
422            self.accept(table, info, row)
423        }
424    }
425
426    unsafe impl NSTableViewDelegate for Source {
427        #[unsafe(method_id(tableView:viewForTableColumn:row:))]
428        fn view_for(&self, table: &NSTableView, column: Option<&NSTableColumn>, row: NSInteger) -> Option<Retained<NSView>> {
429            match column {
430                Some(column) => self.cell_view(table, column, row),
431                // A group row spans the table (no column).
432                None => self.group_view(table, row),
433            }
434        }
435
436        #[unsafe(method(tableView:isGroupRow:))]
437        fn is_group_row(&self, _table: &NSTableView, row: NSInteger) -> bool {
438            self.data().is_some_and(|d| d.group_title(row as usize).is_some())
439        }
440
441        #[unsafe(method(tableView:shouldSelectRow:))]
442        fn should_select_row(&self, _table: &NSTableView, row: NSInteger) -> bool {
443            self.data().is_none_or(|d| d.group_title(row as usize).is_none())
444        }
445
446        #[unsafe(method(tableViewSelectionDidChange:))]
447        fn selection_did_change(&self, notification: &NSNotification) {
448            let Some(data) = self.data() else { return };
449            if data.quiet() {
450                return;
451            }
452            let Some(table) = notification.object().and_then(|o| o.downcast::<NSTableView>().ok()) else { return };
453            let rows = indexes(&table.selectedRowIndexes()).into_iter().filter_map(|r| data.model_row(r)).collect();
454            data.push(TableEvent::Selection(rows));
455        }
456
457        #[unsafe(method_id(tableView:typeSelectStringForTableColumn:row:))]
458        fn type_select_string(&self, _table: &NSTableView, column: Option<&NSTableColumn>, row: NSInteger) -> Option<Retained<NSString>> {
459            self.cell_text(column, row)
460        }
461
462        #[unsafe(method(tableViewColumnDidMove:))]
463        fn column_did_move(&self, _notification: &NSNotification) {
464            if let Some(data) = self.data() {
465                data.push(TableEvent::ColumnsChanged);
466            }
467        }
468
469        #[unsafe(method(tableViewColumnDidResize:))]
470        fn column_did_resize(&self, _notification: &NSNotification) {
471            if let Some(data) = self.data() {
472                data.push(TableEvent::ColumnsChanged);
473            }
474        }
475    }
476
477    impl Source {
478        #[unsafe(method(activate:))]
479        fn activate(&self, sender: &NSTableView) {
480            let Some(data) = self.data() else { return };
481            let row = sender.clickedRow();
482            if let Some(row) = (row >= 0).then_some(row as usize).and_then(|r| data.model_row(r)) {
483                data.push(TableEvent::Activate(row));
484            }
485        }
486
487        #[unsafe(method(edit:))]
488        fn edit(&self, sender: &NSTextField) {
489            let Some(data) = self.data() else { return };
490            let Some(table) = table_of(sender) else { return };
491            let row = table.rowForView(sender);
492            let Some(column) = sender.identifier().map(|i| i.to_string()) else { return };
493            let value = sender.stringValue().to_string();
494            // Editing ends with Return, Tab or the focus moving away; an
495            // edit cancelled with Escape (or left as it was) isn't one.
496            let shown = (row >= 0).then(|| data.cell(row as usize, &column)).flatten().map(|(kind, v)| display(kind, &v));
497            if shown.as_deref() == Some(value.as_str()) {
498                return;
499            }
500            if let Some(row) = (row >= 0).then_some(row as usize).and_then(|r| data.model_row(r)) {
501                data.push(TableEvent::Edit { row, column, value });
502            }
503        }
504
505        #[unsafe(method(toggle:))]
506        fn toggle(&self, sender: &NSButton) {
507            let Some(data) = self.data() else { return };
508            let Some(table) = table_of(sender) else { return };
509            let row = table.rowForView(sender);
510            let Some(column) = sender.identifier().map(|i| i.to_string()) else { return };
511            if let Some(row) = (row >= 0).then_some(row as usize).and_then(|r| data.model_row(r)) {
512                data.push(TableEvent::Toggle { row, column, value: sender.state() == NSControlStateValueOn });
513            }
514        }
515    }
516);
517
518/// A key a table can take without ⌘ (see [`TableModel::set_keys`]).
519#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
520#[non_exhaustive]
521pub enum TableKey {
522    /// Delete (⌫) or Forward Delete (⌦): remove the selected rows, say.
523    Delete,
524    /// Space: Quick Look the selected rows, say.
525    Space,
526}
527
528impl TableKey {
529    /// The key a key-down event is, if it's one of these without ⌘, ⌥ or ⌃.
530    fn of(event: &NSEvent) -> Option<TableKey> {
531        use objc2_app_kit::NSEventModifierFlags as F;
532        if event.modifierFlags().intersects(F::Command | F::Option | F::Control) {
533            return None;
534        }
535        // 51: Delete, 117: Forward Delete, 49: Space.
536        match event.keyCode() {
537            51 | 117 => Some(TableKey::Delete),
538            49 => Some(TableKey::Space),
539            _ => None,
540        }
541    }
542}
543
544/// What a drag carries that this table accepts.
545enum Dropped {
546    Rows(Vec<usize>),
547    Files(Vec<std::path::PathBuf>),
548}
549
550define_class!(
551    // NSTableView that also activates the selected row on Return / Enter, and
552    // copies and pastes rows.
553    #[unsafe(super(NSTableView, NSControl, NSView, NSResponder, NSObject))]
554    #[thread_kind = MainThreadOnly]
555    #[name = "FerrokitCoreTableView"]
556    struct HostTableView;
557
558    impl HostTableView {
559        #[unsafe(method(keyDown:))]
560        fn key_down(&self, event: &NSEvent) {
561            // 36: Return, 76: keypad Enter.
562            if matches!(event.keyCode(), 36 | 76) {
563                let row = self.selectedRow();
564                let source = unsafe { self.dataSource() };
565                let source = source.and_then(|s| {
566                    let any: &AnyObject = s.as_ref();
567                    any.downcast_ref::<Source>().map(|s| s.retain())
568                });
569                if let (true, Some(source)) = (row >= 0, source) {
570                    if let Some(data) = source.data()
571                        && let Some(row) = data.model_row(row as usize)
572                    {
573                        data.push(TableEvent::Activate(row));
574                    }
575                    return;
576                }
577            }
578            // A bare key the app handles, with rows selected.
579            if let Some(key) = TableKey::of(event)
580                && let Some(data) = self.source().and_then(|s| s.data())
581                && data.transfer().keys.contains(&key)
582            {
583                let rows: Vec<usize> = indexes(&self.selectedRowIndexes()).into_iter().filter_map(|r| data.model_row(r)).collect();
584                if !rows.is_empty() {
585                    data.push(TableEvent::Key { key, rows });
586                    return;
587                }
588            }
589            let () = unsafe { msg_send![super(self), keyDown: event] };
590        }
591
592        #[unsafe(method(copy:))]
593        fn copy(&self, _sender: Option<&AnyObject>) {
594            self.copy_rows(&NSPasteboard::generalPasteboard());
595        }
596
597        #[unsafe(method(paste:))]
598        fn paste(&self, _sender: Option<&AnyObject>) {
599            self.paste_text(&NSPasteboard::generalPasteboard());
600        }
601
602        #[unsafe(method(validateMenuItem:))]
603        fn validate_menu_item(&self, item: &NSMenuItem) -> bool {
604            let action = item.action();
605            if action == Some(sel!(copy:)) {
606                self.selectedRow() >= 0
607            } else if action == Some(sel!(paste:)) {
608                let pastes = self.source().and_then(|s| s.data()).is_some_and(|d| d.transfer().pastes);
609                // SAFETY: AppKit's pasteboard type constant.
610                pastes && NSPasteboard::generalPasteboard().stringForType(unsafe { NSPasteboardTypeString }).is_some()
611            } else {
612                true
613            }
614        }
615    }
616);
617
618impl HostTableView {
619    fn source(&self) -> Option<Retained<Source>> {
620        let source = unsafe { self.dataSource() }?;
621        let any: &AnyObject = source.as_ref();
622        any.downcast_ref::<Source>().map(|s| s.retain())
623    }
624
625    /// Writes the selected rows to `pasteboard` as tab-separated text.
626    fn copy_rows(&self, pasteboard: &NSPasteboard) -> bool {
627        let Some(data) = self.source().and_then(|s| s.data()) else { return false };
628        let rows = indexes(&self.selectedRowIndexes());
629        if rows.is_empty() {
630            return false;
631        }
632        let text = NSString::from_str(&data.rows_text(&rows, &column_ids(self)));
633        pasteboard.clearContents();
634        // SAFETY: AppKit's pasteboard type constants.
635        unsafe {
636            pasteboard.setString_forType(&text, NSPasteboardTypeString);
637            pasteboard.setString_forType(&text, NSPasteboardTypeTabularText);
638        }
639        true
640    }
641
642    /// Reports `pasteboard`'s text as a paste, if the table takes pastes.
643    fn paste_text(&self, pasteboard: &NSPasteboard) -> bool {
644        let Some(data) = self.source().and_then(|s| s.data()) else { return false };
645        // SAFETY: AppKit's pasteboard type constant.
646        let text = pasteboard.stringForType(unsafe { NSPasteboardTypeString });
647        match (data.transfer().pastes, text) {
648            (true, Some(text)) => {
649                data.push(TableEvent::Paste(text.to_string()));
650                true
651            }
652            _ => false,
653        }
654    }
655}
656
657/// The table's column ids, in their current (user-arranged) order.
658fn column_ids(table: &NSTableView) -> Vec<String> {
659    table.tableColumns().iter().map(|c| c.identifier().to_string()).collect()
660}
661
662use objc2::Message as _;
663
664fn table_of(view: &NSView) -> Option<Retained<NSTableView>> {
665    // SAFETY: walking up a live view hierarchy on the main thread.
666    let mut current = unsafe { view.superview() };
667    while let Some(v) = current {
668        if let Ok(table) = v.clone().downcast::<NSTableView>() {
669            return Some(table);
670        }
671        current = unsafe { v.superview() };
672    }
673    None
674}
675
676fn indexes(set: &NSIndexSet) -> Vec<usize> {
677    let mut out = Vec::with_capacity(set.count());
678    let mut i = set.firstIndex();
679    while i != usize::MAX && out.len() < set.count() {
680        out.push(i);
681        i = set.indexGreaterThanIndex(i);
682    }
683    out
684}
685
686impl Source {
687    fn cell_text(&self, column: Option<&NSTableColumn>, row: NSInteger) -> Option<Retained<NSString>> {
688        let (kind, value) = self.data()?.cell(row as usize, &column?.identifier().to_string())?;
689        Some(NSString::from_str(&display(kind, &value)))
690    }
691
692    fn data(&self) -> Option<Rc<dyn Data>> {
693        self.ivars().data.borrow().as_ref().and_then(Weak::upgrade)
694    }
695
696    fn row_writer(&self, table: &NSTableView, row: NSInteger) -> Option<Retained<ProtocolObject<dyn NSPasteboardWriting>>> {
697        let data = self.data()?;
698        if !data.transfer().drag {
699            return None;
700        }
701        let model = data.model_row(usize::try_from(row).ok()?)?;
702        let item = NSPasteboardItem::new();
703        item.setString_forType(&NSString::from_str(&model.to_string()), &row_type());
704        let text = data.rows_text(&[row as usize], &column_ids(table));
705        // SAFETY: AppKit's pasteboard type constant.
706        item.setString_forType(&NSString::from_str(&text), unsafe { NSPasteboardTypeString });
707        Some(ProtocolObject::from_retained(item))
708    }
709
710    fn accept(&self, table: &NSTableView, info: &ProtocolObject<dyn NSDraggingInfo>, row: NSInteger) -> bool {
711        let Some(data) = self.data() else { return false };
712        let before = usize::try_from(row).ok().and_then(|r| data.model_row(r));
713        match self.dropped(table, info) {
714            Some(Dropped::Rows(rows)) => data.push(TableEvent::RowsMoved { rows, before }),
715            Some(Dropped::Files(paths)) => data.push(TableEvent::FilesDropped { paths, before }),
716            None => return false,
717        }
718        true
719    }
720
721    /// What a drag over `table` carries that the table takes: its own rows
722    /// (when reorderable and unsorted), or files (when it takes them).
723    fn dropped(&self, table: &NSTableView, info: &ProtocolObject<dyn NSDraggingInfo>) -> Option<Dropped> {
724        let data = self.data()?;
725        let transfer = data.transfer();
726        let items = info.draggingPasteboard().pasteboardItems()?;
727        let own = info.draggingSource().is_some_and(|s| std::ptr::eq(&*s as *const AnyObject, table as *const NSTableView as *const AnyObject));
728        if own {
729            // Reordering a sorted table has no meaning: the sort decides.
730            if !transfer.reorder || data.sorted() {
731                return None;
732            }
733            let rows: Vec<usize> = items.iter().filter_map(|i| i.stringForType(&row_type())?.to_string().parse().ok()).collect();
734            return (!rows.is_empty()).then_some(Dropped::Rows(rows));
735        }
736        let extensions = transfer.files?;
737        let paths: Vec<std::path::PathBuf> = items
738            .iter()
739            // SAFETY: AppKit's pasteboard type constant.
740            .filter_map(|i| i.stringForType(unsafe { NSPasteboardTypeFileURL }))
741            .filter_map(|u| NSURL::URLWithString(&u)?.path().map(|p| std::path::PathBuf::from(p.to_string())))
742            .collect();
743        let accepted = |p: &std::path::PathBuf| {
744            extensions.is_empty()
745                || p.extension().and_then(|e| e.to_str()).is_some_and(|e| extensions.iter().any(|x| x.eq_ignore_ascii_case(e)))
746        };
747        (!paths.is_empty() && paths.iter().all(accepted)).then_some(Dropped::Files(paths))
748    }
749
750    /// A group header: its title, in the table's group-row style.
751    fn group_view(&self, table: &NSTableView, row: NSInteger) -> Option<Retained<NSView>> {
752        let title = self.data()?.group_title(row as usize)?;
753        let ident = NSString::from_str("ferrokit-core.group");
754        // SAFETY: reuse lookup by identifier; owner may be nil.
755        let field = match unsafe { table.makeViewWithIdentifier_owner(&ident, None) }.and_then(|v| v.downcast::<NSTextField>().ok()) {
756            Some(f) => f,
757            None => {
758                let f = NSTextField::labelWithString(&NSString::new(), MainThreadMarker::from(self));
759                f.setIdentifier(Some(&ident));
760                f.setFont(Some(&objc2_app_kit::NSFont::boldSystemFontOfSize(objc2_app_kit::NSFont::smallSystemFontSize())));
761                f.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
762                f
763            }
764        };
765        field.setStringValue(&NSString::from_str(&title));
766        Some(Retained::into_super(Retained::into_super(field)))
767    }
768
769    fn progress_view(&self, table: &NSTableView, ident: &NSString, value: f64) -> Retained<NSView> {
770        use objc2_app_kit::{NSProgressIndicator, NSProgressIndicatorStyle, NSTableCellView};
771        let mtm = MainThreadMarker::from(self);
772        // SAFETY: reuse lookup by identifier; owner may be nil.
773        let cell = match unsafe { table.makeViewWithIdentifier_owner(ident, None) }.and_then(|v| v.downcast::<NSTableCellView>().ok()) {
774            Some(c) => c,
775            None => {
776                self.ivars().created.set(self.ivars().created.get() + 1);
777                let c = NSTableCellView::new(mtm);
778                c.setIdentifier(Some(ident));
779                let bar = NSProgressIndicator::new(mtm);
780                bar.setStyle(NSProgressIndicatorStyle::Bar);
781                bar.setIndeterminate(false);
782                bar.setMinValue(0.0);
783                bar.setMaxValue(1.0);
784                bar.setControlSize(objc2_app_kit::NSControlSize::Small);
785                bar.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable | objc2_app_kit::NSAutoresizingMaskOptions::ViewMinYMargin | objc2_app_kit::NSAutoresizingMaskOptions::ViewMaxYMargin);
786                bar.setFrame(objc2_foundation::NSRect::new(objc2_foundation::NSPoint::new(2.0, 2.0), objc2_foundation::NSSize::new(96.0, 12.0)));
787                c.addSubview(&bar);
788                if let Some(title) = self.data().and_then(|d| d.title(&ident.to_string())) {
789                    // SAFETY: NSAccessibility's label setter.
790                    let () = unsafe { msg_send![&*bar, setAccessibilityLabel: &*NSString::from_str(&title)] };
791                }
792                c
793            }
794        };
795        if let Some(bar) = cell.subviews().iter().find_map(|v| v.downcast::<objc2_app_kit::NSProgressIndicator>().ok()) {
796            bar.setDoubleValue(value);
797        }
798        Retained::into_super(cell)
799    }
800
801    fn cell_view(&self, table: &NSTableView, column: &NSTableColumn, row: NSInteger) -> Option<Retained<NSView>> {
802        let ident = column.identifier();
803        let (kind, value) = self.data()?.cell(row as usize, &ident.to_string())?;
804        let mtm = MainThreadMarker::from(self);
805        if kind == Kind::Progress {
806            let v = if let Value::Number(n) = value { n } else { 0.0 };
807            return Some(self.progress_view(table, &ident, v));
808        }
809        if self.data().is_some_and(|d| d.has_icon(&ident.to_string())) {
810            return Some(self.icon_view(table, &ident, kind, &value, row));
811        }
812        // SAFETY: reuse lookup by identifier; owner may be nil.
813        let reused = unsafe { table.makeViewWithIdentifier_owner(&ident, None) };
814        if kind == Kind::Check {
815            let button = match reused.and_then(|v| v.downcast::<NSButton>().ok()) {
816                Some(b) => b,
817                None => {
818                    self.ivars().created.set(self.ivars().created.get() + 1);
819                    // SAFETY: target is this source, which outlives the table's cells.
820                    let b = unsafe { NSButton::checkboxWithTitle_target_action(&NSString::new(), Some(self), Some(sel!(toggle:)), mtm) };
821                    b.setIdentifier(Some(&ident));
822                    // An untitled checkbox reads as just "checkbox": title it after
823                    // its column and show only the box.
824                    if let Some(title) = self.data().and_then(|d| d.title(&ident.to_string())) {
825                        let title = NSString::from_str(&title);
826                        b.setTitle(&title);
827                        b.setImagePosition(objc2_app_kit::NSCellImagePosition::ImageOnly);
828                        // Image-only buttons report an empty AX title; label
829                        // the button and its cell (which serves accessibility).
830                        // SAFETY: NSAccessibility setters taking a string.
831                        unsafe {
832                            let () = msg_send![&*b, setAccessibilityLabel: &*title];
833                            let cell: Option<Retained<AnyObject>> = msg_send![&*b, cell];
834                            if let Some(cell) = cell {
835                                let () = msg_send![&*cell, setAccessibilityLabel: &*title];
836                            }
837                        }
838                    }
839                    b
840                }
841            };
842            button.setState(if value == Value::Bool(true) { NSControlStateValueOn } else { NSControlStateValueOff });
843            return Some(Retained::into_super(Retained::into_super(button)));
844        }
845        let field = match reused.and_then(|v| v.downcast::<NSTextField>().ok()) {
846            Some(f) => f,
847            None => {
848                self.ivars().created.set(self.ivars().created.get() + 1);
849                let f = NSTextField::labelWithString(&NSString::new(), mtm);
850                f.setIdentifier(Some(&ident));
851                f.setLineBreakMode(NSLineBreakMode::ByTruncatingTail);
852                if self.data().is_some_and(|d| d.editable(&ident.to_string())) {
853                    // A borderless editable label: NSTableView starts editing
854                    // on double-click (or a click on the selected row), and
855                    // the action fires when editing ends: with Return, and
856                    // also with Tab or a click elsewhere (a label sends it
857                    // only on Return otherwise, and the edit was lost).
858                    f.setEditable(true);
859                    f.setSelectable(true);
860                    if let Some(cell) = f.cell() {
861                        cell.setSendsActionOnEndEditing(true);
862                    }
863                    // SAFETY: target is this source, which outlives the table's cells.
864                    unsafe {
865                        f.setTarget(Some(self));
866                        f.setAction(Some(sel!(edit:)));
867                    }
868                }
869                f
870            }
871        };
872        // Set on reuse too: a column's kind can change (`set_columns`).
873        field.setAlignment(if let Kind::Number { .. } = kind { NSTextAlignment::Right } else { NSTextAlignment::Natural });
874        field.setStringValue(&NSString::from_str(&display(kind, &value)));
875        Some(Retained::into_super(Retained::into_super(field)))
876    }
877
878    /// A cell with an image before its text (an icon column).
879    fn icon_view(&self, table: &NSTableView, ident: &NSString, kind: Kind, value: &Value, row: NSInteger) -> Retained<NSView> {
880        use objc2_app_kit::{NSImageView, NSTableCellView};
881        let mtm = MainThreadMarker::from(self);
882        // SAFETY: reuse lookup by identifier; owner may be nil.
883        let cell = match unsafe { table.makeViewWithIdentifier_owner(ident, None) }.and_then(|v| v.downcast::<NSTableCellView>().ok()) {
884            Some(c) => c,
885            None => {
886                self.ivars().created.set(self.ivars().created.get() + 1);
887                let c = NSTableCellView::new(mtm);
888                c.setIdentifier(Some(ident));
889                let image = NSImageView::new(mtm);
890                image.setFrame(objc2_foundation::NSRect::new(objc2_foundation::NSPoint::new(2.0, 0.0), objc2_foundation::NSSize::new(16.0, 16.0)));
891                image.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewMinYMargin | objc2_app_kit::NSAutoresizingMaskOptions::ViewMaxYMargin);
892                // The icon is decoration: the text names the row. (macOS 15
893                // and 26 otherwise read an unnamed image in every row.) The
894                // view's cell answers for it there, so hide both.
895                // SAFETY: NSAccessibility's setter taking a BOOL.
896                unsafe {
897                    let () = msg_send![&*image, setAccessibilityElement: false];
898                    if let Some(cell) = image.cell() {
899                        let () = msg_send![&*cell, setAccessibilityElement: false];
900                    }
901                }
902                let text = NSTextField::labelWithString(&NSString::new(), mtm);
903                text.setLineBreakMode(NSLineBreakMode::ByTruncatingTail);
904                text.setFrame(objc2_foundation::NSRect::new(objc2_foundation::NSPoint::new(22.0, 0.0), objc2_foundation::NSSize::new(100.0, 17.0)));
905                text.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable | objc2_app_kit::NSAutoresizingMaskOptions::ViewMinYMargin | objc2_app_kit::NSAutoresizingMaskOptions::ViewMaxYMargin);
906                if let Kind::Number { .. } = kind {
907                    text.setAlignment(NSTextAlignment::Right);
908                }
909                c.addSubview(&image);
910                c.addSubview(&text);
911                // SAFETY: weak outlets; both views are the cell's subviews,
912                // which keeps them alive.
913                unsafe {
914                    c.setImageView(Some(&image));
915                    c.setTextField(Some(&text));
916                }
917                c
918            }
919        };
920        let image = self.data().and_then(|d| d.icon(row as usize, &ident.to_string())).and_then(|i| match i {
921            CellImage::Symbol(name) => objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(&NSString::from_str(&name), None),
922            CellImage::FileIcon(path) => Some(objc2_app_kit::NSWorkspace::sharedWorkspace().iconForFile(&NSString::from_str(&path.to_string_lossy()))),
923        });
924        // SAFETY: the outlets set above (subviews of the cell).
925        if let Some(iv) = unsafe { cell.imageView() } {
926            iv.setImage(image.as_deref());
927        }
928        // SAFETY: as above.
929        if let Some(tf) = unsafe { cell.textField() } {
930            tf.setStringValue(&NSString::from_str(&display(kind, value)));
931        }
932        Retained::into_super(cell)
933    }
934}
935
936struct Inner<T: 'static> {
937    id: ViewId,
938    columns: RefCell<Vec<Column<T>>>,
939    rows: RefCell<Vec<T>>,
940    /// View position → model index (identity when unsorted); a group
941    /// header's slot is `HEADER | group`.
942    order: RefCell<Vec<usize>>,
943    /// Groups' titles (see `set_group_by`).
944    groups: RefCell<Vec<String>>,
945    group_by: RefCell<Option<GroupKey<T>>>,
946    sort: RefCell<Option<Sort>>,
947    sorts_in_place: Cell<bool>,
948    events: RefCell<VecDeque<TableEvent>>,
949    /// Set while the model changes the selection itself (no event).
950    quiet: Cell<bool>,
951    mounted: Cell<bool>,
952    transfer: RefCell<Transfer>,
953    scroll: Retained<NSScrollView>,
954    table: Retained<HostTableView>,
955    _source: Retained<Source>,
956}
957
958impl<T: 'static> Data for Inner<T> {
959    fn count(&self) -> usize {
960        self.order.borrow().len()
961    }
962
963    fn cell(&self, view_row: usize, column: &str) -> Option<(Kind, Value)> {
964        let columns = self.columns.borrow();
965        let column = columns.iter().find(|c| c.id == column)?;
966        let index = self.model_row(view_row)?;
967        let rows = self.rows.borrow();
968        Some((column.kind, (column.value)(rows.get(index)?)))
969    }
970
971    fn model_row(&self, view_row: usize) -> Option<usize> {
972        self.order.borrow().get(view_row).copied().filter(|m| m & HEADER == 0)
973    }
974
975    fn group_title(&self, view_row: usize) -> Option<String> {
976        let slot = *self.order.borrow().get(view_row)?;
977        (slot & HEADER != 0).then(|| self.groups.borrow().get(slot & !HEADER).cloned()).flatten()
978    }
979
980    fn icon(&self, view_row: usize, column: &str) -> Option<CellImage> {
981        let columns = self.columns.borrow();
982        let column = columns.iter().find(|c| c.id == column)?;
983        let index = self.model_row(view_row)?;
984        let rows = self.rows.borrow();
985        column.icon.as_ref().and_then(|f| f(rows.get(index)?))
986    }
987
988    fn has_icon(&self, column: &str) -> bool {
989        self.columns.borrow().iter().any(|c| c.id == column && c.icon.is_some())
990    }
991
992    fn editable(&self, column: &str) -> bool {
993        self.columns.borrow().iter().any(|c| c.id == column && c.editable && c.kind != Kind::Check && !matches!(c.kind, Kind::Date { .. }))
994    }
995
996    fn title(&self, column: &str) -> Option<String> {
997        self.columns.borrow().iter().find(|c| c.id == column).map(|c| c.title.clone())
998    }
999
1000    fn sort_changed(&self, sort: Option<Sort>) {
1001        *self.sort.borrow_mut() = sort.clone();
1002        if self.sorts_in_place.get() {
1003            self.resort_keeping_selection();
1004        }
1005        if let Some(sort) = sort {
1006            self.push(TableEvent::Sort(sort));
1007        }
1008    }
1009
1010    fn push(&self, event: TableEvent) {
1011        let mut events = self.events.borrow_mut();
1012        // Column resizes arrive continuously while dragging: keep one.
1013        if event == TableEvent::ColumnsChanged && events.back() == Some(&TableEvent::ColumnsChanged) {
1014            return;
1015        }
1016        events.push_back(event);
1017        drop(events);
1018        crate::request_redraw();
1019    }
1020
1021    fn quiet(&self) -> bool {
1022        self.quiet.get()
1023    }
1024
1025    fn transfer(&self) -> Transfer {
1026        self.transfer.borrow().clone()
1027    }
1028
1029    fn sorted(&self) -> bool {
1030        self.sort.borrow().is_some()
1031    }
1032
1033    fn rows_text(&self, view_rows: &[usize], columns: &[String]) -> String {
1034        let all = self.columns.borrow();
1035        let columns: Vec<&Column<T>> = columns.iter().filter_map(|id| all.iter().find(|c| &c.id == id)).collect();
1036        let order = self.order.borrow();
1037        let rows = self.rows.borrow();
1038        let clean = |s: String| s.replace(['\t', '\n', '\r'], " ");
1039        view_rows
1040            .iter()
1041            .filter_map(|&r| rows.get(*order.get(r)?))
1042            .map(|row| columns.iter().map(|c| clean(display(c.kind, &(c.value)(row)))).collect::<Vec<_>>().join("\t"))
1043            .collect::<Vec<_>>()
1044            .join("\n")
1045    }
1046}
1047
1048impl<T: 'static> Inner<T> {
1049    /// Recomputes `order` from the current sort. Keys are computed once per
1050    /// row (not per comparison) and the sort is stable.
1051    fn compute_order(&self) {
1052        let rows = self.rows.borrow();
1053        let mut order: Vec<usize> = (0..rows.len()).collect();
1054        let sort = self.sort.borrow().clone();
1055        let columns = self.columns.borrow();
1056        if let Some(column) = sort.as_ref().and_then(|s| columns.iter().find(|c| c.id == s.column)) {
1057            // One key per row, built once: text becomes a natural-order key
1058            // compared bytewise (comparing with case folding on every
1059            // comparison took 160 ms for 100k rows).
1060            enum Key {
1061                Number(f64),
1062                Text(String),
1063            }
1064            let keys: Vec<Key> = rows
1065                .iter()
1066                .map(|r| match (column.value)(r) {
1067                    Value::Number(n) => Key::Number(n),
1068                    Value::Bool(b) => Key::Number(b as u8 as f64),
1069                    Value::Text(t) => Key::Text(natural_key(&t)),
1070                })
1071                .collect();
1072            order.sort_by(|a, b| match (&keys[*a], &keys[*b]) {
1073                (Key::Number(x), Key::Number(y)) => x.total_cmp(y),
1074                (Key::Text(x), Key::Text(y)) => x.cmp(y),
1075                (Key::Number(_), Key::Text(_)) => std::cmp::Ordering::Less,
1076                (Key::Text(_), Key::Number(_)) => std::cmp::Ordering::Greater,
1077            });
1078            if sort.is_some_and(|s| !s.ascending) {
1079                order.reverse();
1080            }
1081        }
1082        // Groups: rows gathered by key (groups in order of first appearance
1083        // in the model, rows in the sort's order within each), each run
1084        // after a header slot.
1085        let mut groups = Vec::new();
1086        if let Some(key) = self.group_by.borrow().as_ref() {
1087            let keys: Vec<String> = rows.iter().map(key).collect();
1088            let mut index_of: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
1089            for k in &keys {
1090                if !index_of.contains_key(k.as_str()) {
1091                    index_of.insert(k, groups.len());
1092                    groups.push(k.clone());
1093                }
1094            }
1095            let mut buckets: Vec<Vec<usize>> = vec![Vec::new(); groups.len()];
1096            for &m in &order {
1097                buckets[index_of[keys[m].as_str()]].push(m);
1098            }
1099            order = buckets.into_iter().enumerate().flat_map(|(g, rows)| std::iter::once(HEADER | g).chain(rows)).collect();
1100        }
1101        drop(rows);
1102        *self.groups.borrow_mut() = groups;
1103        *self.order.borrow_mut() = order;
1104        self.fit_columns();
1105    }
1106
1107    /// Sizes `fit` columns to their widest content: the title and, with many
1108    /// rows, the 64 longest values by character count (all of them below
1109    /// 2,000 rows), measured in the table's font.
1110    fn fit_columns(&self) {
1111        let rows = self.rows.borrow();
1112        for column in self.columns.borrow().iter().filter(|c| c.fit) {
1113            let Some(native) = self.table.tableColumnWithIdentifier(&NSString::from_str(&column.id)) else { continue };
1114            let mut texts: Vec<String> = rows.iter().map(|r| display(column.kind, &(column.value)(r))).collect();
1115            if texts.len() > 2_000 {
1116                texts.sort_by_key(|t| std::cmp::Reverse(t.chars().count()));
1117                texts.truncate(64);
1118            }
1119            let font = objc2_app_kit::NSFont::systemFontOfSize(objc2_app_kit::NSFont::systemFontSize());
1120            let attrs = objc2_foundation::NSDictionary::from_retained_objects(
1121                // SAFETY: AppKit's font attribute key.
1122                &[unsafe { objc2_app_kit::NSFontAttributeName }],
1123                &[Retained::into_super(Retained::into_super(font)) as Retained<AnyObject>],
1124            );
1125            // SAFETY: measuring a string with font attributes.
1126            let width = |s: &str| unsafe { objc2_app_kit::NSStringDrawing::sizeWithAttributes(&*NSString::from_str(s), Some(&attrs)).width };
1127            let widest = texts.iter().map(|t| width(t)).fold(width(&column.title) + 16.0, f64::max);
1128            let icon = if column.icon.is_some() { 22.0 } else { 0.0 };
1129            native.setWidth((widest + icon + 12.0).ceil().max(column.min_width));
1130        }
1131    }
1132
1133    fn selection_model_rows(&self) -> Vec<usize> {
1134        let order = self.order.borrow();
1135        indexes(&self.table.selectedRowIndexes()).into_iter().filter_map(|r| order.get(r).copied()).filter(|m| m & HEADER == 0).collect()
1136    }
1137
1138    fn select_model_rows(&self, rows: &[usize]) {
1139        let order = self.order.borrow();
1140        let mut position = vec![usize::MAX; self.rows.borrow().len()];
1141        for (view, &model) in order.iter().enumerate() {
1142            if model & HEADER == 0 {
1143                position[model] = view;
1144            }
1145        }
1146        drop(order);
1147        let set = NSMutableIndexSet::new();
1148        for &r in rows {
1149            if let Some(&p) = position.get(r).filter(|p| **p != usize::MAX) {
1150                set.addIndex(p);
1151            }
1152        }
1153        self.quiet.set(true);
1154        self.table.selectRowIndexes_byExtendingSelection(&set, false);
1155        self.quiet.set(false);
1156    }
1157
1158    fn resort_keeping_selection(&self) {
1159        let selected = self.selection_model_rows();
1160        self.compute_order();
1161        self.table.reloadData();
1162        self.select_model_rows(&selected);
1163    }
1164}
1165
1166impl<T: 'static> Drop for Inner<T> {
1167    fn drop(&mut self) {
1168        // AppKit holds these weakly: detach them before the source goes, in
1169        // case the table outlives the model (e.g. in an autorelease pool).
1170        // SAFETY: clearing to nil is always valid.
1171        unsafe {
1172            self.table.setDataSource(None);
1173            self.table.setDelegate(None);
1174            self.table.setTarget(None);
1175            self.table.setDoubleAction(None);
1176        }
1177        if self.mounted.get() {
1178            crate::unmount(self.id);
1179        }
1180        crate::testing::LIVE_MODELS.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
1181    }
1182}
1183
1184impl Drop for SourceIvars {
1185    fn drop(&mut self) {
1186        crate::testing::LIVE_OBJC.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
1187    }
1188}
1189
1190/// A sort key giving natural order under plain byte comparison:
1191/// case-insensitive, digit runs compared as numbers ("Item 9" < "Item 10"),
1192/// like the Finder. Digit runs become their length (as a char) then the
1193/// digits without leading zeros, so longer numbers sort later.
1194fn natural_key(s: &str) -> String {
1195    let mut key = String::with_capacity(s.len() + 4);
1196    let mut chars = s.chars().peekable();
1197    while let Some(c) = chars.next() {
1198        if c.is_ascii_digit() {
1199            let mut digits = String::from(c);
1200            while let Some(d) = chars.peek().filter(|d| d.is_ascii_digit()) {
1201                digits.push(*d);
1202                chars.next();
1203            }
1204            let trimmed = digits.trim_start_matches('0');
1205            // \u{1} sorts before any printable character.
1206            key.push('\u{1}');
1207            key.push(char::from_u32(0x30 + trimmed.len() as u32).unwrap_or('~'));
1208            key.push_str(trimmed);
1209        } else {
1210            key.extend(c.to_lowercase());
1211        }
1212    }
1213    key
1214}
1215
1216/// Natural order for text (reference implementation for the key's tests).
1217#[cfg(test)]
1218fn natural_cmp(a: &str, b: &str) -> std::cmp::Ordering {
1219    use std::cmp::Ordering;
1220    let (mut a, mut b) = (a.chars().peekable(), b.chars().peekable());
1221    loop {
1222        match (a.peek(), b.peek()) {
1223            (None, None) => return Ordering::Equal,
1224            (None, _) => return Ordering::Less,
1225            (_, None) => return Ordering::Greater,
1226            (Some(x), Some(y)) if x.is_ascii_digit() && y.is_ascii_digit() => {
1227                let take = |it: &mut std::iter::Peekable<std::str::Chars>| {
1228                    let mut n = String::new();
1229                    while let Some(c) = it.peek().filter(|c| c.is_ascii_digit()) {
1230                        n.push(*c);
1231                        it.next();
1232                    }
1233                    n
1234                };
1235                let (x, y) = (take(&mut a), take(&mut b));
1236                let (xt, yt) = (x.trim_start_matches('0'), y.trim_start_matches('0'));
1237                let o = xt.len().cmp(&yt.len()).then_with(|| xt.cmp(yt));
1238                if o != Ordering::Equal {
1239                    return o;
1240                }
1241            }
1242            (Some(x), Some(y)) => {
1243                let o = x.to_lowercase().cmp(y.to_lowercase());
1244                if o != Ordering::Equal {
1245                    return o;
1246                }
1247                a.next();
1248                b.next();
1249            }
1250        }
1251    }
1252}
1253
1254/// Adds a native column for each of `columns`.
1255fn add_columns<T>(table: &NSTableView, columns: &[Column<T>]) {
1256    for c in columns {
1257        let column = NSTableColumn::initWithIdentifier(NSTableColumn::alloc(mtm()), &NSString::from_str(&c.id));
1258        column.setTitle(&NSString::from_str(&c.title));
1259        column.setWidth(c.width);
1260        column.setMinWidth(c.min_width);
1261        column.setResizingMask(NSTableColumnResizingOptions::UserResizingMask);
1262        if c.sortable {
1263            let descriptor = NSSortDescriptor::sortDescriptorWithKey_ascending(Some(&NSString::from_str(&c.id)), true);
1264            column.setSortDescriptorPrototype(Some(&descriptor));
1265        }
1266        table.addTableColumn(&column);
1267    }
1268}
1269
1270/// A native table backed by rows of `T`. See the module docs.
1271pub struct TableModel<T: 'static> {
1272    inner: Rc<Inner<T>>,
1273}
1274
1275impl<T: 'static> Clone for TableModel<T> {
1276    fn clone(&self) -> Self {
1277        Self { inner: self.inner.clone() }
1278    }
1279}
1280
1281impl<T: 'static> std::fmt::Debug for TableModel<T> {
1282    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1283        write!(f, "TableModel({:?}, {} rows)", self.inner.id, self.inner.rows.borrow().len())
1284    }
1285}
1286
1287impl<T: 'static> TableModel<T> {
1288    /// Creates the native table (not yet in a window: it's added the first
1289    /// time the host draws it, see [`TableModel::ensure_mounted`]).
1290    pub fn new(id: ViewId, columns: Vec<Column<T>>) -> Self {
1291        let mtm = mtm();
1292        crate::testing::LIVE_OBJC.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1293        let source = Source::alloc(mtm).set_ivars(SourceIvars { data: RefCell::new(None), created: Cell::new(0) });
1294        // SAFETY: plain NSObject init.
1295        let source: Retained<Source> = unsafe { msg_send![super(source), init] };
1296
1297        let table: Retained<HostTableView> = unsafe { msg_send![HostTableView::alloc(mtm), init] };
1298        table.setStyle(NSTableViewStyle::FullWidth);
1299        table.setUsesAlternatingRowBackgroundColors(true);
1300        table.setAllowsMultipleSelection(true);
1301        table.setAllowsColumnReordering(true);
1302        table.setAllowsColumnResizing(true);
1303        add_columns(&table, &columns);
1304        let scroll = NSScrollView::new(mtm);
1305        scroll.setHasVerticalScroller(true);
1306        scroll.setHasHorizontalScroller(true);
1307        scroll.setAutohidesScrollers(true);
1308        scroll.setDocumentView(Some(&table));
1309
1310        let inner = Rc::new(Inner {
1311            id,
1312            columns: RefCell::new(columns),
1313            rows: RefCell::new(Vec::new()),
1314            order: RefCell::new(Vec::new()),
1315            groups: RefCell::new(Vec::new()),
1316            group_by: RefCell::new(None),
1317            sort: RefCell::new(None),
1318            sorts_in_place: Cell::new(true),
1319            events: RefCell::new(VecDeque::new()),
1320            quiet: Cell::new(false),
1321            mounted: Cell::new(false),
1322            transfer: RefCell::new(Transfer::default()),
1323            scroll,
1324            table: table.clone(),
1325            _source: source.clone(),
1326        });
1327        crate::testing::LIVE_MODELS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1328        let weak: Weak<dyn Data> = Rc::downgrade(&inner) as Weak<dyn Data>;
1329        *source.ivars().data.borrow_mut() = Some(weak);
1330        // SAFETY: the source is kept alive by the model (`_source`), and the
1331        // model removes the table when dropped.
1332        unsafe {
1333            table.setDataSource(Some(ProtocolObject::from_ref(&*source)));
1334            table.setDelegate(Some(ProtocolObject::from_ref(&*source)));
1335            table.setTarget(Some(&source));
1336            table.setDoubleAction(Some(sel!(activate:)));
1337        }
1338        Self { inner }
1339    }
1340
1341    /// The view id the table was created with.
1342    pub fn id(&self) -> ViewId {
1343        self.inner.id
1344    }
1345
1346    /// Adds the table to the attached window if it isn't yet. Called by the
1347    /// host widget before placing it.
1348    pub fn ensure_mounted(&self) {
1349        if !self.inner.mounted.get() && crate::is_attached() {
1350            crate::mount(self.inner.id, Retained::into_super(self.inner.scroll.clone()));
1351            self.inner.mounted.set(true);
1352        }
1353    }
1354
1355    /// Replaces the columns, keeping the same native table (a query
1356    /// browser's results change shape with every query). The sort is
1357    /// cleared. Call [`set_rows`](Self::set_rows) after it when the rows
1358    /// change too: nothing is drawn in between.
1359    pub fn set_columns(&self, columns: Vec<Column<T>>) {
1360        let table = &self.inner.table;
1361        *self.inner.sort.borrow_mut() = None;
1362        self.inner.quiet.set(true);
1363        table.setSortDescriptors(&NSArray::new());
1364        let old: Vec<_> = table.tableColumns().iter().collect();
1365        for column in old {
1366            table.removeTableColumn(&column);
1367        }
1368        add_columns(table, &columns);
1369        *self.inner.columns.borrow_mut() = columns;
1370        self.inner.compute_order();
1371        table.reloadData();
1372        self.inner.quiet.set(false);
1373    }
1374
1375    /// Replaces all rows (the current sort is applied). Clears the selection.
1376    pub fn set_rows(&self, rows: Vec<T>) {
1377        *self.inner.rows.borrow_mut() = rows;
1378        self.inner.compute_order();
1379        self.inner.quiet.set(true);
1380        self.inner.table.reloadData();
1381        // SAFETY: nil sender.
1382        unsafe { self.inner.table.deselectAll(None) };
1383        self.inner.quiet.set(false);
1384        // Views bound to the selection hear that it was cleared.
1385        crate::request_redraw();
1386    }
1387
1388    /// The rows, in model order (unsorted).
1389    pub fn rows(&self) -> Ref<'_, Vec<T>> {
1390        self.inner.rows.borrow()
1391    }
1392
1393    /// Number of rows.
1394    pub fn len(&self) -> usize {
1395        self.inner.rows.borrow().len()
1396    }
1397
1398    /// Whether there are no rows.
1399    pub fn is_empty(&self) -> bool {
1400        self.len() == 0
1401    }
1402
1403    /// Replaces one row. Redraws only that row unless the table is sorted
1404    /// (then the order is recomputed; the selection is kept).
1405    pub fn update_row(&self, index: usize, row: T) {
1406        if let Some(slot) = self.inner.rows.borrow_mut().get_mut(index) {
1407            *slot = row;
1408        } else {
1409            return;
1410        }
1411        if self.inner.sort.borrow().is_some() && self.inner.sorts_in_place.get() {
1412            self.inner.resort_keeping_selection();
1413            return;
1414        }
1415        let Some(view_row) = self.inner.order.borrow().iter().position(|&m| m == index) else { return };
1416        let columns = NSIndexSet::indexSetWithIndexesInRange(objc2_foundation::NSRange::new(0, self.inner.columns.borrow().len()));
1417        self.inner.table.reloadDataForRowIndexes_columnIndexes(&NSIndexSet::indexSetWithIndex(view_row), &columns);
1418    }
1419
1420    /// Inserts a row at a model index (the selection is kept).
1421    pub fn insert(&self, index: usize, row: T) {
1422        let selected = self.inner.selection_model_rows();
1423        self.inner.rows.borrow_mut().insert(index, row);
1424        let selected: Vec<usize> = selected.into_iter().map(|r| if r >= index { r + 1 } else { r }).collect();
1425        self.inner.compute_order();
1426        self.inner.table.reloadData();
1427        self.inner.select_model_rows(&selected);
1428    }
1429
1430    /// Appends rows in one step, for live data (a log tail, a feed): when
1431    /// unsorted, the new rows are added to the end and AppKit only learns
1432    /// the new count (cost independent of the rows already there; the
1433    /// selection is kept). When sorted, the order is recomputed.
1434    pub fn append(&self, rows: Vec<T>) {
1435        if rows.is_empty() {
1436            return;
1437        }
1438        let start = self.len();
1439        self.inner.rows.borrow_mut().extend(rows);
1440        let grouped = self.inner.group_by.borrow().is_some();
1441        if grouped || (self.inner.sort.borrow().is_some() && self.inner.sorts_in_place.get()) {
1442            self.inner.resort_keeping_selection();
1443            return;
1444        }
1445        let end = self.len();
1446        self.inner.order.borrow_mut().extend(start..end);
1447        self.inner.table.noteNumberOfRowsChanged();
1448    }
1449
1450    /// Scrolls so the last row is visible.
1451    pub fn scroll_to_end(&self) {
1452        let n = self.inner.order.borrow().len();
1453        if n > 0 {
1454            self.inner.table.scrollRowToVisible((n - 1) as NSInteger);
1455        }
1456    }
1457
1458    /// Whether the table is scrolled to its last row (within one row), e.g.
1459    /// to keep following new rows only while the user hasn't scrolled up.
1460    pub fn is_at_end(&self) -> bool {
1461        let table = &self.inner.table;
1462        let visible = table.visibleRect();
1463        let bottom = visible.origin.y + visible.size.height;
1464        bottom >= table.bounds().size.height - table.rowHeight() - table.intercellSpacing().height - 1.0
1465    }
1466
1467    /// Appends a row.
1468    pub fn push(&self, row: T) {
1469        let len = self.len();
1470        self.insert(len, row);
1471    }
1472
1473    /// Removes a row (the selection is kept for the other rows).
1474    pub fn remove(&self, index: usize) -> Option<T> {
1475        if index >= self.len() {
1476            return None;
1477        }
1478        let selected = self.inner.selection_model_rows();
1479        let row = self.inner.rows.borrow_mut().remove(index);
1480        let selected: Vec<usize> =
1481            selected.into_iter().filter(|&r| r != index).map(|r| if r > index { r - 1 } else { r }).collect();
1482        self.inner.compute_order();
1483        self.inner.table.reloadData();
1484        self.inner.select_model_rows(&selected);
1485        Some(row)
1486    }
1487
1488    /// Moves `rows` (model indices) to just above the row `before` (or to
1489    /// the end), keeping their order, as a drop reported by
1490    /// [`TableEvent::RowsMoved`] asks. Returns their new model indices; they
1491    /// end up selected.
1492    pub fn move_rows(&self, rows: &[usize], before: Option<usize>) -> Vec<usize> {
1493        let mut moving: Vec<usize> = rows.iter().copied().filter(|&r| r < self.len()).collect();
1494        moving.sort_unstable();
1495        moving.dedup();
1496        let at = {
1497            let mut all = self.inner.rows.borrow_mut();
1498            let end = before.unwrap_or(all.len());
1499            // Rows staying put above the drop point.
1500            let at = (0..end.min(all.len())).filter(|r| moving.binary_search(r).is_err()).count();
1501            let mut taken = Vec::with_capacity(moving.len());
1502            for &r in moving.iter().rev() {
1503                taken.push(all.remove(r));
1504            }
1505            for (i, row) in taken.into_iter().rev().enumerate() {
1506                all.insert(at + i, row);
1507            }
1508            at
1509        };
1510        let moved: Vec<usize> = (at..at + moving.len()).collect();
1511        self.inner.compute_order();
1512        self.inner.table.reloadData();
1513        self.inner.select_model_rows(&moved);
1514        moved
1515    }
1516
1517    /// Lets rows be dragged out: each carries its cells as tab-separated
1518    /// text (for other apps), and its model index for
1519    /// [`set_reorderable`](Self::set_reorderable). Off by default (a drag
1520    /// then extends the selection).
1521    pub fn set_row_drag(&self, on: bool) {
1522        self.inner.transfer.borrow_mut().drag = on;
1523        self.inner.table.setDraggingSourceOperationMask_forLocal(NSDragOperation::Copy, false);
1524        self.register_drag_types();
1525    }
1526
1527    /// Lets the user drag rows to a new place (also turns on
1528    /// [`set_row_drag`](Self::set_row_drag)); each drop is reported as
1529    /// [`TableEvent::RowsMoved`]. Refused while the table is sorted.
1530    pub fn set_reorderable(&self, on: bool) {
1531        if on {
1532            self.set_row_drag(true);
1533            self.inner.table.setDraggingSourceOperationMask_forLocal(NSDragOperation::Move, true);
1534        }
1535        self.inner.transfer.borrow_mut().reorder = on;
1536        self.register_drag_types();
1537    }
1538
1539    /// Accepts files dropped from the Finder: `Some(&["csv", "txt"])` for
1540    /// those extensions, `Some(&[])` for any file, `None` to stop. Each drop
1541    /// is reported as [`TableEvent::FilesDropped`].
1542    pub fn set_file_drop(&self, extensions: Option<&[&str]>) {
1543        self.inner.transfer.borrow_mut().files = extensions.map(|e| e.iter().map(|s| s.to_string()).collect());
1544        self.register_drag_types();
1545    }
1546
1547    /// Reports ⌘V on the table as [`TableEvent::Paste`] (and enables Paste
1548    /// in the Edit menu while there is text to paste). Off by default.
1549    pub fn set_pastes(&self, on: bool) {
1550        self.inner.transfer.borrow_mut().pastes = on;
1551    }
1552
1553    /// Reports these keys, pressed without ⌘, ⌥ or ⌃ while rows are
1554    /// selected, as [`TableEvent::Key`] instead of AppKit's handling
1555    /// (Space would type-select, Delete beep). None by default.
1556    pub fn set_keys(&self, keys: &[TableKey]) {
1557        self.inner.transfer.borrow_mut().keys = keys.to_vec();
1558    }
1559
1560    fn register_drag_types(&self) {
1561        let t = self.inner.transfer.borrow();
1562        let mut types = Vec::new();
1563        if t.reorder {
1564            types.push(row_type());
1565        }
1566        if t.files.is_some() {
1567            // SAFETY: AppKit's pasteboard type constant.
1568            types.push(NSString::from_str(&unsafe { NSPasteboardTypeFileURL }.to_string()));
1569        }
1570        self.inner.table.unregisterDraggedTypes();
1571        if !types.is_empty() {
1572            self.inner.table.registerForDraggedTypes(&NSArray::from_retained_slice(&types));
1573        }
1574    }
1575
1576    /// The selected rows as tab-separated text (columns in their current
1577    /// order, one line per row, as ⌘C copies them).
1578    pub fn selected_text(&self) -> String {
1579        let rows = indexes(&self.inner.table.selectedRowIndexes());
1580        self.inner.rows_text(&rows, &column_ids(&self.inner.table))
1581    }
1582
1583    /// Copies the selected rows to `pasteboard` (what ⌘C does with the
1584    /// general pasteboard). False if nothing is selected.
1585    pub fn copy_to(&self, pasteboard: &NSPasteboard) -> bool {
1586        self.inner.table.copy_rows(pasteboard)
1587    }
1588
1589    /// Pastes `pasteboard`'s text (what ⌘V does with the general
1590    /// pasteboard): queues [`TableEvent::Paste`] if the table takes pastes.
1591    pub fn paste_from(&self, pasteboard: &NSPasteboard) -> bool {
1592        self.inner.table.paste_text(pasteboard)
1593    }
1594
1595    /// The model index of the row shown at `position` (0 = top row as
1596    /// currently sorted); `None` past the end or for a group header.
1597    pub fn row_at(&self, position: usize) -> Option<usize> {
1598        self.inner.model_row(position)
1599    }
1600
1601    /// Groups the rows under headers by `key` (e.g. a date or a category):
1602    /// groups appear in the order their first row has in the model, rows
1603    /// keep the sort's order within each group, and each group starts with
1604    /// a header row showing the key (full width, not selectable, floating
1605    /// while its rows scroll). `None` ungroups. Row indices in events stay
1606    /// model indices.
1607    pub fn set_group_by(&self, key: Option<GroupKey<T>>) {
1608        *self.inner.group_by.borrow_mut() = key;
1609        self.inner.table.setFloatsGroupRows(true);
1610        self.inner.resort_keeping_selection();
1611    }
1612
1613    /// The groups' titles, in the order shown (empty when not grouped).
1614    pub fn groups(&self) -> Vec<String> {
1615        self.inner.groups.borrow().clone()
1616    }
1617
1618    /// The number of rows shown, group headers included.
1619    pub fn shown_rows(&self) -> usize {
1620        self.inner.order.borrow().len()
1621    }
1622
1623    /// Selected rows (model indices, ascending in view order).
1624    pub fn selection(&self) -> Vec<usize> {
1625        self.inner.selection_model_rows()
1626    }
1627
1628    /// Selects rows by model index (emits no event).
1629    pub fn select(&self, rows: &[usize]) {
1630        self.inner.select_model_rows(rows);
1631        if let Some(&first) = rows.first()
1632            && let Some(view_row) = self.inner.order.borrow().iter().position(|&m| m == first)
1633        {
1634            self.inner.table.scrollRowToVisible(view_row as NSInteger);
1635        }
1636    }
1637
1638    /// The current sort, if any.
1639    pub fn sort(&self) -> Option<Sort> {
1640        self.inner.sort.borrow().clone()
1641    }
1642
1643    /// Sets the sort (shown in the header) and, with built-in sorting, applies it.
1644    pub fn set_sort(&self, sort: Option<Sort>) {
1645        let descriptors = match &sort {
1646            Some(s) => NSArray::from_retained_slice(&[NSSortDescriptor::sortDescriptorWithKey_ascending(
1647                Some(&NSString::from_str(&s.column)),
1648                s.ascending,
1649            )]),
1650            None => NSArray::new(),
1651        };
1652        *self.inner.sort.borrow_mut() = sort;
1653        // setSortDescriptors calls back sortDescriptorsDidChange; quiet the event.
1654        let events_before = self.inner.events.borrow().len();
1655        self.inner.table.setSortDescriptors(&descriptors);
1656        self.inner.events.borrow_mut().truncate(events_before);
1657        if self.inner.sorts_in_place.get() {
1658            self.inner.resort_keeping_selection();
1659        }
1660    }
1661
1662    /// Built-in sorting (default on): header clicks reorder the rows here.
1663    /// Turn it off to sort yourself on [`TableEvent::Sort`] (e.g. in a database)
1664    /// and call [`TableModel::set_rows`].
1665    pub fn set_sorts_in_place(&self, on: bool) {
1666        self.inner.sorts_in_place.set(on);
1667    }
1668
1669    /// Columns in their current order, with widths.
1670    pub fn column_state(&self) -> Vec<ColumnState> {
1671        self.inner
1672            .table
1673            .tableColumns()
1674            .iter()
1675            .map(|c| ColumnState { id: c.identifier().to_string(), width: c.width() })
1676            .collect()
1677    }
1678
1679    /// Restores a saved arrangement (unknown ids are ignored).
1680    pub fn set_column_state(&self, state: &[ColumnState]) {
1681        let table = &self.inner.table;
1682        for (target, s) in state.iter().enumerate() {
1683            let index = table.columnWithIdentifier(&NSString::from_str(&s.id));
1684            if index < 0 {
1685                continue;
1686            }
1687            if let Some(column) = table.tableColumns().iter().nth(index as usize) {
1688                column.setWidth(s.width);
1689            }
1690            if index as usize != target && target < table.numberOfColumns() as usize {
1691                table.moveColumn_toColumn(index, target as NSInteger);
1692            }
1693        }
1694        // moveColumn fires the delegate; this was the program, not the user.
1695        self.inner.events.borrow_mut().retain(|e| *e != TableEvent::ColumnsChanged);
1696    }
1697
1698    /// Takes the queued user events (for the host widget).
1699    pub fn drain_events(&self) -> Vec<TableEvent> {
1700        self.inner.events.borrow_mut().drain(..).collect()
1701    }
1702
1703    /// Diagnostics: cell views created so far (reuse keeps this near the
1704    /// number of visible cells).
1705    pub fn cells_created(&self) -> usize {
1706        self.inner._source.ivars().created.get()
1707    }
1708
1709    /// The `NSScrollView` holding the table, for hosts that place it
1710    /// themselves (no [`crate::attach`]ed window).
1711    pub fn scroll_view(&self) -> Retained<NSScrollView> {
1712        self.inner.scroll.clone()
1713    }
1714
1715    /// The underlying `NSTableView` (escape hatch).
1716    pub fn table_view(&self) -> Retained<NSTableView> {
1717        Retained::into_super(self.inner.table.clone())
1718    }
1719}
1720
1721#[cfg(test)]
1722mod tests {
1723    use super::natural_cmp;
1724    use std::cmp::Ordering::*;
1725
1726    #[test]
1727    fn key_matches_natural_order() {
1728        use super::natural_key;
1729        let words = ["Item 10", "item 9", "Item 009", "apple", "Banana", "x", "x1", "a2b", "a10b", "Zo", "zoe 2"];
1730        for a in words {
1731            for b in words {
1732                let by_key = natural_key(a).cmp(&natural_key(b));
1733                let by_cmp = natural_cmp(a, b);
1734                if by_cmp != std::cmp::Ordering::Equal {
1735                    assert_eq!(by_key, by_cmp, "{a:?} vs {b:?}");
1736                }
1737            }
1738        }
1739    }
1740
1741    #[test]
1742    fn dates_shown_in_the_users_format() {
1743        use super::{Kind, Value, display};
1744        let none = display(Kind::Date { time: false }, &Value::Number(f64::NEG_INFINITY));
1745        assert_eq!(none, "");
1746        // 2020-09-13 12:26:40 UTC: the year shows in every medium style.
1747        let day = display(Kind::Date { time: false }, &Value::Number(1_600_000_000.0));
1748        let with_time = display(Kind::Date { time: true }, &Value::Number(1_600_000_000.0));
1749        assert!(day.contains("2020") && with_time.contains("2020") && with_time.len() > day.len(), "{day:?} {with_time:?}");
1750    }
1751
1752    #[test]
1753    fn natural_order() {
1754        assert_eq!(natural_cmp("Item 9", "Item 10"), Less);
1755        assert_eq!(natural_cmp("apple", "Banana"), Less);
1756        assert_eq!(natural_cmp("a2b", "a02b"), Equal);
1757        assert_eq!(natural_cmp("x", "x1"), Less);
1758    }
1759}