Skip to main content

ferrokit_core/
table.rs

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