Skip to main content

ferrokit_core/
table.rs

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