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, NSPasteboardTypeURL,
27    NSPasteboardTypeString, NSPasteboardTypeTabularText, NSPasteboardWriting, NSResponder, NSScrollView, NSTableColumn,
28    NSTableColumnResizingOptions, NSTableView, NSTableViewDataSource, NSTableViewDelegate, NSTableViewDropOperation,
29    NSTableViewStyle, NSTextAlignment, NSTextField, NSUserInterfaceItemIdentification, NSView, NSBezierPath, NSColor, NSTableRowView,
30};
31use objc2_foundation::{
32    NSArray, NSIndexSet, NSInteger, NSMutableIndexSet, NSNotification, NSRect, 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, 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, shown
58    /// as `none`'s text).
59    Date { time: bool, none: Option<std::rc::Rc<str>> },
60}
61
62/// A small image shown before a cell's text (see [`Column::icon`]).
63#[derive(Debug, Clone, PartialEq)]
64pub enum CellImage {
65    /// An SF Symbol by name.
66    Symbol(String),
67    /// The Finder's icon for a file or folder.
68    FileIcon(std::path::PathBuf),
69}
70
71type IconFn<T> = Box<dyn Fn(&T) -> Option<CellImage>>;
72type StyleFn<T> = Box<dyn Fn(&T) -> CellStyle>;
73
74/// How a cell's text looks (see [`Column::style`]): the default for each
75/// field is the table's own look.
76#[derive(Debug, Clone, Default, PartialEq)]
77pub struct CellStyle {
78    /// The text's colour.
79    pub color: Option<crate::text::Color>,
80    /// A tint behind the cell (a changed value, say).
81    pub background: Option<crate::text::Color>,
82    /// Italic text (a placeholder such as NULL).
83    pub italic: bool,
84    /// Struck-through text (a row about to be deleted).
85    pub strikethrough: bool,
86}
87
88/// A row's group (see [`TableModel::set_group_by`]).
89pub type GroupKey<T> = Box<dyn Fn(&T) -> String>;
90
91/// A column: an id (stable, used for sorting and saved state), a title, and
92/// how to get the cell value from a row.
93pub struct Column<T> {
94    id: String,
95    title: String,
96    width: f64,
97    min_width: f64,
98    kind: Kind,
99    sortable: bool,
100    editable: bool,
101    fit: bool,
102    icon: Option<IconFn<T>>,
103    style: Option<StyleFn<T>>,
104    value: Box<dyn Fn(&T) -> Value>,
105}
106
107impl<T> Column<T> {
108    fn new(id: &str, title: &str, kind: Kind, value: Box<dyn Fn(&T) -> Value>) -> Self {
109        Self { id: id.into(), title: title.into(), width: 120.0, min_width: 40.0, kind, sortable: true, editable: false, fit: false, icon: None, style: None, value }
110    }
111
112    /// A text column.
113    pub fn text(id: &str, title: &str, value: impl Fn(&T) -> String + 'static) -> Self {
114        Self::new(id, title, Kind::Text, Box::new(move |row| Value::Text(value(row))))
115    }
116
117    /// A right-aligned number column, sorted numerically. `f64::NAN` is no
118    /// value (a database's NULL, say): shown as nothing.
119    pub fn number(id: &str, title: &str, value: impl Fn(&T) -> f64 + 'static) -> Self {
120        Self::new(id, title, Kind::Number { decimals: 0 }, Box::new(move |row| Value::Number(value(row))))
121    }
122
123    /// A checkbox column. Clicking a checkbox emits [`TableEvent::Toggle`];
124    /// the model doesn't change the row itself.
125    pub fn check(id: &str, title: &str, value: impl Fn(&T) -> bool + 'static) -> Self {
126        Self::new(id, title, Kind::Check, Box::new(move |row| Value::Bool(value(row)))).width(60.0)
127    }
128
129    /// A progress bar from 0 to 1 (values outside are clamped). Sorted and
130    /// copied as the number; VoiceOver reads it as a percentage.
131    pub fn progress(id: &str, title: &str, value: impl Fn(&T) -> f64 + 'static) -> Self {
132        Self::new(id, title, Kind::Progress, Box::new(move |row| Value::Number(value(row).clamp(0.0, 1.0)))).width(100.0)
133    }
134
135    /// A date column: shown in the user's format and language ("12 Mar
136    /// 2024", "Today", "Yesterday"), sorted by date, oldest first;
137    /// `None` shows nothing and sorts before every date. Copied as shown.
138    /// [`with_time`](Self::with_time) adds the time.
139    pub fn date(id: &str, title: &str, value: impl Fn(&T) -> Option<std::time::SystemTime> + 'static) -> Self {
140        Self::new(
141            id,
142            title,
143            Kind::Date { time: false, none: None },
144            Box::new(move |row| {
145                let secs = value(row).map_or(f64::NEG_INFINITY, |t| match t.duration_since(std::time::UNIX_EPOCH) {
146                    Ok(d) => d.as_secs_f64(),
147                    Err(e) => -e.duration().as_secs_f64(),
148                });
149                Value::Number(secs)
150            }),
151        )
152        .width(150.0)
153    }
154
155    /// Shows a date column's time too ("Today at 09:41").
156    pub fn with_time(mut self) -> Self {
157        if let Kind::Date { time, .. } = &mut self.kind {
158            *time = true;
159        }
160        self
161    }
162
163    /// What a date column shows for `None` (default nothing): "Running"
164    /// for a timer with no end yet, "Never" for a file never opened. It
165    /// still sorts before every date, and is copied as shown.
166    pub fn none_text(mut self, text: &str) -> Self {
167        if let Kind::Date { none, .. } = &mut self.kind {
168            *none = Some(text.into());
169        }
170        self
171    }
172
173    /// Shows an image before each cell's text (a text or number column),
174    /// e.g. a file's icon before its name. `None` leaves the space empty.
175    pub fn icon(mut self, image: impl Fn(&T) -> Option<CellImage> + 'static) -> Self {
176        self.icon = Some(Box::new(image));
177        self
178    }
179
180    /// Styles each cell of a text or number column from its row: a colour,
181    /// a background tint, italic or struck-through text. The style is read
182    /// when a cell is shown; after changing what it depends on, refresh the
183    /// rows ([`TableModel::update_row`]).
184    pub fn style(mut self, style: impl Fn(&T) -> CellStyle + 'static) -> Self {
185        self.style = Some(Box::new(style));
186        self
187    }
188
189    /// Sizes the column to its widest content (and its title) whenever the
190    /// rows change. With many rows, the longest values are measured.
191    pub fn fit(mut self) -> Self {
192        self.fit = true;
193        self
194    }
195
196    /// Initial width in points (default 120).
197    pub fn width(mut self, width: f64) -> Self {
198        self.width = width;
199        self
200    }
201
202    /// Smallest width the user can drag the column to.
203    pub fn min_width(mut self, min_width: f64) -> Self {
204        self.min_width = min_width;
205        self
206    }
207
208    /// Decimal places shown for a number column (default 0).
209    pub fn decimals(mut self, decimals: usize) -> Self {
210        if let Kind::Number { .. } = self.kind {
211            self.kind = Kind::Number { decimals };
212        }
213        self
214    }
215
216    /// Lets the user edit this column's text or number cells (double-click,
217    /// or Return on the selected row's cell). Finishing an edit (Return, Tab
218    /// or a click elsewhere; not Escape) emits [`TableEvent::Edit`]; the model doesn't change the row: apply it with
219    /// [`TableModel::update_row`]. No effect on checkbox columns.
220    pub fn editable(mut self, editable: bool) -> Self {
221        self.editable = editable;
222        self
223    }
224
225    /// Whether a header click sorts by this column (default true).
226    pub fn sortable(mut self, sortable: bool) -> Self {
227        self.sortable = sortable;
228        self
229    }
230}
231
232fn display(kind: &Kind, value: &Value) -> String {
233    match (kind, value) {
234        (_, Value::Text(s)) => s.clone(),
235        (Kind::Date { none: Some(text), .. }, Value::Number(n)) if !n.is_finite() => text.to_string(),
236        (Kind::Date { time, .. }, Value::Number(n)) => format_date(*n, *time),
237        // NaN is no value (a database's NULL): shown as nothing.
238        (Kind::Number { .. }, Value::Number(n)) if n.is_nan() => String::new(),
239        (Kind::Number { decimals: 0 }, Value::Number(n)) => format!("{n:.0}"),
240        (Kind::Number { decimals }, Value::Number(n)) => format!("{n:.decimals$}").replacen('.', &decimal_separator(), 1),
241        (_, Value::Number(n)) => n.to_string(),
242        (_, Value::Bool(b)) => if *b { "Yes".into() } else { "No".into() },
243    }
244}
245
246thread_local! {
247    /// The date formatters (date only, date and time), made once: making
248    /// one is slow, and a table formats every visible cell.
249    static DATE_FORMATS: UiCell<[Option<Retained<objc2_foundation::NSDateFormatter>>; 2]> = const { UiCell::new([None, None]) };
250}
251
252thread_local! {
253    /// The user's decimal separator ("." or ","), read once.
254    static DECIMAL: UiCell<Option<String>> = const { UiCell::new(None) };
255}
256
257/// The user's region's decimal separator: number columns show 78,4 in
258/// Germany. (No grouping: a column of years or ids would read 2,026.)
259fn decimal_separator() -> String {
260    DECIMAL.with_borrow_mut(|d| d.get_or_insert_with(|| objc2_foundation::NSLocale::currentLocale().decimalSeparator().to_string()).clone())
261}
262
263/// `secs` since 1970 in the user's date format, relative where it can be
264/// ("Today"); empty when not finite (no date).
265fn format_date(secs: f64, time: bool) -> String {
266    use objc2_foundation::{NSDate, NSDateFormatter, NSDateFormatterStyle};
267    if !secs.is_finite() {
268        return String::new();
269    }
270    let formatter = DATE_FORMATS.with_borrow_mut(|f| {
271        f[time as usize]
272            .get_or_insert_with(|| {
273                let f = NSDateFormatter::new();
274                f.setDateStyle(NSDateFormatterStyle::MediumStyle);
275                f.setTimeStyle(if time { NSDateFormatterStyle::ShortStyle } else { NSDateFormatterStyle::NoStyle });
276                f.setDoesRelativeDateFormatting(true);
277                f
278            })
279            .clone()
280    });
281    formatter.stringFromDate(&NSDate::dateWithTimeIntervalSince1970(secs)).to_string()
282}
283
284/// How rows animate in and out (see [`TableModel::set_animates`]): a fade
285/// with a slide, as Mail's message list does.
286const ANIMATION: objc2_app_kit::NSTableViewAnimationOptions =
287    objc2_app_kit::NSTableViewAnimationOptions(objc2_app_kit::NSTableViewAnimationOptions::EffectFade.0 | objc2_app_kit::NSTableViewAnimationOptions::SlideDown.0);
288
289/// Group header slots in `order` carry this bit (and the group's index).
290const HEADER: usize = 1 << (usize::BITS - 1);
291
292/// The table's sort: a column id and a direction.
293#[derive(Debug, Clone, PartialEq, Eq)]
294pub struct Sort {
295    /// The column id.
296    pub column: String,
297    /// Ascending (A→Z, 0→9) or descending.
298    pub ascending: bool,
299}
300
301/// A column's place and width, as the user arranged them (for saving).
302#[derive(Debug, Clone, PartialEq)]
303pub struct ColumnState {
304    /// The column id.
305    pub id: String,
306    /// Width in points.
307    pub width: f64,
308}
309
310/// Something the user did in the table. Row indices are model indices
311/// (positions in the rows given to [`TableModel::set_rows`]), whatever the sort.
312#[derive(Debug, Clone, PartialEq)]
313#[non_exhaustive]
314pub enum TableEvent {
315    /// The selected rows changed.
316    Selection(Vec<usize>),
317    /// Double-click or Return on a row.
318    Activate(usize),
319    /// The user clicked a column header. With built-in sorting on (the
320    /// default) the rows are already shown in the new order.
321    Sort(Sort),
322    /// A checkbox cell was clicked. The model doesn't change the row: apply
323    /// it with [`TableModel::update_row`].
324    Toggle {
325        /// The row (model index).
326        row: usize,
327        /// The column id.
328        column: String,
329        /// The checkbox's new state.
330        value: bool,
331    },
332    /// Columns were moved or resized; read [`TableModel::column_state`].
333    ColumnsChanged,
334    /// The user finished editing a cell of an [`Column::editable`] column.
335    /// The model doesn't change the row: apply it with
336    /// [`TableModel::update_row`].
337    Edit {
338        /// The row (model index).
339        row: usize,
340        /// The column id.
341        column: String,
342        /// The text the user entered.
343        value: String,
344    },
345    /// The user dragged rows to a new place (see
346    /// [`TableModel::set_reorderable`]). The model doesn't move them: apply
347    /// it with [`TableModel::move_rows`].
348    RowsMoved {
349        /// The dragged rows (model indices).
350        rows: Vec<usize>,
351        /// The row they were dropped above (model index), or `None` for the end.
352        before: Option<usize>,
353    },
354    /// Files were dropped on the table (see [`TableModel::set_file_drop`]).
355    FilesDropped {
356        /// The files' paths.
357        paths: Vec<std::path::PathBuf>,
358        /// The row they were dropped above (model index), or `None` for the end.
359        before: Option<usize>,
360    },
361    /// Web addresses were dropped on the table, dragged from a browser (see
362    /// [`TableModel::set_url_drop`]).
363    UrlsDropped {
364        /// The addresses, as text (`https://…`).
365        urls: Vec<String>,
366        /// The row they were dropped above (model index), or `None` for the end.
367        before: Option<usize>,
368    },
369    /// The user pasted (⌘V) text (see [`TableModel::set_pastes`]); rows
370    /// copied from a table arrive as tab-separated lines.
371    Paste(String),
372    /// The user pressed a bare key the table handles (see
373    /// [`TableModel::set_keys`]) with rows selected.
374    Key {
375        /// The key.
376        key: TableKey,
377        /// The selected rows (model indices).
378        rows: Vec<usize>,
379    },
380    /// The focused column changed (see [`TableModel::set_cell_focus`]): the
381    /// user clicked a cell in another column, or pressed ← or →.
382    FocusedColumn(Option<String>),
383}
384
385/// Which transfers a table takes part in (see the `set_…` methods on
386/// [`TableModel`]).
387#[derive(Debug, Clone, Default)]
388struct Transfer {
389    drag: bool,
390    reorder: bool,
391    /// Bare keys reported as [`TableEvent::Key`].
392    keys: Vec<TableKey>,
393    /// File drops: `None` off; `Some(extensions)`, any file if empty.
394    files: Option<Vec<String>>,
395    /// Web addresses dragged from a browser (`http`, `https` and others).
396    urls: bool,
397    pastes: bool,
398    /// A focused column, moved by clicks and ← →, drawn in the selected rows.
399    cell_focus: bool,
400}
401
402/// The pasteboard type carrying a dragged row's model index (only read back
403/// by the table it came from).
404fn row_type() -> Retained<NSString> {
405    NSString::from_str("dev.ferrokit.table-row")
406}
407
408/// Type-erased view of a model for the Objective-C data source.
409trait Data {
410    fn count(&self) -> usize;
411    fn cell(&self, view_row: usize, column: &str) -> Option<(Kind, Value)>;
412    fn editable(&self, column: &str) -> bool;
413    fn title(&self, column: &str) -> Option<String>;
414    fn model_row(&self, view_row: usize) -> Option<usize>;
415    fn sort_changed(&self, sort: Option<Sort>);
416    fn push(&self, event: TableEvent);
417    fn quiet(&self) -> bool;
418    fn transfer(&self) -> Transfer;
419    fn sorted(&self) -> bool;
420    /// Tab-separated text of rows (view positions), columns in `columns` order.
421    fn rows_text(&self, view_rows: &[usize], columns: &[String]) -> String;
422    /// The title of the group header shown at `view_row`, if it is one.
423    fn group_title(&self, view_row: usize) -> Option<String>;
424    /// The cell's image (an [`Column::icon`] column).
425    fn icon(&self, view_row: usize, column: &str) -> Option<CellImage>;
426    /// Whether the column has icons.
427    fn has_icon(&self, column: &str) -> bool;
428    /// The cell's style (a [`Column::style`] column).
429    fn style(&self, view_row: usize, column: &str) -> Option<CellStyle>;
430    /// The focused column's id (see [`TableModel::set_cell_focus`]).
431    fn focus(&self) -> Option<String>;
432    /// Focuses `column`, reporting it as an event when `report`.
433    fn set_focus(&self, column: Option<String>, report: bool);
434}
435
436struct SourceIvars {
437    data: RefCell<Option<Weak<dyn Data>>>,
438    /// Cell views created (not reused), for diagnostics.
439    created: Cell<usize>,
440}
441
442define_class!(
443    // Data source, delegate and action target for one table.
444    #[unsafe(super(NSObject))]
445    #[thread_kind = MainThreadOnly]
446    #[name = "FerrokitCoreTableSource"]
447    #[ivars = SourceIvars]
448    struct Source;
449
450    unsafe impl NSObjectProtocol for Source {}
451    unsafe impl NSControlTextEditingDelegate for Source {}
452
453    unsafe impl NSTableViewDataSource for Source {
454        #[unsafe(method(numberOfRowsInTableView:))]
455        fn number_of_rows(&self, _table: &NSTableView) -> NSInteger {
456            crate::boundary::guarded("a table (number_of_rows)", 0, || {
457                self.data().map_or(0, |d| d.count() as NSInteger)
458            })
459        }
460
461        #[unsafe(method(tableView:sortDescriptorsDidChange:))]
462        fn sort_descriptors_did_change(&self, table: &NSTableView, _old: &NSArray<NSSortDescriptor>) {
463            crate::boundary::guarded("a table (sort_descriptors_did_change)", (), || {
464                let sort = table.sortDescriptors().firstObject().and_then(|d| {
465                    Some(Sort { column: d.key()?.to_string(), ascending: d.ascending() })
466                });
467                if let Some(data) = self.data() {
468                    data.sort_changed(sort);
469                }
470            })
471        }
472
473        #[unsafe(method_id(tableView:pasteboardWriterForRow:))]
474        fn writer_for_row(&self, table: &NSTableView, row: NSInteger) -> Option<Retained<ProtocolObject<dyn NSPasteboardWriting>>> {
475            crate::boundary::guarded("a table (writer_for_row)", None, || {
476                self.row_writer(table, row)
477            })
478        }
479
480        #[unsafe(method(tableView:validateDrop:proposedRow:proposedDropOperation:))]
481        fn validate_drop(
482            &self,
483            table: &NSTableView,
484            info: &ProtocolObject<dyn NSDraggingInfo>,
485            row: NSInteger,
486            _operation: NSTableViewDropOperation,
487        ) -> NSDragOperation {
488            crate::boundary::guarded("a table (validate_drop)", NSDragOperation::None, || {
489                let operation = match self.dropped(table, info) {
490                    Some(Dropped::Rows(_)) => NSDragOperation::Move,
491                    Some(Dropped::Files(_) | Dropped::Urls(_)) => NSDragOperation::Copy,
492                    None => return NSDragOperation::None,
493                };
494                // Between rows, never onto one.
495                table.setDropRow_dropOperation(row, NSTableViewDropOperation::Above);
496                operation
497            })
498        }
499
500        #[unsafe(method(tableView:acceptDrop:row:dropOperation:))]
501        fn accept_drop(
502            &self,
503            table: &NSTableView,
504            info: &ProtocolObject<dyn NSDraggingInfo>,
505            row: NSInteger,
506            _operation: NSTableViewDropOperation,
507        ) -> bool {
508            crate::boundary::guarded("a table (accept_drop)", false, || {
509                self.accept(table, info, row)
510            })
511        }
512    }
513
514    unsafe impl NSTableViewDelegate for Source {
515        #[unsafe(method_id(tableView:rowViewForRow:))]
516        fn row_view_for(&self, table: &NSTableView, _row: NSInteger) -> Option<Retained<NSTableRowView>> {
517            crate::boundary::guarded("a table (row_view_for)", None, || {
518                // With cell focus, rows that draw the focused cell; otherwise AppKit's own.
519                self.focus_row(table)
520            })
521        }
522
523        #[unsafe(method_id(tableView:viewForTableColumn:row:))]
524        fn view_for(&self, table: &NSTableView, column: Option<&NSTableColumn>, row: NSInteger) -> Option<Retained<NSView>> {
525            crate::boundary::guarded("a table (view_for)", None, || {
526                match column {
527                    Some(column) => self.cell_view(table, column, row),
528                    // A group row spans the table (no column).
529                    None => self.group_view(table, row),
530                }
531            })
532        }
533
534        #[unsafe(method(tableView:isGroupRow:))]
535        fn is_group_row(&self, _table: &NSTableView, row: NSInteger) -> bool {
536            crate::boundary::guarded("a table (is_group_row)", false, || {
537                self.data().is_some_and(|d| d.group_title(row as usize).is_some())
538            })
539        }
540
541        #[unsafe(method(tableView:shouldSelectRow:))]
542        fn should_select_row(&self, _table: &NSTableView, row: NSInteger) -> bool {
543            crate::boundary::guarded("a table (should_select_row)", false, || {
544                self.data().is_none_or(|d| d.group_title(row as usize).is_none())
545            })
546        }
547
548        #[unsafe(method(tableViewSelectionDidChange:))]
549        fn selection_did_change(&self, notification: &NSNotification) {
550            crate::boundary::guarded("a table (selection_did_change)", (), || {
551                let Some(data) = self.data() else { return };
552                if data.quiet() {
553                    return;
554                }
555                let Some(table) = notification.object().and_then(|o| o.downcast::<NSTableView>().ok()) else { return };
556                let rows = indexes(&table.selectedRowIndexes()).into_iter().filter_map(|r| data.model_row(r)).collect();
557                data.push(TableEvent::Selection(rows));
558            })
559        }
560
561        #[unsafe(method_id(tableView:typeSelectStringForTableColumn:row:))]
562        fn type_select_string(&self, _table: &NSTableView, column: Option<&NSTableColumn>, row: NSInteger) -> Option<Retained<NSString>> {
563            crate::boundary::guarded("a table (type_select_string)", None, || {
564                self.cell_text(column, row)
565            })
566        }
567
568        #[unsafe(method(tableViewColumnDidMove:))]
569        fn column_did_move(&self, _notification: &NSNotification) {
570            crate::boundary::guarded("a table (column_did_move)", (), || {
571                if let Some(data) = self.data() {
572                    data.push(TableEvent::ColumnsChanged);
573                }
574            })
575        }
576
577        #[unsafe(method(tableViewColumnDidResize:))]
578        fn column_did_resize(&self, _notification: &NSNotification) {
579            crate::boundary::guarded("a table (column_did_resize)", (), || {
580                if let Some(data) = self.data() {
581                    data.push(TableEvent::ColumnsChanged);
582                }
583            })
584        }
585    }
586
587    impl Source {
588        #[unsafe(method(activate:))]
589        fn activate(&self, sender: &NSTableView) {
590            crate::boundary::guarded("a table (activate)", (), || {
591                let Some(data) = self.data() else { return };
592                let row = sender.clickedRow();
593                if let Some(row) = (row >= 0).then_some(row as usize).and_then(|r| data.model_row(r)) {
594                    data.push(TableEvent::Activate(row));
595                }
596            })
597        }
598
599        #[unsafe(method(edit:))]
600        fn edit(&self, sender: &NSTextField) {
601            crate::boundary::guarded("a table (edit)", (), || {
602                let Some(data) = self.data() else { return };
603                let Some(table) = table_of(sender) else { return };
604                let row = table.rowForView(sender);
605                let Some(column) = sender.identifier().map(|i| i.to_string()) else { return };
606                let value = sender.stringValue().to_string();
607                // Editing ends with Return, Tab or the focus moving away; an
608                // edit cancelled with Escape (or left as it was) isn't one.
609                let shown = (row >= 0).then(|| data.cell(row as usize, &column)).flatten().map(|(kind, v)| display(&kind, &v));
610                if shown.as_deref() == Some(value.as_str()) {
611                    return;
612                }
613                if let Some(row) = (row >= 0).then_some(row as usize).and_then(|r| data.model_row(r)) {
614                    data.push(TableEvent::Edit { row, column, value });
615                }
616            })
617        }
618
619        #[unsafe(method(toggle:))]
620        fn toggle(&self, sender: &NSButton) {
621            crate::boundary::guarded("a table (toggle)", (), || {
622                let Some(data) = self.data() else { return };
623                let Some(table) = table_of(sender) else { return };
624                let row = table.rowForView(sender);
625                let Some(column) = sender.identifier().map(|i| i.to_string()) else { return };
626                if let Some(row) = (row >= 0).then_some(row as usize).and_then(|r| data.model_row(r)) {
627                    data.push(TableEvent::Toggle { row, column, value: sender.state() == NSControlStateValueOn });
628                }
629            })
630        }
631    }
632);
633
634/// A key a table can take without ⌘ (see [`TableModel::set_keys`]).
635#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
636#[non_exhaustive]
637pub enum TableKey {
638    /// Delete (⌫) or Forward Delete (⌦): remove the selected rows, say.
639    Delete,
640    /// Space: Quick Look the selected rows, say.
641    Space,
642}
643
644impl TableKey {
645    /// The key a key-down event is, if it's one of these without ⌘, ⌥ or ⌃.
646    fn of(event: &NSEvent) -> Option<TableKey> {
647        use objc2_app_kit::NSEventModifierFlags as F;
648        if event.modifierFlags().intersects(F::Command | F::Option | F::Control) {
649            return None;
650        }
651        // 51: Delete, 117: Forward Delete, 49: Space.
652        match event.keyCode() {
653            51 | 117 => Some(TableKey::Delete),
654            49 => Some(TableKey::Space),
655            _ => None,
656        }
657    }
658}
659
660/// What a drag carries that this table accepts.
661enum Dropped {
662    Rows(Vec<usize>),
663    Files(Vec<std::path::PathBuf>),
664    Urls(Vec<String>),
665}
666
667define_class!(
668    // NSTableView that also activates the selected row on Return / Enter, and
669    // copies and pastes rows.
670    #[unsafe(super(NSTableView, NSControl, NSView, NSResponder, NSObject))]
671    #[thread_kind = MainThreadOnly]
672    #[name = "FerrokitCoreTableView"]
673    struct HostTableView;
674
675    impl HostTableView {
676        #[unsafe(method(keyDown:))]
677        fn key_down(&self, event: &NSEvent) {
678            crate::boundary::guarded("a table (key_down)", (), || {
679                // 36: Return, 76: keypad Enter.
680                if matches!(event.keyCode(), 36 | 76) {
681                    let row = self.selectedRow();
682                    let source = unsafe { self.dataSource() };
683                    let source = source.and_then(|s| {
684                        let any: &AnyObject = s.as_ref();
685                        any.downcast_ref::<Source>().map(|s| s.retain())
686                    });
687                    if let (true, Some(source)) = (row >= 0, source) {
688                        if let Some(data) = source.data()
689                            && let Some(row) = data.model_row(row as usize)
690                        {
691                            data.push(TableEvent::Activate(row));
692                        }
693                        return;
694                    }
695                }
696                // ← and → move the focused column, with cell focus on.
697                if matches!(event.keyCode(), 123 | 124) && self.move_focus(event) {
698                    return;
699                }
700                // A bare key the app handles, with rows selected.
701                if let Some(key) = TableKey::of(event)
702                    && let Some(data) = self.source().and_then(|s| s.data())
703                    && data.transfer().keys.contains(&key)
704                {
705                    let rows: Vec<usize> = indexes(&self.selectedRowIndexes()).into_iter().filter_map(|r| data.model_row(r)).collect();
706                    if !rows.is_empty() {
707                        data.push(TableEvent::Key { key, rows });
708                        return;
709                    }
710                }
711                let () = unsafe { msg_send![super(self), keyDown: event] };
712            })
713        }
714
715        #[unsafe(method(mouseDown:))]
716        fn mouse_down(&self, event: &NSEvent) {
717            crate::boundary::guarded("a table (mouse_down)", (), || {
718                // With cell focus, a click focuses the clicked cell's column.
719                if let Some(data) = self.source().and_then(|s| s.data())
720                    && data.transfer().cell_focus
721                {
722                    let point = self.convertPoint_fromView(event.locationInWindow(), None);
723                    let column = self.columnAtPoint(point);
724                    if column >= 0 && self.rowAtPoint(point) >= 0 {
725                        let id = self.tableColumns().objectAtIndex(column as usize).identifier().to_string();
726                        data.set_focus(Some(id), true);
727                    }
728                }
729                let () = unsafe { msg_send![super(self), mouseDown: event] };
730            })
731        }
732
733        #[unsafe(method(copy:))]
734        fn copy(&self, _sender: Option<&AnyObject>) {
735            crate::boundary::guarded("a table (copy)", (), || {
736                self.copy_rows(&NSPasteboard::generalPasteboard());
737            })
738        }
739
740        #[unsafe(method(paste:))]
741        fn paste(&self, _sender: Option<&AnyObject>) {
742            crate::boundary::guarded("a table (paste)", (), || {
743                self.paste_text(&NSPasteboard::generalPasteboard());
744            })
745        }
746
747        #[unsafe(method(validateMenuItem:))]
748        fn validate_menu_item(&self, item: &NSMenuItem) -> bool {
749            crate::boundary::guarded("a table (validate_menu_item)", false, || {
750                let action = item.action();
751                if action == Some(sel!(copy:)) {
752                    self.selectedRow() >= 0
753                } else if action == Some(sel!(paste:)) {
754                    let pastes = self.source().and_then(|s| s.data()).is_some_and(|d| d.transfer().pastes);
755                    // SAFETY: AppKit's pasteboard type constant.
756                    pastes && NSPasteboard::generalPasteboard().stringForType(unsafe { NSPasteboardTypeString }).is_some()
757                } else {
758                    true
759                }
760            })
761        }
762    }
763);
764
765impl HostTableView {
766    /// Moves the focused column one to the left or right (← or →, no
767    /// modifier but Fn), scrolling it into view. Whether it was handled.
768    fn move_focus(&self, event: &NSEvent) -> bool {
769        use objc2_app_kit::NSEventModifierFlags as F;
770        let Some(data) = self.source().and_then(|s| s.data()) else { return false };
771        if !data.transfer().cell_focus || event.modifierFlags().intersects(F::Command | F::Option | F::Control | F::Shift) {
772            return false;
773        }
774        let ids = column_ids(self);
775        if ids.is_empty() {
776            return false;
777        }
778        let now = data.focus().and_then(|f| ids.iter().position(|i| *i == f));
779        let next = match (now, event.keyCode()) {
780            (None, _) => 0,
781            (Some(i), 123) => i.saturating_sub(1),
782            (Some(i), _) => (i + 1).min(ids.len() - 1),
783        };
784        self.scrollColumnToVisible(next as NSInteger);
785        data.set_focus(Some(ids[next].clone()), true);
786        true
787    }
788
789    fn source(&self) -> Option<Retained<Source>> {
790        let source = unsafe { self.dataSource() }?;
791        let any: &AnyObject = source.as_ref();
792        any.downcast_ref::<Source>().map(|s| s.retain())
793    }
794
795    /// Writes the selected rows to `pasteboard` as tab-separated text.
796    fn copy_rows(&self, pasteboard: &NSPasteboard) -> bool {
797        let Some(data) = self.source().and_then(|s| s.data()) else { return false };
798        let rows = indexes(&self.selectedRowIndexes());
799        if rows.is_empty() {
800            return false;
801        }
802        let text = NSString::from_str(&data.rows_text(&rows, &column_ids(self)));
803        pasteboard.clearContents();
804        // SAFETY: AppKit's pasteboard type constants.
805        unsafe {
806            pasteboard.setString_forType(&text, NSPasteboardTypeString);
807            pasteboard.setString_forType(&text, NSPasteboardTypeTabularText);
808        }
809        true
810    }
811
812    /// Reports `pasteboard`'s text as a paste, if the table takes pastes.
813    fn paste_text(&self, pasteboard: &NSPasteboard) -> bool {
814        let Some(data) = self.source().and_then(|s| s.data()) else { return false };
815        // SAFETY: AppKit's pasteboard type constant.
816        let text = pasteboard.stringForType(unsafe { NSPasteboardTypeString });
817        match (data.transfer().pastes, text) {
818            (true, Some(text)) => {
819                data.push(TableEvent::Paste(text.to_string()));
820                true
821            }
822            _ => false,
823        }
824    }
825}
826
827define_class!(
828    // A row that draws the focused cell over its selection (cell focus).
829    #[unsafe(super(NSTableRowView, NSView, NSResponder, NSObject))]
830    #[thread_kind = MainThreadOnly]
831    #[name = "FerrokitFocusRowView"]
832    struct FocusRowView;
833
834    impl FocusRowView {
835        #[unsafe(method(drawSelectionInRect:))]
836        fn draw_selection(&self, rect: NSRect) {
837            crate::boundary::guarded("a table (draw_selection)", (), || {
838                let () = unsafe { msg_send![super(self), drawSelectionInRect: rect] };
839                let Some(cell) = self.focus_rect() else { return };
840                let path = NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(cell, 4.0, 4.0);
841                path.setLineWidth(1.5);
842                if self.isEmphasized() {
843                    NSColor::whiteColor().colorWithAlphaComponent(0.18).setFill();
844                    path.fill();
845                    NSColor::whiteColor().setStroke();
846                } else {
847                    NSColor::controlAccentColor().setStroke();
848                }
849                path.stroke();
850            })
851        }
852    }
853);
854
855impl FocusRowView {
856    /// The focused cell's rectangle in this row, if a column is focused.
857    fn focus_rect(&self) -> Option<NSRect> {
858        // SAFETY: a row view's superview is its table (or nothing).
859        let table = unsafe { self.superview() }?.downcast::<HostTableView>().ok()?;
860        let focus = table.source()?.data()?.focus()?;
861        let column = table.columnWithIdentifier(&NSString::from_str(&focus));
862        if column < 0 {
863            return None;
864        }
865        let c = table.rectOfColumn(column);
866        let x = c.origin.x - self.frame().origin.x;
867        let h = self.bounds().size.height;
868        Some(NSRect::new(objc2_foundation::NSPoint::new(x + 1.5, 1.5), objc2_foundation::NSSize::new((c.size.width - 3.0).max(0.0), (h - 3.0).max(0.0))))
869    }
870}
871
872impl Source {
873    /// A focus row view for `table`, reused when one is free, if the table
874    /// has cell focus.
875    fn focus_row(&self, table: &NSTableView) -> Option<Retained<NSTableRowView>> {
876        if !self.data().is_some_and(|d| d.transfer().cell_focus) {
877            return None;
878        }
879        let id = NSString::from_str("FerrokitFocusRow");
880        // SAFETY: views under this identifier are focus rows made below.
881        let reused = unsafe { table.makeViewWithIdentifier_owner(&id, None) }.and_then(|v| v.downcast::<NSTableRowView>().ok());
882        Some(reused.unwrap_or_else(|| {
883            // SAFETY: plain NSTableRowView init.
884            let row: Retained<FocusRowView> = unsafe { msg_send![FocusRowView::alloc(mtm()), init] };
885            row.setIdentifier(Some(&id));
886            Retained::into_super(row)
887        }))
888    }
889}
890
891/// Redraws the selected rows' row views (the focused cell moved).
892fn redraw_selected_rows(table: &NSTableView) {
893    for row in indexes(&table.selectedRowIndexes()) {
894        if let Some(view) = table.rowViewAtRow_makeIfNecessary(row as NSInteger, false) {
895            view.setNeedsDisplay(true);
896        }
897    }
898}
899
900/// The table's column ids, in their current (user-arranged) order.
901fn column_ids(table: &NSTableView) -> Vec<String> {
902    table.tableColumns().iter().map(|c| c.identifier().to_string()).collect()
903}
904
905use objc2::Message as _;
906
907fn table_of(view: &NSView) -> Option<Retained<NSTableView>> {
908    // SAFETY: walking up a live view hierarchy on the main thread.
909    let mut current = unsafe { view.superview() };
910    while let Some(v) = current {
911        if let Ok(table) = v.clone().downcast::<NSTableView>() {
912            return Some(table);
913        }
914        current = unsafe { v.superview() };
915    }
916    None
917}
918
919/// Gives the keyboard back to a table whose rows changed under a cell
920/// edit. AppKit ends the edit when the cell's row is reloaded (what was
921/// typed isn't an edit: its row may be another one now) and leaves the
922/// window with no first responder, so the arrow keys would do nothing.
923struct KeepFocus {
924    table: Retained<NSTableView>,
925    editing: bool,
926}
927
928impl KeepFocus {
929    fn new(table: &NSTableView) -> Self {
930        let editing = table.window().and_then(|w| w.firstResponder()).and_then(|r| r.downcast::<objc2_app_kit::NSText>().ok()).is_some_and(|editor| {
931            // SAFETY: a field editor's delegate is the control it edits for.
932            let field: Option<Retained<objc2::runtime::AnyObject>> = unsafe { objc2::msg_send![&*editor, delegate] };
933            field.and_then(|f| f.downcast::<NSView>().ok()).is_some_and(|f| f.isDescendantOf(table))
934        });
935        KeepFocus { table: table.retain(), editing }
936    }
937}
938
939impl Drop for KeepFocus {
940    fn drop(&mut self) {
941        if !self.editing {
942            return;
943        }
944        if let Some(window) = self.table.window() {
945            let lost = window.firstResponder().is_none_or(|r| std::ptr::eq(Retained::as_ptr(&r).cast::<u8>(), Retained::as_ptr(&window).cast::<u8>()));
946            if lost {
947                window.makeFirstResponder(Some(&self.table));
948            }
949        }
950    }
951}
952
953fn indexes(set: &NSIndexSet) -> Vec<usize> {
954    let mut out = Vec::with_capacity(set.count());
955    let mut i = set.firstIndex();
956    while i != usize::MAX && out.len() < set.count() {
957        out.push(i);
958        i = set.indexGreaterThanIndex(i);
959    }
960    out
961}
962
963impl Source {
964    fn cell_text(&self, column: Option<&NSTableColumn>, row: NSInteger) -> Option<Retained<NSString>> {
965        let (kind, value) = self.data()?.cell(row as usize, &column?.identifier().to_string())?;
966        Some(NSString::from_str(&display(&kind, &value)))
967    }
968
969    fn data(&self) -> Option<Rc<dyn Data>> {
970        self.ivars().data.borrow().as_ref().and_then(Weak::upgrade)
971    }
972
973    fn row_writer(&self, table: &NSTableView, row: NSInteger) -> Option<Retained<ProtocolObject<dyn NSPasteboardWriting>>> {
974        let data = self.data()?;
975        if !data.transfer().drag {
976            return None;
977        }
978        let model = data.model_row(usize::try_from(row).ok()?)?;
979        let item = NSPasteboardItem::new();
980        item.setString_forType(&NSString::from_str(&model.to_string()), &row_type());
981        let text = data.rows_text(&[row as usize], &column_ids(table));
982        // SAFETY: AppKit's pasteboard type constant.
983        item.setString_forType(&NSString::from_str(&text), unsafe { NSPasteboardTypeString });
984        Some(ProtocolObject::from_retained(item))
985    }
986
987    fn accept(&self, table: &NSTableView, info: &ProtocolObject<dyn NSDraggingInfo>, row: NSInteger) -> bool {
988        let Some(data) = self.data() else { return false };
989        let before = usize::try_from(row).ok().and_then(|r| data.model_row(r));
990        match self.dropped(table, info) {
991            Some(Dropped::Rows(rows)) => data.push(TableEvent::RowsMoved { rows, before }),
992            Some(Dropped::Files(paths)) => data.push(TableEvent::FilesDropped { paths, before }),
993            Some(Dropped::Urls(urls)) => data.push(TableEvent::UrlsDropped { urls, before }),
994            None => return false,
995        }
996        true
997    }
998
999    /// What a drag over `table` carries that the table takes: its own rows
1000    /// (when reorderable and unsorted), or files (when it takes them).
1001    fn dropped(&self, table: &NSTableView, info: &ProtocolObject<dyn NSDraggingInfo>) -> Option<Dropped> {
1002        let data = self.data()?;
1003        let transfer = data.transfer();
1004        let items = info.draggingPasteboard().pasteboardItems()?;
1005        let own = info.draggingSource().is_some_and(|s| std::ptr::eq(&*s as *const AnyObject, table as *const NSTableView as *const AnyObject));
1006        if own {
1007            // Reordering a sorted table has no meaning: the sort decides.
1008            if !transfer.reorder || data.sorted() {
1009                return None;
1010            }
1011            let rows: Vec<usize> = items.iter().filter_map(|i| i.stringForType(&row_type())?.to_string().parse().ok()).collect();
1012            return (!rows.is_empty()).then_some(Dropped::Rows(rows));
1013        }
1014        // Web addresses (a link or the address bar dragged from a browser),
1015        // not files: those go to the file drop.
1016        let urls: Vec<String> = items
1017            .iter()
1018            .filter(|i| i.stringForType(unsafe { NSPasteboardTypeFileURL }).is_none())
1019            // SAFETY: AppKit's pasteboard type constant.
1020            .filter_map(|i| i.stringForType(unsafe { NSPasteboardTypeURL }).map(|u| u.to_string()))
1021            .collect();
1022        if transfer.urls && !urls.is_empty() {
1023            return Some(Dropped::Urls(urls));
1024        }
1025        let extensions = transfer.files?;
1026        let paths: Vec<std::path::PathBuf> = items
1027            .iter()
1028            // SAFETY: AppKit's pasteboard type constant.
1029            .filter_map(|i| i.stringForType(unsafe { NSPasteboardTypeFileURL }))
1030            .filter_map(|u| NSURL::URLWithString(&u)?.path().map(|p| std::path::PathBuf::from(p.to_string())))
1031            .collect();
1032        let accepted = |p: &std::path::PathBuf| {
1033            extensions.is_empty()
1034                || p.extension().and_then(|e| e.to_str()).is_some_and(|e| extensions.iter().any(|x| x.eq_ignore_ascii_case(e)))
1035        };
1036        (!paths.is_empty() && paths.iter().all(accepted)).then_some(Dropped::Files(paths))
1037    }
1038
1039    /// A group header: its title, in the table's group-row style.
1040    fn group_view(&self, table: &NSTableView, row: NSInteger) -> Option<Retained<NSView>> {
1041        let title = self.data()?.group_title(row as usize)?;
1042        let ident = NSString::from_str("ferrokit-core.group");
1043        // SAFETY: reuse lookup by identifier; owner may be nil.
1044        let field = match unsafe { table.makeViewWithIdentifier_owner(&ident, None) }.and_then(|v| v.downcast::<NSTextField>().ok()) {
1045            Some(f) => f,
1046            None => {
1047                let f = NSTextField::labelWithString(&NSString::new(), MainThreadMarker::from(self));
1048                f.setIdentifier(Some(&ident));
1049                f.setFont(Some(&objc2_app_kit::NSFont::boldSystemFontOfSize(objc2_app_kit::NSFont::smallSystemFontSize())));
1050                f.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
1051                f
1052            }
1053        };
1054        field.setStringValue(&NSString::from_str(&title));
1055        Some(Retained::into_super(Retained::into_super(field)))
1056    }
1057
1058    fn progress_view(&self, table: &NSTableView, ident: &NSString, value: f64) -> Retained<NSView> {
1059        use objc2_app_kit::{NSProgressIndicator, NSProgressIndicatorStyle, NSTableCellView};
1060        let mtm = MainThreadMarker::from(self);
1061        // SAFETY: reuse lookup by identifier; owner may be nil.
1062        let cell = match unsafe { table.makeViewWithIdentifier_owner(ident, None) }.and_then(|v| v.downcast::<NSTableCellView>().ok()) {
1063            Some(c) => c,
1064            None => {
1065                self.ivars().created.set(self.ivars().created.get() + 1);
1066                // Sized to hold the bar, which resizes with it (as icon cells).
1067                let c = NSTableCellView::initWithFrame(NSTableCellView::alloc(mtm), objc2_foundation::NSRect::new(objc2_foundation::NSPoint::new(0.0, 0.0), objc2_foundation::NSSize::new(100.0, 17.0)));
1068                c.setIdentifier(Some(ident));
1069                let bar = NSProgressIndicator::new(mtm);
1070                bar.setStyle(NSProgressIndicatorStyle::Bar);
1071                bar.setIndeterminate(false);
1072                bar.setMinValue(0.0);
1073                bar.setMaxValue(1.0);
1074                bar.setControlSize(objc2_app_kit::NSControlSize::Small);
1075                bar.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable | objc2_app_kit::NSAutoresizingMaskOptions::ViewMinYMargin | objc2_app_kit::NSAutoresizingMaskOptions::ViewMaxYMargin);
1076                bar.setFrame(objc2_foundation::NSRect::new(objc2_foundation::NSPoint::new(2.0, 2.0), objc2_foundation::NSSize::new(96.0, 12.0)));
1077                c.addSubview(&bar);
1078                if let Some(title) = self.data().and_then(|d| d.title(&ident.to_string())) {
1079                    // SAFETY: NSAccessibility's label setter.
1080                    let () = unsafe { msg_send![&*bar, setAccessibilityLabel: &*NSString::from_str(&title)] };
1081                }
1082                c
1083            }
1084        };
1085        if let Some(bar) = cell.subviews().iter().find_map(|v| v.downcast::<objc2_app_kit::NSProgressIndicator>().ok()) {
1086            bar.setDoubleValue(value);
1087        }
1088        Retained::into_super(cell)
1089    }
1090
1091    fn cell_view(&self, table: &NSTableView, column: &NSTableColumn, row: NSInteger) -> Option<Retained<NSView>> {
1092        let ident = column.identifier();
1093        let (kind, value) = self.data()?.cell(row as usize, &ident.to_string())?;
1094        let mtm = MainThreadMarker::from(self);
1095        if kind == Kind::Progress {
1096            let v = if let Value::Number(n) = value { n } else { 0.0 };
1097            return Some(self.progress_view(table, &ident, v));
1098        }
1099        if self.data().is_some_and(|d| d.has_icon(&ident.to_string())) {
1100            return Some(self.icon_view(table, &ident, kind, &value, row));
1101        }
1102        // SAFETY: reuse lookup by identifier; owner may be nil.
1103        let reused = unsafe { table.makeViewWithIdentifier_owner(&ident, None) };
1104        if kind == Kind::Check {
1105            let button = match reused.and_then(|v| v.downcast::<NSButton>().ok()) {
1106                Some(b) => b,
1107                None => {
1108                    self.ivars().created.set(self.ivars().created.get() + 1);
1109                    // SAFETY: target is this source, which outlives the table's cells.
1110                    let b = unsafe { NSButton::checkboxWithTitle_target_action(&NSString::new(), Some(self), Some(sel!(toggle:)), mtm) };
1111                    b.setIdentifier(Some(&ident));
1112                    // An untitled checkbox reads as just "checkbox": title it after
1113                    // its column and show only the box.
1114                    if let Some(title) = self.data().and_then(|d| d.title(&ident.to_string())) {
1115                        let title = NSString::from_str(&title);
1116                        b.setTitle(&title);
1117                        b.setImagePosition(objc2_app_kit::NSCellImagePosition::ImageOnly);
1118                        // Image-only buttons report an empty AX title; label
1119                        // the button and its cell (which serves accessibility).
1120                        // SAFETY: NSAccessibility setters taking a string.
1121                        unsafe {
1122                            let () = msg_send![&*b, setAccessibilityLabel: &*title];
1123                            let cell: Option<Retained<AnyObject>> = msg_send![&*b, cell];
1124                            if let Some(cell) = cell {
1125                                let () = msg_send![&*cell, setAccessibilityLabel: &*title];
1126                            }
1127                        }
1128                    }
1129                    b
1130                }
1131            };
1132            button.setState(if value == Value::Bool(true) { NSControlStateValueOn } else { NSControlStateValueOff });
1133            return Some(Retained::into_super(Retained::into_super(button)));
1134        }
1135        let field = match reused.and_then(|v| v.downcast::<NSTextField>().ok()) {
1136            Some(f) => f,
1137            None => {
1138                self.ivars().created.set(self.ivars().created.get() + 1);
1139                let f = NSTextField::labelWithString(&NSString::new(), mtm);
1140                f.setIdentifier(Some(&ident));
1141                f.setLineBreakMode(NSLineBreakMode::ByTruncatingTail);
1142                if self.data().is_some_and(|d| d.editable(&ident.to_string())) {
1143                    // A borderless editable label: NSTableView starts editing
1144                    // on double-click (or a click on the selected row), and
1145                    // the action fires when editing ends: with Return, and
1146                    // also with Tab or a click elsewhere (a label sends it
1147                    // only on Return otherwise, and the edit was lost).
1148                    f.setEditable(true);
1149                    f.setSelectable(true);
1150                    if let Some(cell) = f.cell() {
1151                        cell.setSendsActionOnEndEditing(true);
1152                    }
1153                    // SAFETY: target is this source, which outlives the table's cells.
1154                    unsafe {
1155                        f.setTarget(Some(self));
1156                        f.setAction(Some(sel!(edit:)));
1157                    }
1158                    // A field VoiceOver can name while it's empty: its
1159                    // cell reads as its column's title ("Default").
1160                    let title = column.title();
1161                    let () = unsafe { msg_send![&*f, setAccessibilityLabel: &*title] };
1162                }
1163                f
1164            }
1165        };
1166        // Set on reuse too: a column's kind can change (`set_columns`).
1167        field.setAlignment(if let Kind::Number { .. } = kind { NSTextAlignment::Right } else { NSTextAlignment::Natural });
1168        let style = self.data().and_then(|d| d.style(row as usize, &ident.to_string()));
1169        Self::show_text(&field, &display(&kind, &value), style.as_ref());
1170        Some(Retained::into_super(Retained::into_super(field)))
1171    }
1172
1173    /// Sets a cell's text in its style, or the table's plain look (every field
1174/// is set each time: cells are reused across rows).
1175fn show_text(field: &NSTextField, text: &str, style: Option<&CellStyle>) {
1176    use objc2_app_kit::{NSColor, NSFont, NSFontManager, NSFontTraitMask};
1177    let size = NSFont::systemFontSize();
1178    let font = match style {
1179        Some(s) if s.italic => NSFontManager::sharedFontManager(MainThreadMarker::from(field)).convertFont_toHaveTrait(&NSFont::systemFontOfSize(size), NSFontTraitMask::ItalicFontMask),
1180        _ => NSFont::systemFontOfSize(size),
1181    };
1182    let color = style.and_then(|s| s.color).map_or_else(NSColor::labelColor, |c| c.ns());
1183    field.setFont(Some(&font));
1184    field.setTextColor(Some(&color));
1185    match style.and_then(|s| s.background) {
1186        Some(bg) => {
1187            field.setDrawsBackground(true);
1188            field.setBackgroundColor(Some(&bg.ns()));
1189        }
1190        None => field.setDrawsBackground(false),
1191    }
1192    if style.is_some_and(|s| s.strikethrough) {
1193        use objc2_app_kit::{NSFontAttributeName, NSForegroundColorAttributeName, NSStrikethroughStyleAttributeName};
1194        use objc2_foundation::{NSAttributedString, NSDictionary, NSNumber};
1195        let one = NSNumber::new_isize(1);
1196        // SAFETY: AppKit's attribute names, with values of their types.
1197        let attrs = unsafe {
1198            NSDictionary::<NSString, objc2::runtime::AnyObject>::from_slices(
1199                &[NSStrikethroughStyleAttributeName, NSForegroundColorAttributeName, NSFontAttributeName],
1200                &[&*one as &objc2::runtime::AnyObject, &*color as &objc2::runtime::AnyObject, &*font as &objc2::runtime::AnyObject],
1201            )
1202        };
1203        // SAFETY: the dictionary holds attributes as NSAttributedString takes them.
1204        let text = unsafe { NSAttributedString::new_with_attributes(&NSString::from_str(text), &attrs) };
1205        field.setAttributedStringValue(&text);
1206    } else {
1207        field.setStringValue(&NSString::from_str(text));
1208    }
1209}
1210
1211/// A cell with an image before its text (an icon column).
1212    fn icon_view(&self, table: &NSTableView, ident: &NSString, kind: Kind, value: &Value, row: NSInteger) -> Retained<NSView> {
1213        use objc2_app_kit::{NSImageView, NSTableCellView};
1214        let mtm = MainThreadMarker::from(self);
1215        // SAFETY: reuse lookup by identifier; owner may be nil.
1216        let cell = match unsafe { table.makeViewWithIdentifier_owner(ident, None) }.and_then(|v| v.downcast::<NSTableCellView>().ok()) {
1217            Some(c) => c,
1218            None => {
1219                self.ivars().created.set(self.ivars().created.get() + 1);
1220                // Sized to hold its subviews: they resize with it from
1221                // here (from a zero frame, the text would grow a column's
1222                // width past the cell, and right-aligned numbers with it).
1223                let c = NSTableCellView::initWithFrame(NSTableCellView::alloc(mtm), objc2_foundation::NSRect::new(objc2_foundation::NSPoint::new(0.0, 0.0), objc2_foundation::NSSize::new(124.0, 17.0)));
1224                c.setIdentifier(Some(ident));
1225                let image = NSImageView::new(mtm);
1226                // Image and text keep to the top, where plain cells draw their
1227                // text: a row's text shares one baseline, icon or not.
1228                image.setFrame(objc2_foundation::NSRect::new(objc2_foundation::NSPoint::new(2.0, 0.5), objc2_foundation::NSSize::new(16.0, 16.0)));
1229                image.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewMinYMargin);
1230                // The icon is decoration: the text names the row. (macOS 15
1231                // and 26 otherwise read an unnamed image in every row.) The
1232                // view's cell answers for it there, so hide both.
1233                // SAFETY: NSAccessibility's setter taking a BOOL.
1234                unsafe {
1235                    let () = msg_send![&*image, setAccessibilityElement: false];
1236                    if let Some(cell) = image.cell() {
1237                        let () = msg_send![&*cell, setAccessibilityElement: false];
1238                    }
1239                }
1240                let text = NSTextField::labelWithString(&NSString::new(), mtm);
1241                text.setLineBreakMode(NSLineBreakMode::ByTruncatingTail);
1242                text.setFrame(objc2_foundation::NSRect::new(objc2_foundation::NSPoint::new(22.0, 0.0), objc2_foundation::NSSize::new(100.0, 17.0)));
1243                text.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable | objc2_app_kit::NSAutoresizingMaskOptions::ViewMinYMargin);
1244                if let Kind::Number { .. } = kind {
1245                    text.setAlignment(NSTextAlignment::Right);
1246                }
1247                c.addSubview(&image);
1248                c.addSubview(&text);
1249                // SAFETY: weak outlets; both views are the cell's subviews,
1250                // which keeps them alive.
1251                unsafe {
1252                    c.setImageView(Some(&image));
1253                    c.setTextField(Some(&text));
1254                }
1255                c
1256            }
1257        };
1258        let image = self.data().and_then(|d| d.icon(row as usize, &ident.to_string())).and_then(|i| match i {
1259            CellImage::Symbol(name) => objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(&NSString::from_str(&name), None),
1260            CellImage::FileIcon(path) => Some(objc2_app_kit::NSWorkspace::sharedWorkspace().iconForFile(&NSString::from_str(&path.to_string_lossy()))),
1261        });
1262        // SAFETY: the outlets set above (subviews of the cell).
1263        if let Some(iv) = unsafe { cell.imageView() } {
1264            iv.setImage(image.as_deref());
1265        }
1266        // SAFETY: as above.
1267        if let Some(tf) = unsafe { cell.textField() } {
1268            let style = self.data().and_then(|d| d.style(row as usize, &ident.to_string()));
1269            Self::show_text(&tf, &display(&kind, value), style.as_ref());
1270        }
1271        Retained::into_super(cell)
1272    }
1273}
1274
1275struct Inner<T: 'static> {
1276    id: ViewId,
1277    columns: RefCell<Vec<Column<T>>>,
1278    rows: RefCell<Vec<T>>,
1279    /// View position → model index (identity when unsorted); a group
1280    /// header's slot is `HEADER | group`.
1281    order: RefCell<Vec<usize>>,
1282    /// Groups' titles (see `set_group_by`).
1283    groups: RefCell<Vec<String>>,
1284    group_by: RefCell<Option<GroupKey<T>>>,
1285    sort: RefCell<Option<Sort>>,
1286    sorts_in_place: Cell<bool>,
1287    /// `insert` and `remove` animate the row in and out (see `set_animates`).
1288    animates: Cell<bool>,
1289    events: RefCell<VecDeque<TableEvent>>,
1290    /// Set while the model changes the selection itself (no event).
1291    quiet: Cell<bool>,
1292    mounted: Cell<bool>,
1293    transfer: RefCell<Transfer>,
1294    /// The focused column's id (cell focus).
1295    focus: RefCell<Option<String>>,
1296    scroll: Retained<NSScrollView>,
1297    table: Retained<HostTableView>,
1298    _source: Retained<Source>,
1299}
1300
1301impl<T: 'static> Data for Inner<T> {
1302    fn count(&self) -> usize {
1303        self.order.borrow().len()
1304    }
1305
1306    fn cell(&self, view_row: usize, column: &str) -> Option<(Kind, Value)> {
1307        let columns = self.columns.borrow();
1308        let column = columns.iter().find(|c| c.id == column)?;
1309        let index = self.model_row(view_row)?;
1310        let rows = self.rows.borrow();
1311        Some((column.kind.clone(), (column.value)(rows.get(index)?)))
1312    }
1313
1314    fn model_row(&self, view_row: usize) -> Option<usize> {
1315        self.order.borrow().get(view_row).copied().filter(|m| m & HEADER == 0)
1316    }
1317
1318    fn group_title(&self, view_row: usize) -> Option<String> {
1319        let slot = *self.order.borrow().get(view_row)?;
1320        (slot & HEADER != 0).then(|| self.groups.borrow().get(slot & !HEADER).cloned()).flatten()
1321    }
1322
1323    fn icon(&self, view_row: usize, column: &str) -> Option<CellImage> {
1324        let columns = self.columns.borrow();
1325        let column = columns.iter().find(|c| c.id == column)?;
1326        let index = self.model_row(view_row)?;
1327        let rows = self.rows.borrow();
1328        column.icon.as_ref().and_then(|f| f(rows.get(index)?))
1329    }
1330
1331    fn has_icon(&self, column: &str) -> bool {
1332        self.columns.borrow().iter().any(|c| c.id == column && c.icon.is_some())
1333    }
1334
1335    fn style(&self, view_row: usize, column: &str) -> Option<CellStyle> {
1336        let columns = self.columns.borrow();
1337        let column = columns.iter().find(|c| c.id == column)?;
1338        let index = self.model_row(view_row)?;
1339        let rows = self.rows.borrow();
1340        column.style.as_ref().map(|f| f(&rows[index]))
1341    }
1342
1343    fn editable(&self, column: &str) -> bool {
1344        self.columns.borrow().iter().any(|c| c.id == column && c.editable && c.kind != Kind::Check && !matches!(c.kind, Kind::Date { .. }))
1345    }
1346
1347    fn title(&self, column: &str) -> Option<String> {
1348        self.columns.borrow().iter().find(|c| c.id == column).map(|c| c.title.clone())
1349    }
1350
1351    fn sort_changed(&self, sort: Option<Sort>) {
1352        *self.sort.borrow_mut() = sort.clone();
1353        if self.sorts_in_place.get() {
1354            self.resort_keeping_selection();
1355        }
1356        if let Some(sort) = sort {
1357            self.push(TableEvent::Sort(sort));
1358        }
1359    }
1360
1361    fn push(&self, event: TableEvent) {
1362        let mut events = self.events.borrow_mut();
1363        // Column resizes arrive continuously while dragging: keep one.
1364        if event == TableEvent::ColumnsChanged && events.back() == Some(&TableEvent::ColumnsChanged) {
1365            return;
1366        }
1367        events.push_back(event);
1368        drop(events);
1369        crate::request_redraw();
1370    }
1371
1372    fn quiet(&self) -> bool {
1373        self.quiet.get()
1374    }
1375
1376    fn transfer(&self) -> Transfer {
1377        self.transfer.borrow().clone()
1378    }
1379
1380    fn focus(&self) -> Option<String> {
1381        self.focus.borrow().clone()
1382    }
1383
1384    fn set_focus(&self, column: Option<String>, report: bool) {
1385        if *self.focus.borrow() == column {
1386            return;
1387        }
1388        *self.focus.borrow_mut() = column.clone();
1389        redraw_selected_rows(&self.table);
1390        if report {
1391            self.push(TableEvent::FocusedColumn(column));
1392        }
1393    }
1394
1395    fn sorted(&self) -> bool {
1396        self.sort.borrow().is_some()
1397    }
1398
1399    fn rows_text(&self, view_rows: &[usize], columns: &[String]) -> String {
1400        let all = self.columns.borrow();
1401        let columns: Vec<&Column<T>> = columns.iter().filter_map(|id| all.iter().find(|c| &c.id == id)).collect();
1402        let order = self.order.borrow();
1403        let rows = self.rows.borrow();
1404        let clean = |s: String| s.replace(['\t', '\n', '\r'], " ");
1405        view_rows
1406            .iter()
1407            .filter_map(|&r| rows.get(*order.get(r)?))
1408            .map(|row| columns.iter().map(|c| clean(display(&c.kind, &(c.value)(row)))).collect::<Vec<_>>().join("\t"))
1409            .collect::<Vec<_>>()
1410            .join("\n")
1411    }
1412}
1413
1414impl<T: 'static> Inner<T> {
1415    /// Recomputes `order` from the current sort. Keys are computed once per
1416    /// row (not per comparison) and the sort is stable.
1417    fn compute_order(&self) {
1418        let rows = self.rows.borrow();
1419        let mut order: Vec<usize> = (0..rows.len()).collect();
1420        // Sorted here only with built-in sorting on: otherwise the rows
1421        // come in the app's own order (a database's), and the sort is kept
1422        // for the header's arrow.
1423        let sort = self.sort.borrow().clone().filter(|_| self.sorts_in_place.get());
1424        let columns = self.columns.borrow();
1425        if let Some(column) = sort.as_ref().and_then(|s| columns.iter().find(|c| c.id == s.column)) {
1426            // One key per row, built once: text becomes a natural-order key
1427            // compared bytewise (comparing with case folding on every
1428            // comparison took 160 ms for 100k rows).
1429            enum Key {
1430                Number(f64),
1431                Text(String),
1432            }
1433            let keys: Vec<Key> = rows
1434                .iter()
1435                .map(|r| match (column.value)(r) {
1436                    Value::Number(n) => Key::Number(n),
1437                    Value::Bool(b) => Key::Number(b as u8 as f64),
1438                    Value::Text(t) => Key::Text(natural_key(&t)),
1439                })
1440                .collect();
1441            order.sort_by(|a, b| match (&keys[*a], &keys[*b]) {
1442                (Key::Number(x), Key::Number(y)) => x.total_cmp(y),
1443                (Key::Text(x), Key::Text(y)) => x.cmp(y),
1444                (Key::Number(_), Key::Text(_)) => std::cmp::Ordering::Less,
1445                (Key::Text(_), Key::Number(_)) => std::cmp::Ordering::Greater,
1446            });
1447            if sort.is_some_and(|s| !s.ascending) {
1448                order.reverse();
1449            }
1450        }
1451        // Groups: rows gathered by key (groups in order of first appearance
1452        // in the model, rows in the sort's order within each), each run
1453        // after a header slot.
1454        let mut groups = Vec::new();
1455        if let Some(key) = self.group_by.borrow().as_ref() {
1456            let keys: Vec<String> = rows.iter().map(key).collect();
1457            let mut index_of: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
1458            for k in &keys {
1459                if !index_of.contains_key(k.as_str()) {
1460                    index_of.insert(k, groups.len());
1461                    groups.push(k.clone());
1462                }
1463            }
1464            let mut buckets: Vec<Vec<usize>> = vec![Vec::new(); groups.len()];
1465            for &m in &order {
1466                buckets[index_of[keys[m].as_str()]].push(m);
1467            }
1468            order = buckets.into_iter().enumerate().flat_map(|(g, rows)| std::iter::once(HEADER | g).chain(rows)).collect();
1469        }
1470        drop(rows);
1471        *self.groups.borrow_mut() = groups;
1472        *self.order.borrow_mut() = order;
1473        self.fit_columns();
1474    }
1475
1476    /// Sizes `fit` columns to their widest content: the title and, with many
1477    /// rows, the 64 longest values by character count (all of them below
1478    /// 2,000 rows), measured in the table's font.
1479    fn fit_columns(&self) {
1480        let rows = self.rows.borrow();
1481        for column in self.columns.borrow().iter().filter(|c| c.fit) {
1482            let Some(native) = self.table.tableColumnWithIdentifier(&NSString::from_str(&column.id)) else { continue };
1483            let mut texts: Vec<String> = rows.iter().map(|r| display(&column.kind, &(column.value)(r))).collect();
1484            if texts.len() > 2_000 {
1485                texts.sort_by_key(|t| std::cmp::Reverse(t.chars().count()));
1486                texts.truncate(64);
1487            }
1488            let font = objc2_app_kit::NSFont::systemFontOfSize(objc2_app_kit::NSFont::systemFontSize());
1489            let attrs = objc2_foundation::NSDictionary::from_retained_objects(
1490                // SAFETY: AppKit's font attribute key.
1491                &[unsafe { objc2_app_kit::NSFontAttributeName }],
1492                &[Retained::into_super(Retained::into_super(font)) as Retained<AnyObject>],
1493            );
1494            // SAFETY: measuring a string with font attributes.
1495            let width = |s: &str| unsafe { objc2_app_kit::NSStringDrawing::sizeWithAttributes(&*NSString::from_str(s), Some(&attrs)).width };
1496            let widest = texts.iter().map(|t| width(t)).fold(width(&column.title) + 16.0, f64::max);
1497            let icon = if column.icon.is_some() { 22.0 } else { 0.0 };
1498            native.setWidth((widest + icon + 12.0).ceil().max(column.min_width));
1499        }
1500    }
1501
1502    fn selection_model_rows(&self) -> Vec<usize> {
1503        let order = self.order.borrow();
1504        indexes(&self.table.selectedRowIndexes()).into_iter().filter_map(|r| order.get(r).copied()).filter(|m| m & HEADER == 0).collect()
1505    }
1506
1507    fn select_model_rows(&self, rows: &[usize]) {
1508        let order = self.order.borrow();
1509        let mut position = vec![usize::MAX; self.rows.borrow().len()];
1510        for (view, &model) in order.iter().enumerate() {
1511            if model & HEADER == 0 {
1512                position[model] = view;
1513            }
1514        }
1515        drop(order);
1516        let set = NSMutableIndexSet::new();
1517        for &r in rows {
1518            if let Some(&p) = position.get(r).filter(|p| **p != usize::MAX) {
1519                set.addIndex(p);
1520            }
1521        }
1522        self.quiet.set(true);
1523        self.table.selectRowIndexes_byExtendingSelection(&set, false);
1524        self.quiet.set(false);
1525    }
1526
1527    /// Where model row `index` is shown, when changes to it animate (on,
1528    /// in a window, not grouped: a group's header would move too).
1529    fn animated_position(&self, index: usize) -> Option<usize> {
1530        if !self.animates.get() || self.group_by.borrow().is_some() || self.table.window().is_none() {
1531            return None;
1532        }
1533        self.order.borrow().iter().position(|&m| m == index)
1534    }
1535
1536    fn resort_keeping_selection(&self) {
1537        let _focus = KeepFocus::new(&self.table);
1538        let selected = self.selection_model_rows();
1539        self.compute_order();
1540        self.table.reloadData();
1541        self.select_model_rows(&selected);
1542    }
1543}
1544
1545impl<T: 'static> Drop for Inner<T> {
1546    fn drop(&mut self) {
1547        // AppKit holds these weakly: detach them before the source goes, in
1548        // case the table outlives the model (e.g. in an autorelease pool).
1549        // SAFETY: clearing to nil is always valid.
1550        unsafe {
1551            self.table.setDataSource(None);
1552            self.table.setDelegate(None);
1553            self.table.setTarget(None);
1554            self.table.setDoubleAction(None);
1555        }
1556        if self.mounted.get() {
1557            crate::unmount(self.id);
1558        }
1559        crate::testing::LIVE_MODELS.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
1560    }
1561}
1562
1563impl Drop for SourceIvars {
1564    fn drop(&mut self) {
1565        crate::testing::LIVE_OBJC.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
1566    }
1567}
1568
1569/// A sort key giving natural order under plain byte comparison:
1570/// case-insensitive, digit runs compared as numbers ("Item 9" < "Item 10"),
1571/// like the Finder. Digit runs become their length (as a char) then the
1572/// digits without leading zeros, so longer numbers sort later.
1573fn natural_key(s: &str) -> String {
1574    let mut key = String::with_capacity(s.len() + 4);
1575    let mut chars = s.chars().peekable();
1576    while let Some(c) = chars.next() {
1577        if c.is_ascii_digit() {
1578            let mut digits = String::from(c);
1579            while let Some(d) = chars.peek().filter(|d| d.is_ascii_digit()) {
1580                digits.push(*d);
1581                chars.next();
1582            }
1583            let trimmed = digits.trim_start_matches('0');
1584            // \u{1} sorts before any printable character.
1585            key.push('\u{1}');
1586            key.push(char::from_u32(0x30 + trimmed.len() as u32).unwrap_or('~'));
1587            key.push_str(trimmed);
1588        } else {
1589            key.extend(c.to_lowercase());
1590        }
1591    }
1592    key
1593}
1594
1595/// Natural order for text (reference implementation for the key's tests).
1596#[cfg(test)]
1597fn natural_cmp(a: &str, b: &str) -> std::cmp::Ordering {
1598    use std::cmp::Ordering;
1599    let (mut a, mut b) = (a.chars().peekable(), b.chars().peekable());
1600    loop {
1601        match (a.peek(), b.peek()) {
1602            (None, None) => return Ordering::Equal,
1603            (None, _) => return Ordering::Less,
1604            (_, None) => return Ordering::Greater,
1605            (Some(x), Some(y)) if x.is_ascii_digit() && y.is_ascii_digit() => {
1606                let take = |it: &mut std::iter::Peekable<std::str::Chars>| {
1607                    let mut n = String::new();
1608                    while let Some(c) = it.peek().filter(|c| c.is_ascii_digit()) {
1609                        n.push(*c);
1610                        it.next();
1611                    }
1612                    n
1613                };
1614                let (x, y) = (take(&mut a), take(&mut b));
1615                let (xt, yt) = (x.trim_start_matches('0'), y.trim_start_matches('0'));
1616                let o = xt.len().cmp(&yt.len()).then_with(|| xt.cmp(yt));
1617                if o != Ordering::Equal {
1618                    return o;
1619                }
1620            }
1621            (Some(x), Some(y)) => {
1622                let o = x.to_lowercase().cmp(y.to_lowercase());
1623                if o != Ordering::Equal {
1624                    return o;
1625                }
1626                a.next();
1627                b.next();
1628            }
1629        }
1630    }
1631}
1632
1633/// Adds a native column for each of `columns`.
1634fn add_columns<T>(table: &NSTableView, columns: &[Column<T>]) {
1635    for c in columns {
1636        let column = NSTableColumn::initWithIdentifier(NSTableColumn::alloc(mtm()), &NSString::from_str(&c.id));
1637        column.setTitle(&NSString::from_str(&c.title));
1638        column.setWidth(c.width);
1639        column.setMinWidth(c.min_width);
1640        column.setResizingMask(NSTableColumnResizingOptions::UserResizingMask);
1641        if c.sortable {
1642            let descriptor = NSSortDescriptor::sortDescriptorWithKey_ascending(Some(&NSString::from_str(&c.id)), true);
1643            column.setSortDescriptorPrototype(Some(&descriptor));
1644        }
1645        table.addTableColumn(&column);
1646    }
1647}
1648
1649/// A native table backed by rows of `T`. See the module docs.
1650pub struct TableModel<T: 'static> {
1651    inner: Rc<Inner<T>>,
1652}
1653
1654impl<T: 'static> Clone for TableModel<T> {
1655    fn clone(&self) -> Self {
1656        Self { inner: self.inner.clone() }
1657    }
1658}
1659
1660impl<T: 'static> std::fmt::Debug for TableModel<T> {
1661    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1662        write!(f, "TableModel({:?}, {} rows)", self.inner.id, self.inner.rows.borrow().len())
1663    }
1664}
1665
1666impl<T: 'static> TableModel<T> {
1667    /// Creates the native table (not yet in a window: it's added the first
1668    /// time the host draws it, see [`TableModel::ensure_mounted`]).
1669    pub fn new(id: ViewId, columns: Vec<Column<T>>) -> Self {
1670        let mtm = mtm();
1671        crate::testing::LIVE_OBJC.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1672        let source = Source::alloc(mtm).set_ivars(SourceIvars { data: RefCell::new(None), created: Cell::new(0) });
1673        // SAFETY: plain NSObject init.
1674        let source: Retained<Source> = unsafe { msg_send![super(source), init] };
1675
1676        let table: Retained<HostTableView> = unsafe { msg_send![HostTableView::alloc(mtm), init] };
1677        table.setStyle(NSTableViewStyle::FullWidth);
1678        table.setUsesAlternatingRowBackgroundColors(true);
1679        table.setAllowsMultipleSelection(true);
1680        table.setAllowsColumnReordering(true);
1681        table.setAllowsColumnResizing(true);
1682        add_columns(&table, &columns);
1683        let scroll = NSScrollView::new(mtm);
1684        scroll.setHasVerticalScroller(true);
1685        scroll.setHasHorizontalScroller(true);
1686        scroll.setAutohidesScrollers(true);
1687        scroll.setDocumentView(Some(&table));
1688
1689        let inner = Rc::new(Inner {
1690            id,
1691            columns: RefCell::new(columns),
1692            rows: RefCell::new(Vec::new()),
1693            order: RefCell::new(Vec::new()),
1694            animates: Cell::new(false),
1695            groups: RefCell::new(Vec::new()),
1696            group_by: RefCell::new(None),
1697            sort: RefCell::new(None),
1698            sorts_in_place: Cell::new(true),
1699            events: RefCell::new(VecDeque::new()),
1700            quiet: Cell::new(false),
1701            mounted: Cell::new(false),
1702            transfer: RefCell::new(Transfer::default()),
1703            focus: RefCell::new(None),
1704            scroll,
1705            table: table.clone(),
1706            _source: source.clone(),
1707        });
1708        crate::testing::LIVE_MODELS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1709        let weak: Weak<dyn Data> = Rc::downgrade(&inner) as Weak<dyn Data>;
1710        *source.ivars().data.borrow_mut() = Some(weak);
1711        // SAFETY: the source is kept alive by the model (`_source`), and the
1712        // model removes the table when dropped.
1713        unsafe {
1714            table.setDataSource(Some(ProtocolObject::from_ref(&*source)));
1715            table.setDelegate(Some(ProtocolObject::from_ref(&*source)));
1716            table.setTarget(Some(&source));
1717            table.setDoubleAction(Some(sel!(activate:)));
1718        }
1719        Self { inner }
1720    }
1721
1722    /// The view id the table was created with.
1723    pub fn id(&self) -> ViewId {
1724        self.inner.id
1725    }
1726
1727    /// Adds the table to the attached window if it isn't yet. Called by the
1728    /// host widget before placing it.
1729    pub fn ensure_mounted(&self) {
1730        if !self.inner.mounted.get() && crate::is_attached() {
1731            crate::mount(self.inner.id, Retained::into_super(self.inner.scroll.clone()));
1732            self.inner.mounted.set(true);
1733        }
1734    }
1735
1736    /// Replaces the columns, keeping the same native table (a query
1737    /// browser's results change shape with every query). The sort is
1738    /// cleared. Call [`set_rows`](Self::set_rows) after it when the rows
1739    /// change too: nothing is drawn in between.
1740    pub fn set_columns(&self, columns: Vec<Column<T>>) {
1741        let _focus = KeepFocus::new(&self.inner.table);
1742        let table = &self.inner.table;
1743        *self.inner.sort.borrow_mut() = None;
1744        self.inner.quiet.set(true);
1745        table.setSortDescriptors(&NSArray::new());
1746        let old: Vec<_> = table.tableColumns().iter().collect();
1747        for column in old {
1748            table.removeTableColumn(&column);
1749        }
1750        add_columns(table, &columns);
1751        let gone = self.inner.focus().is_some_and(|f| !columns.iter().any(|c| c.id == f));
1752        *self.inner.columns.borrow_mut() = columns;
1753        self.inner.compute_order();
1754        table.reloadData();
1755        self.inner.quiet.set(false);
1756        if gone {
1757            self.inner.set_focus(None, true);
1758        }
1759    }
1760
1761    /// Replaces all rows (the current sort is applied). Clears the selection.
1762    pub fn set_rows(&self, rows: Vec<T>) {
1763        let _focus = KeepFocus::new(&self.inner.table);
1764        *self.inner.rows.borrow_mut() = rows;
1765        self.inner.compute_order();
1766        self.inner.quiet.set(true);
1767        self.inner.table.reloadData();
1768        // SAFETY: nil sender.
1769        unsafe { self.inner.table.deselectAll(None) };
1770        self.inner.quiet.set(false);
1771        // Views bound to the selection hear that it was cleared.
1772        crate::request_redraw();
1773    }
1774
1775    /// The rows, in model order (unsorted).
1776    pub fn rows(&self) -> Ref<'_, Vec<T>> {
1777        self.inner.rows.borrow()
1778    }
1779
1780    /// Number of rows.
1781    pub fn len(&self) -> usize {
1782        self.inner.rows.borrow().len()
1783    }
1784
1785    /// Whether there are no rows.
1786    pub fn is_empty(&self) -> bool {
1787        self.len() == 0
1788    }
1789
1790    /// Replaces one row. Redraws only that row unless the table is sorted
1791    /// (then the order is recomputed; the selection is kept).
1792    pub fn update_row(&self, index: usize, row: T) {
1793        if let Some(slot) = self.inner.rows.borrow_mut().get_mut(index) {
1794            *slot = row;
1795        } else {
1796            return;
1797        }
1798        // Sorted or grouped: the row may belong elsewhere now.
1799        if self.inner.group_by.borrow().is_some() || (self.inner.sort.borrow().is_some() && self.inner.sorts_in_place.get()) {
1800            self.inner.resort_keeping_selection();
1801            return;
1802        }
1803        let Some(view_row) = self.inner.order.borrow().iter().position(|&m| m == index) else { return };
1804        let columns = NSIndexSet::indexSetWithIndexesInRange(objc2_foundation::NSRange::new(0, self.inner.columns.borrow().len()));
1805        self.inner.table.reloadDataForRowIndexes_columnIndexes(&NSIndexSet::indexSetWithIndex(view_row), &columns);
1806    }
1807
1808    /// Inserts a row at a model index (the selection is kept).
1809    pub fn insert(&self, index: usize, row: T) {
1810        let _focus = KeepFocus::new(&self.inner.table);
1811        let selected = self.inner.selection_model_rows();
1812        // Past the end is the end (an index from before a row went).
1813        let index = index.min(self.inner.rows.borrow().len());
1814        self.inner.rows.borrow_mut().insert(index, row);
1815        let selected: Vec<usize> = selected.into_iter().map(|r| if r >= index { r + 1 } else { r }).collect();
1816        self.inner.compute_order();
1817        match self.inner.animated_position(index) {
1818            // AppKit slides the new row in and keeps the others' views.
1819            Some(at) => self.inner.table.insertRowsAtIndexes_withAnimation(&NSIndexSet::indexSetWithIndex(at), ANIMATION),
1820            None => self.inner.table.reloadData(),
1821        }
1822        self.inner.select_model_rows(&selected);
1823    }
1824
1825    /// Appends rows in one step, for live data (a log tail, a feed): when
1826    /// unsorted, the new rows are added to the end and AppKit only learns
1827    /// the new count (cost independent of the rows already there; the
1828    /// selection is kept). When sorted, the order is recomputed.
1829    pub fn append(&self, rows: Vec<T>) {
1830        if rows.is_empty() {
1831            return;
1832        }
1833        let start = self.len();
1834        self.inner.rows.borrow_mut().extend(rows);
1835        let grouped = self.inner.group_by.borrow().is_some();
1836        if grouped || (self.inner.sort.borrow().is_some() && self.inner.sorts_in_place.get()) {
1837            self.inner.resort_keeping_selection();
1838            return;
1839        }
1840        let end = self.len();
1841        self.inner.order.borrow_mut().extend(start..end);
1842        self.inner.table.noteNumberOfRowsChanged();
1843    }
1844
1845    /// Scrolls so the last row is visible.
1846    pub fn scroll_to_end(&self) {
1847        let n = self.inner.order.borrow().len();
1848        if n > 0 {
1849            self.inner.table.scrollRowToVisible((n - 1) as NSInteger);
1850        }
1851    }
1852
1853    /// Whether the table is scrolled to its last row (within one row), e.g.
1854    /// to keep following new rows only while the user hasn't scrolled up.
1855    pub fn is_at_end(&self) -> bool {
1856        let table = &self.inner.table;
1857        let visible = table.visibleRect();
1858        let bottom = visible.origin.y + visible.size.height;
1859        bottom >= table.bounds().size.height - table.rowHeight() - table.intercellSpacing().height - 1.0
1860    }
1861
1862    /// Appends a row.
1863    pub fn push(&self, row: T) {
1864        let len = self.len();
1865        self.insert(len, row);
1866    }
1867
1868    /// Removes a row (the selection is kept for the other rows).
1869    pub fn remove(&self, index: usize) -> Option<T> {
1870        let _focus = KeepFocus::new(&self.inner.table);
1871        if index >= self.len() {
1872            return None;
1873        }
1874        let selected = self.inner.selection_model_rows();
1875        let at = self.inner.animated_position(index);
1876        let row = self.inner.rows.borrow_mut().remove(index);
1877        let selected: Vec<usize> =
1878            selected.into_iter().filter(|&r| r != index).map(|r| if r > index { r - 1 } else { r }).collect();
1879        self.inner.compute_order();
1880        match at {
1881            Some(at) => self.inner.table.removeRowsAtIndexes_withAnimation(&NSIndexSet::indexSetWithIndex(at), ANIMATION),
1882            None => self.inner.table.reloadData(),
1883        }
1884        self.inner.select_model_rows(&selected);
1885        Some(row)
1886    }
1887
1888    /// Moves `rows` (model indices) to just above the row `before` (or to
1889    /// the end), keeping their order, as a drop reported by
1890    /// [`TableEvent::RowsMoved`] asks. Returns their new model indices; they
1891    /// end up selected.
1892    pub fn move_rows(&self, rows: &[usize], before: Option<usize>) -> Vec<usize> {
1893        let _focus = KeepFocus::new(&self.inner.table);
1894        let mut moving: Vec<usize> = rows.iter().copied().filter(|&r| r < self.len()).collect();
1895        moving.sort_unstable();
1896        moving.dedup();
1897        let at = {
1898            let mut all = self.inner.rows.borrow_mut();
1899            let end = before.unwrap_or(all.len());
1900            // Rows staying put above the drop point.
1901            let at = (0..end.min(all.len())).filter(|r| moving.binary_search(r).is_err()).count();
1902            let mut taken = Vec::with_capacity(moving.len());
1903            for &r in moving.iter().rev() {
1904                taken.push(all.remove(r));
1905            }
1906            for (i, row) in taken.into_iter().rev().enumerate() {
1907                all.insert(at + i, row);
1908            }
1909            at
1910        };
1911        let moved: Vec<usize> = (at..at + moving.len()).collect();
1912        self.inner.compute_order();
1913        self.inner.table.reloadData();
1914        self.inner.select_model_rows(&moved);
1915        moved
1916    }
1917
1918    /// Lets rows be dragged out: each carries its cells as tab-separated
1919    /// text (for other apps), and its model index for
1920    /// [`set_reorderable`](Self::set_reorderable). Off by default (a drag
1921    /// then extends the selection).
1922    pub fn set_row_drag(&self, on: bool) {
1923        self.inner.transfer.borrow_mut().drag = on;
1924        self.inner.table.setDraggingSourceOperationMask_forLocal(NSDragOperation::Copy, false);
1925        self.register_drag_types();
1926    }
1927
1928    /// Lets the user drag rows to a new place (also turns on
1929    /// [`set_row_drag`](Self::set_row_drag)); each drop is reported as
1930    /// [`TableEvent::RowsMoved`]. Refused while the table is sorted.
1931    pub fn set_reorderable(&self, on: bool) {
1932        if on {
1933            self.set_row_drag(true);
1934            self.inner.table.setDraggingSourceOperationMask_forLocal(NSDragOperation::Move, true);
1935        }
1936        self.inner.transfer.borrow_mut().reorder = on;
1937        self.register_drag_types();
1938    }
1939
1940    /// Accepts files dropped from the Finder: `Some(&["csv", "txt"])` for
1941    /// those extensions, `Some(&[])` for any file, `None` to stop. Each drop
1942    /// is reported as [`TableEvent::FilesDropped`].
1943    pub fn set_file_drop(&self, extensions: Option<&[&str]>) {
1944        self.inner.transfer.borrow_mut().files = extensions.map(|e| e.iter().map(|s| s.to_string()).collect());
1945        self.register_drag_types();
1946    }
1947
1948    /// Rows added by [`insert`](Self::insert) and [`push`](Self::push), and
1949    /// removed by [`remove`](Self::remove), fade and slide in and out
1950    /// instead of appearing at once; the other rows keep their cells. Not
1951    /// in a grouped table, and not for [`set_rows`](Self::set_rows) or
1952    /// [`append`](Self::append) (whole lists and live feeds). Off by default.
1953    pub fn set_animates(&self, on: bool) {
1954        self.inner.animates.set(on);
1955    }
1956
1957    /// Accepts web addresses dragged from a browser (a link, or the address
1958    /// bar's icon). Each drop is reported as [`TableEvent::UrlsDropped`].
1959    /// Off by default.
1960    pub fn set_url_drop(&self, on: bool) {
1961        self.inner.transfer.borrow_mut().urls = on;
1962        self.register_drag_types();
1963    }
1964
1965    /// Reports ⌘V on the table as [`TableEvent::Paste`] (and enables Paste
1966    /// in the Edit menu while there is text to paste). Off by default.
1967    pub fn set_pastes(&self, on: bool) {
1968        self.inner.transfer.borrow_mut().pastes = on;
1969    }
1970
1971    /// Reports these keys, pressed without ⌘, ⌥ or ⌃ while rows are
1972    /// selected, as [`TableEvent::Key`] instead of AppKit's handling
1973    /// (Space would type-select, Delete beep). None by default.
1974    pub fn set_keys(&self, keys: &[TableKey]) {
1975        self.inner.transfer.borrow_mut().keys = keys.to_vec();
1976    }
1977
1978    /// Cell focus, as in a spreadsheet: the table keeps a focused column,
1979    /// which a click on a cell moves to its column and ← and → move one
1980    /// column at a time ([`TableEvent::FocusedColumn`]). The focused cell of
1981    /// each selected row is outlined. With the selection it names the cells
1982    /// an action applies to (Set to NULL, Copy Cell). Off by default.
1983    pub fn set_cell_focus(&self, on: bool) {
1984        if self.inner.transfer.borrow().cell_focus == on {
1985            return;
1986        }
1987        self.inner.transfer.borrow_mut().cell_focus = on;
1988        if !on {
1989            *self.inner.focus.borrow_mut() = None;
1990        }
1991        // Row views are made again, as focus rows or AppKit's own.
1992        self.inner.table.reloadData();
1993    }
1994
1995    /// The focused column's id (see [`set_cell_focus`](Self::set_cell_focus)).
1996    pub fn focused_column(&self) -> Option<String> {
1997        self.inner.focus()
1998    }
1999
2000    /// Focuses a column by id (`None`: no column), scrolling it into view.
2001    /// Doesn't report an event.
2002    pub fn set_focused_column(&self, column: Option<&str>) {
2003        let index = column.map(|c| self.inner.table.columnWithIdentifier(&NSString::from_str(c))).unwrap_or(-1);
2004        if index >= 0 {
2005            self.inner.table.scrollColumnToVisible(index);
2006        }
2007        self.inner.set_focus(column.filter(|_| index >= 0).map(str::to_string), false);
2008    }
2009
2010    /// The focused cell's outline in row `view_row` (a view position), in
2011    /// the row's coordinates, if the row is shown, selected and a column is
2012    /// focused. For checks.
2013    pub fn focus_ring(&self, view_row: usize) -> Option<(f64, f64, f64, f64)> {
2014        let table = &self.inner.table;
2015        if !table.isRowSelected(view_row as NSInteger) {
2016            return None;
2017        }
2018        let row = table.rowViewAtRow_makeIfNecessary(view_row as NSInteger, false)?;
2019        let row = row.downcast::<FocusRowView>().ok()?;
2020        let r = row.focus_rect()?;
2021        Some((r.origin.x, r.origin.y, r.size.width, r.size.height))
2022    }
2023
2024    fn register_drag_types(&self) {
2025        let t = self.inner.transfer.borrow();
2026        let mut types = Vec::new();
2027        if t.reorder {
2028            types.push(row_type());
2029        }
2030        if t.files.is_some() {
2031            // SAFETY: AppKit's pasteboard type constant.
2032            types.push(NSString::from_str(&unsafe { NSPasteboardTypeFileURL }.to_string()));
2033        }
2034        if t.urls {
2035            // SAFETY: AppKit's pasteboard type constant.
2036            types.push(NSString::from_str(&unsafe { NSPasteboardTypeURL }.to_string()));
2037        }
2038        self.inner.table.unregisterDraggedTypes();
2039        if !types.is_empty() {
2040            self.inner.table.registerForDraggedTypes(&NSArray::from_retained_slice(&types));
2041        }
2042    }
2043
2044    /// The selected rows as tab-separated text (columns in their current
2045    /// order, one line per row, as ⌘C copies them).
2046    pub fn selected_text(&self) -> String {
2047        let rows = indexes(&self.inner.table.selectedRowIndexes());
2048        self.inner.rows_text(&rows, &column_ids(&self.inner.table))
2049    }
2050
2051    /// Copies the selected rows to `pasteboard` (what ⌘C does with the
2052    /// general pasteboard). False if nothing is selected.
2053    pub fn copy_to(&self, pasteboard: &NSPasteboard) -> bool {
2054        self.inner.table.copy_rows(pasteboard)
2055    }
2056
2057    /// Pastes `pasteboard`'s text (what ⌘V does with the general
2058    /// pasteboard): queues [`TableEvent::Paste`] if the table takes pastes.
2059    pub fn paste_from(&self, pasteboard: &NSPasteboard) -> bool {
2060        self.inner.table.paste_text(pasteboard)
2061    }
2062
2063    /// The model index of the row shown at `position` (0 = top row as
2064    /// currently sorted); `None` past the end or for a group header.
2065    pub fn row_at(&self, position: usize) -> Option<usize> {
2066        self.inner.model_row(position)
2067    }
2068
2069    /// Groups the rows under headers by `key` (e.g. a date or a category):
2070    /// groups appear in the order their first row has in the model, rows
2071    /// keep the sort's order within each group, and each group starts with
2072    /// a header row showing the key (full width, not selectable, floating
2073    /// while its rows scroll). `None` ungroups. Row indices in events stay
2074    /// model indices.
2075    pub fn set_group_by(&self, key: Option<GroupKey<T>>) {
2076        *self.inner.group_by.borrow_mut() = key;
2077        self.inner.table.setFloatsGroupRows(true);
2078        self.inner.resort_keeping_selection();
2079    }
2080
2081    /// The groups' titles, in the order shown (empty when not grouped).
2082    pub fn groups(&self) -> Vec<String> {
2083        self.inner.groups.borrow().clone()
2084    }
2085
2086    /// The number of rows shown, group headers included.
2087    pub fn shown_rows(&self) -> usize {
2088        self.inner.order.borrow().len()
2089    }
2090
2091    /// Selected rows (model indices, ascending in view order).
2092    pub fn selection(&self) -> Vec<usize> {
2093        self.inner.selection_model_rows()
2094    }
2095
2096    /// Selects rows by model index (emits no event).
2097    pub fn select(&self, rows: &[usize]) {
2098        self.inner.select_model_rows(rows);
2099        if let Some(&first) = rows.first()
2100            && let Some(view_row) = self.inner.order.borrow().iter().position(|&m| m == first)
2101        {
2102            self.inner.table.scrollRowToVisible(view_row as NSInteger);
2103        }
2104    }
2105
2106    /// The current sort, if any.
2107    pub fn sort(&self) -> Option<Sort> {
2108        self.inner.sort.borrow().clone()
2109    }
2110
2111    /// Sets the sort (shown in the header) and, with built-in sorting, applies it.
2112    pub fn set_sort(&self, sort: Option<Sort>) {
2113        let descriptors = match &sort {
2114            Some(s) => NSArray::from_retained_slice(&[NSSortDescriptor::sortDescriptorWithKey_ascending(
2115                Some(&NSString::from_str(&s.column)),
2116                s.ascending,
2117            )]),
2118            None => NSArray::new(),
2119        };
2120        *self.inner.sort.borrow_mut() = sort;
2121        // setSortDescriptors calls back sortDescriptorsDidChange; quiet the event.
2122        let events_before = self.inner.events.borrow().len();
2123        self.inner.table.setSortDescriptors(&descriptors);
2124        self.inner.events.borrow_mut().truncate(events_before);
2125        if self.inner.sorts_in_place.get() {
2126            self.inner.resort_keeping_selection();
2127        }
2128    }
2129
2130    /// Built-in sorting (default on): header clicks reorder the rows here.
2131    /// Turn it off to sort yourself on [`TableEvent::Sort`] (e.g. in a database)
2132    /// and call [`TableModel::set_rows`].
2133    pub fn set_sorts_in_place(&self, on: bool) {
2134        self.inner.sorts_in_place.set(on);
2135    }
2136
2137    /// Columns in their current order, with widths.
2138    pub fn column_state(&self) -> Vec<ColumnState> {
2139        self.inner
2140            .table
2141            .tableColumns()
2142            .iter()
2143            .map(|c| ColumnState { id: c.identifier().to_string(), width: c.width() })
2144            .collect()
2145    }
2146
2147    /// Restores a saved arrangement (unknown ids are ignored).
2148    pub fn set_column_state(&self, state: &[ColumnState]) {
2149        let table = &self.inner.table;
2150        for (target, s) in state.iter().enumerate() {
2151            let index = table.columnWithIdentifier(&NSString::from_str(&s.id));
2152            if index < 0 {
2153                continue;
2154            }
2155            if let Some(column) = table.tableColumns().iter().nth(index as usize) {
2156                column.setWidth(s.width);
2157            }
2158            if index as usize != target && target < table.numberOfColumns() as usize {
2159                table.moveColumn_toColumn(index, target as NSInteger);
2160            }
2161        }
2162        // moveColumn fires the delegate; this was the program, not the user.
2163        self.inner.events.borrow_mut().retain(|e| *e != TableEvent::ColumnsChanged);
2164    }
2165
2166    /// Takes the queued user events (for the host widget).
2167    pub fn drain_events(&self) -> Vec<TableEvent> {
2168        self.inner.events.borrow_mut().drain(..).collect()
2169    }
2170
2171    /// Diagnostics: cell views created so far (reuse keeps this near the
2172    /// number of visible cells).
2173    pub fn cells_created(&self) -> usize {
2174        self.inner._source.ivars().created.get()
2175    }
2176
2177    /// The `NSScrollView` holding the table, for hosts that place it
2178    /// themselves (no [`crate::attach`]ed window).
2179    pub fn scroll_view(&self) -> Retained<NSScrollView> {
2180        self.inner.scroll.clone()
2181    }
2182
2183    /// The underlying `NSTableView` (escape hatch).
2184    pub fn table_view(&self) -> Retained<NSTableView> {
2185        Retained::into_super(self.inner.table.clone())
2186    }
2187}
2188
2189#[cfg(test)]
2190mod tests {
2191    use super::natural_cmp;
2192    use std::cmp::Ordering::*;
2193
2194    #[test]
2195    fn key_matches_natural_order() {
2196        use super::natural_key;
2197        let words = ["Item 10", "item 9", "Item 009", "apple", "Banana", "x", "x1", "a2b", "a10b", "Zo", "zoe 2"];
2198        for a in words {
2199            for b in words {
2200                let by_key = natural_key(a).cmp(&natural_key(b));
2201                let by_cmp = natural_cmp(a, b);
2202                if by_cmp != std::cmp::Ordering::Equal {
2203                    assert_eq!(by_key, by_cmp, "{a:?} vs {b:?}");
2204                }
2205            }
2206        }
2207    }
2208
2209    #[test]
2210    fn dates_shown_in_the_users_format() {
2211        use super::{Kind, Value, display};
2212        let none = display(&Kind::Date { time: false, none: None }, &Value::Number(f64::NEG_INFINITY));
2213        assert_eq!(none, "");
2214        // 2020-09-13 12:26:40 UTC: the year shows in every medium style.
2215        let day = display(&Kind::Date { time: false, none: None }, &Value::Number(1_600_000_000.0));
2216        let with_time = display(&Kind::Date { time: true, none: None }, &Value::Number(1_600_000_000.0));
2217        assert!(day.contains("2020") && with_time.contains("2020") && with_time.len() > day.len(), "{day:?} {with_time:?}");
2218        // `none_text`: a word for a missing date; dates stay dates.
2219        let col = super::Column::<Option<std::time::SystemTime>>::date("end", "End", |t| *t).with_time().none_text("Running");
2220        assert_eq!(display(&col.kind, &(col.value)(&None)), "Running");
2221        assert_eq!(display(&col.kind, &(col.value)(&Some(std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_600_000_000)))), with_time);
2222    }
2223
2224    #[test]
2225    fn natural_order() {
2226        assert_eq!(natural_cmp("Item 9", "Item 10"), Less);
2227        assert_eq!(natural_cmp("apple", "Banana"), Less);
2228        assert_eq!(natural_cmp("a2b", "a02b"), Equal);
2229        assert_eq!(natural_cmp("x", "x1"), Less);
2230    }
2231}
2232
2233#[cfg(test)]
2234mod number_cells {
2235    use super::*;
2236
2237    #[test]
2238    fn nan_is_no_value() {
2239        assert_eq!(display(&Kind::Number { decimals: 2 }, &Value::Number(f64::NAN)), "");
2240        // The region's decimal separator (78,4 in Germany), no grouping.
2241        assert_eq!(display(&Kind::Number { decimals: 2 }, &Value::Number(1.5)), format!("1{}50", decimal_separator()));
2242        assert_eq!(display(&Kind::Number { decimals: 0 }, &Value::Number(2026.0)), "2026");
2243    }
2244}