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