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