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 emits
150    /// [`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            if let Some(row) = (row >= 0).then_some(row as usize).and_then(|r| data.model_row(r)) {
425                data.push(TableEvent::Edit { row, column, value: sender.stringValue().to_string() });
426            }
427        }
428
429        #[unsafe(method(toggle:))]
430        fn toggle(&self, sender: &NSButton) {
431            let Some(data) = self.data() else { return };
432            let Some(table) = table_of(sender) else { return };
433            let row = table.rowForView(sender);
434            let Some(column) = sender.identifier().map(|i| i.to_string()) else { return };
435            if let Some(row) = (row >= 0).then_some(row as usize).and_then(|r| data.model_row(r)) {
436                data.push(TableEvent::Toggle { row, column, value: sender.state() == NSControlStateValueOn });
437            }
438        }
439    }
440);
441
442/// What a drag carries that this table accepts.
443enum Dropped {
444    Rows(Vec<usize>),
445    Files(Vec<std::path::PathBuf>),
446}
447
448define_class!(
449    // NSTableView that also activates the selected row on Return / Enter, and
450    // copies and pastes rows.
451    #[unsafe(super(NSTableView, NSControl, NSView, NSResponder, NSObject))]
452    #[thread_kind = MainThreadOnly]
453    #[name = "FerrokitCoreTableView"]
454    struct HostTableView;
455
456    impl HostTableView {
457        #[unsafe(method(keyDown:))]
458        fn key_down(&self, event: &NSEvent) {
459            // 36: Return, 76: keypad Enter.
460            if matches!(event.keyCode(), 36 | 76) {
461                let row = self.selectedRow();
462                let source = unsafe { self.dataSource() };
463                let source = source.and_then(|s| {
464                    let any: &AnyObject = s.as_ref();
465                    any.downcast_ref::<Source>().map(|s| s.retain())
466                });
467                if let (true, Some(source)) = (row >= 0, source) {
468                    if let Some(data) = source.data()
469                        && let Some(row) = data.model_row(row as usize)
470                    {
471                        data.push(TableEvent::Activate(row));
472                    }
473                    return;
474                }
475            }
476            let () = unsafe { msg_send![super(self), keyDown: event] };
477        }
478
479        #[unsafe(method(copy:))]
480        fn copy(&self, _sender: Option<&AnyObject>) {
481            self.copy_rows(&NSPasteboard::generalPasteboard());
482        }
483
484        #[unsafe(method(paste:))]
485        fn paste(&self, _sender: Option<&AnyObject>) {
486            self.paste_text(&NSPasteboard::generalPasteboard());
487        }
488
489        #[unsafe(method(validateMenuItem:))]
490        fn validate_menu_item(&self, item: &NSMenuItem) -> bool {
491            let action = item.action();
492            if action == Some(sel!(copy:)) {
493                self.selectedRow() >= 0
494            } else if action == Some(sel!(paste:)) {
495                let pastes = self.source().and_then(|s| s.data()).is_some_and(|d| d.transfer().pastes);
496                // SAFETY: AppKit's pasteboard type constant.
497                pastes && NSPasteboard::generalPasteboard().stringForType(unsafe { NSPasteboardTypeString }).is_some()
498            } else {
499                true
500            }
501        }
502    }
503);
504
505impl HostTableView {
506    fn source(&self) -> Option<Retained<Source>> {
507        let source = unsafe { self.dataSource() }?;
508        let any: &AnyObject = source.as_ref();
509        any.downcast_ref::<Source>().map(|s| s.retain())
510    }
511
512    /// Writes the selected rows to `pasteboard` as tab-separated text.
513    fn copy_rows(&self, pasteboard: &NSPasteboard) -> bool {
514        let Some(data) = self.source().and_then(|s| s.data()) else { return false };
515        let rows = indexes(&self.selectedRowIndexes());
516        if rows.is_empty() {
517            return false;
518        }
519        let text = NSString::from_str(&data.rows_text(&rows, &column_ids(self)));
520        pasteboard.clearContents();
521        // SAFETY: AppKit's pasteboard type constants.
522        unsafe {
523            pasteboard.setString_forType(&text, NSPasteboardTypeString);
524            pasteboard.setString_forType(&text, NSPasteboardTypeTabularText);
525        }
526        true
527    }
528
529    /// Reports `pasteboard`'s text as a paste, if the table takes pastes.
530    fn paste_text(&self, pasteboard: &NSPasteboard) -> bool {
531        let Some(data) = self.source().and_then(|s| s.data()) else { return false };
532        // SAFETY: AppKit's pasteboard type constant.
533        let text = pasteboard.stringForType(unsafe { NSPasteboardTypeString });
534        match (data.transfer().pastes, text) {
535            (true, Some(text)) => {
536                data.push(TableEvent::Paste(text.to_string()));
537                true
538            }
539            _ => false,
540        }
541    }
542}
543
544/// The table's column ids, in their current (user-arranged) order.
545fn column_ids(table: &NSTableView) -> Vec<String> {
546    table.tableColumns().iter().map(|c| c.identifier().to_string()).collect()
547}
548
549use objc2::Message as _;
550
551fn table_of(view: &NSView) -> Option<Retained<NSTableView>> {
552    // SAFETY: walking up a live view hierarchy on the main thread.
553    let mut current = unsafe { view.superview() };
554    while let Some(v) = current {
555        if let Ok(table) = v.clone().downcast::<NSTableView>() {
556            return Some(table);
557        }
558        current = unsafe { v.superview() };
559    }
560    None
561}
562
563fn indexes(set: &NSIndexSet) -> Vec<usize> {
564    let mut out = Vec::with_capacity(set.count());
565    let mut i = set.firstIndex();
566    while i != usize::MAX && out.len() < set.count() {
567        out.push(i);
568        i = set.indexGreaterThanIndex(i);
569    }
570    out
571}
572
573impl Source {
574    fn cell_text(&self, column: Option<&NSTableColumn>, row: NSInteger) -> Option<Retained<NSString>> {
575        let (kind, value) = self.data()?.cell(row as usize, &column?.identifier().to_string())?;
576        Some(NSString::from_str(&display(kind, &value)))
577    }
578
579    fn data(&self) -> Option<Rc<dyn Data>> {
580        self.ivars().data.borrow().as_ref().and_then(Weak::upgrade)
581    }
582
583    fn row_writer(&self, table: &NSTableView, row: NSInteger) -> Option<Retained<ProtocolObject<dyn NSPasteboardWriting>>> {
584        let data = self.data()?;
585        if !data.transfer().drag {
586            return None;
587        }
588        let model = data.model_row(usize::try_from(row).ok()?)?;
589        let item = NSPasteboardItem::new();
590        item.setString_forType(&NSString::from_str(&model.to_string()), &row_type());
591        let text = data.rows_text(&[row as usize], &column_ids(table));
592        // SAFETY: AppKit's pasteboard type constant.
593        item.setString_forType(&NSString::from_str(&text), unsafe { NSPasteboardTypeString });
594        Some(ProtocolObject::from_retained(item))
595    }
596
597    fn accept(&self, table: &NSTableView, info: &ProtocolObject<dyn NSDraggingInfo>, row: NSInteger) -> bool {
598        let Some(data) = self.data() else { return false };
599        let before = usize::try_from(row).ok().and_then(|r| data.model_row(r));
600        match self.dropped(table, info) {
601            Some(Dropped::Rows(rows)) => data.push(TableEvent::RowsMoved { rows, before }),
602            Some(Dropped::Files(paths)) => data.push(TableEvent::FilesDropped { paths, before }),
603            None => return false,
604        }
605        true
606    }
607
608    /// What a drag over `table` carries that the table takes: its own rows
609    /// (when reorderable and unsorted), or files (when it takes them).
610    fn dropped(&self, table: &NSTableView, info: &ProtocolObject<dyn NSDraggingInfo>) -> Option<Dropped> {
611        let data = self.data()?;
612        let transfer = data.transfer();
613        let items = info.draggingPasteboard().pasteboardItems()?;
614        let own = info.draggingSource().is_some_and(|s| std::ptr::eq(&*s as *const AnyObject, table as *const NSTableView as *const AnyObject));
615        if own {
616            // Reordering a sorted table has no meaning: the sort decides.
617            if !transfer.reorder || data.sorted() {
618                return None;
619            }
620            let rows: Vec<usize> = items.iter().filter_map(|i| i.stringForType(&row_type())?.to_string().parse().ok()).collect();
621            return (!rows.is_empty()).then_some(Dropped::Rows(rows));
622        }
623        let extensions = transfer.files?;
624        let paths: Vec<std::path::PathBuf> = items
625            .iter()
626            // SAFETY: AppKit's pasteboard type constant.
627            .filter_map(|i| i.stringForType(unsafe { NSPasteboardTypeFileURL }))
628            .filter_map(|u| NSURL::URLWithString(&u)?.path().map(|p| std::path::PathBuf::from(p.to_string())))
629            .collect();
630        let accepted = |p: &std::path::PathBuf| {
631            extensions.is_empty()
632                || p.extension().and_then(|e| e.to_str()).is_some_and(|e| extensions.iter().any(|x| x.eq_ignore_ascii_case(e)))
633        };
634        (!paths.is_empty() && paths.iter().all(accepted)).then_some(Dropped::Files(paths))
635    }
636
637    /// A group header: its title, in the table's group-row style.
638    fn group_view(&self, table: &NSTableView, row: NSInteger) -> Option<Retained<NSView>> {
639        let title = self.data()?.group_title(row as usize)?;
640        let ident = NSString::from_str("ferrokit-core.group");
641        // SAFETY: reuse lookup by identifier; owner may be nil.
642        let field = match unsafe { table.makeViewWithIdentifier_owner(&ident, None) }.and_then(|v| v.downcast::<NSTextField>().ok()) {
643            Some(f) => f,
644            None => {
645                let f = NSTextField::labelWithString(&NSString::new(), MainThreadMarker::from(self));
646                f.setIdentifier(Some(&ident));
647                f.setFont(Some(&objc2_app_kit::NSFont::boldSystemFontOfSize(objc2_app_kit::NSFont::smallSystemFontSize())));
648                f.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
649                f
650            }
651        };
652        field.setStringValue(&NSString::from_str(&title));
653        Some(Retained::into_super(Retained::into_super(field)))
654    }
655
656    fn progress_view(&self, table: &NSTableView, ident: &NSString, value: f64) -> Retained<NSView> {
657        use objc2_app_kit::{NSProgressIndicator, NSProgressIndicatorStyle, NSTableCellView};
658        let mtm = MainThreadMarker::from(self);
659        // SAFETY: reuse lookup by identifier; owner may be nil.
660        let cell = match unsafe { table.makeViewWithIdentifier_owner(ident, None) }.and_then(|v| v.downcast::<NSTableCellView>().ok()) {
661            Some(c) => c,
662            None => {
663                self.ivars().created.set(self.ivars().created.get() + 1);
664                let c = NSTableCellView::new(mtm);
665                c.setIdentifier(Some(ident));
666                let bar = NSProgressIndicator::new(mtm);
667                bar.setStyle(NSProgressIndicatorStyle::Bar);
668                bar.setIndeterminate(false);
669                bar.setMinValue(0.0);
670                bar.setMaxValue(1.0);
671                bar.setControlSize(objc2_app_kit::NSControlSize::Small);
672                bar.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable | objc2_app_kit::NSAutoresizingMaskOptions::ViewMinYMargin | objc2_app_kit::NSAutoresizingMaskOptions::ViewMaxYMargin);
673                bar.setFrame(objc2_foundation::NSRect::new(objc2_foundation::NSPoint::new(2.0, 2.0), objc2_foundation::NSSize::new(96.0, 12.0)));
674                c.addSubview(&bar);
675                if let Some(title) = self.data().and_then(|d| d.title(&ident.to_string())) {
676                    // SAFETY: NSAccessibility's label setter.
677                    let () = unsafe { msg_send![&*bar, setAccessibilityLabel: &*NSString::from_str(&title)] };
678                }
679                c
680            }
681        };
682        if let Some(bar) = cell.subviews().iter().find_map(|v| v.downcast::<objc2_app_kit::NSProgressIndicator>().ok()) {
683            bar.setDoubleValue(value);
684        }
685        Retained::into_super(cell)
686    }
687
688    fn cell_view(&self, table: &NSTableView, column: &NSTableColumn, row: NSInteger) -> Option<Retained<NSView>> {
689        let ident = column.identifier();
690        let (kind, value) = self.data()?.cell(row as usize, &ident.to_string())?;
691        let mtm = MainThreadMarker::from(self);
692        if kind == Kind::Progress {
693            let v = if let Value::Number(n) = value { n } else { 0.0 };
694            return Some(self.progress_view(table, &ident, v));
695        }
696        if self.data().is_some_and(|d| d.has_icon(&ident.to_string())) {
697            return Some(self.icon_view(table, &ident, kind, &value, row));
698        }
699        // SAFETY: reuse lookup by identifier; owner may be nil.
700        let reused = unsafe { table.makeViewWithIdentifier_owner(&ident, None) };
701        if kind == Kind::Check {
702            let button = match reused.and_then(|v| v.downcast::<NSButton>().ok()) {
703                Some(b) => b,
704                None => {
705                    self.ivars().created.set(self.ivars().created.get() + 1);
706                    // SAFETY: target is this source, which outlives the table's cells.
707                    let b = unsafe { NSButton::checkboxWithTitle_target_action(&NSString::new(), Some(self), Some(sel!(toggle:)), mtm) };
708                    b.setIdentifier(Some(&ident));
709                    // An untitled checkbox reads as just "checkbox": title it after
710                    // its column and show only the box.
711                    if let Some(title) = self.data().and_then(|d| d.title(&ident.to_string())) {
712                        let title = NSString::from_str(&title);
713                        b.setTitle(&title);
714                        b.setImagePosition(objc2_app_kit::NSCellImagePosition::ImageOnly);
715                        // Image-only buttons report an empty AX title; label
716                        // the button and its cell (which serves accessibility).
717                        // SAFETY: NSAccessibility setters taking a string.
718                        unsafe {
719                            let () = msg_send![&*b, setAccessibilityLabel: &*title];
720                            let cell: Option<Retained<AnyObject>> = msg_send![&*b, cell];
721                            if let Some(cell) = cell {
722                                let () = msg_send![&*cell, setAccessibilityLabel: &*title];
723                            }
724                        }
725                    }
726                    b
727                }
728            };
729            button.setState(if value == Value::Bool(true) { NSControlStateValueOn } else { NSControlStateValueOff });
730            return Some(Retained::into_super(Retained::into_super(button)));
731        }
732        let field = match reused.and_then(|v| v.downcast::<NSTextField>().ok()) {
733            Some(f) => f,
734            None => {
735                self.ivars().created.set(self.ivars().created.get() + 1);
736                let f = NSTextField::labelWithString(&NSString::new(), mtm);
737                f.setIdentifier(Some(&ident));
738                f.setLineBreakMode(NSLineBreakMode::ByTruncatingTail);
739                if self.data().is_some_and(|d| d.editable(&ident.to_string())) {
740                    // A borderless editable label: NSTableView starts editing
741                    // on double-click (or a click on the selected row), and
742                    // the action fires when editing ends.
743                    f.setEditable(true);
744                    f.setSelectable(true);
745                    // SAFETY: target is this source, which outlives the table's cells.
746                    unsafe {
747                        f.setTarget(Some(self));
748                        f.setAction(Some(sel!(edit:)));
749                    }
750                }
751                f
752            }
753        };
754        // Set on reuse too: a column's kind can change (`set_columns`).
755        field.setAlignment(if let Kind::Number { .. } = kind { NSTextAlignment::Right } else { NSTextAlignment::Natural });
756        field.setStringValue(&NSString::from_str(&display(kind, &value)));
757        Some(Retained::into_super(Retained::into_super(field)))
758    }
759
760    /// A cell with an image before its text (an icon column).
761    fn icon_view(&self, table: &NSTableView, ident: &NSString, kind: Kind, value: &Value, row: NSInteger) -> Retained<NSView> {
762        use objc2_app_kit::{NSImageView, NSTableCellView};
763        let mtm = MainThreadMarker::from(self);
764        // SAFETY: reuse lookup by identifier; owner may be nil.
765        let cell = match unsafe { table.makeViewWithIdentifier_owner(ident, None) }.and_then(|v| v.downcast::<NSTableCellView>().ok()) {
766            Some(c) => c,
767            None => {
768                self.ivars().created.set(self.ivars().created.get() + 1);
769                let c = NSTableCellView::new(mtm);
770                c.setIdentifier(Some(ident));
771                let image = NSImageView::new(mtm);
772                image.setFrame(objc2_foundation::NSRect::new(objc2_foundation::NSPoint::new(2.0, 0.0), objc2_foundation::NSSize::new(16.0, 16.0)));
773                image.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewMinYMargin | objc2_app_kit::NSAutoresizingMaskOptions::ViewMaxYMargin);
774                let text = NSTextField::labelWithString(&NSString::new(), mtm);
775                text.setLineBreakMode(NSLineBreakMode::ByTruncatingTail);
776                text.setFrame(objc2_foundation::NSRect::new(objc2_foundation::NSPoint::new(22.0, 0.0), objc2_foundation::NSSize::new(100.0, 17.0)));
777                text.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable | objc2_app_kit::NSAutoresizingMaskOptions::ViewMinYMargin | objc2_app_kit::NSAutoresizingMaskOptions::ViewMaxYMargin);
778                if let Kind::Number { .. } = kind {
779                    text.setAlignment(NSTextAlignment::Right);
780                }
781                c.addSubview(&image);
782                c.addSubview(&text);
783                // SAFETY: weak outlets; both views are the cell's subviews,
784                // which keeps them alive.
785                unsafe {
786                    c.setImageView(Some(&image));
787                    c.setTextField(Some(&text));
788                }
789                c
790            }
791        };
792        let image = self.data().and_then(|d| d.icon(row as usize, &ident.to_string())).and_then(|i| match i {
793            CellImage::Symbol(name) => objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(&NSString::from_str(&name), None),
794            CellImage::FileIcon(path) => Some(objc2_app_kit::NSWorkspace::sharedWorkspace().iconForFile(&NSString::from_str(&path.to_string_lossy()))),
795        });
796        // SAFETY: the outlets set above (subviews of the cell).
797        if let Some(iv) = unsafe { cell.imageView() } {
798            iv.setImage(image.as_deref());
799        }
800        // SAFETY: as above.
801        if let Some(tf) = unsafe { cell.textField() } {
802            tf.setStringValue(&NSString::from_str(&display(kind, value)));
803        }
804        Retained::into_super(cell)
805    }
806}
807
808struct Inner<T: 'static> {
809    id: ViewId,
810    columns: RefCell<Vec<Column<T>>>,
811    rows: RefCell<Vec<T>>,
812    /// View position → model index (identity when unsorted); a group
813    /// header's slot is `HEADER | group`.
814    order: RefCell<Vec<usize>>,
815    /// Groups' titles (see `set_group_by`).
816    groups: RefCell<Vec<String>>,
817    group_by: RefCell<Option<GroupKey<T>>>,
818    sort: RefCell<Option<Sort>>,
819    sorts_in_place: Cell<bool>,
820    events: RefCell<VecDeque<TableEvent>>,
821    /// Set while the model changes the selection itself (no event).
822    quiet: Cell<bool>,
823    mounted: Cell<bool>,
824    transfer: RefCell<Transfer>,
825    scroll: Retained<NSScrollView>,
826    table: Retained<HostTableView>,
827    _source: Retained<Source>,
828}
829
830impl<T: 'static> Data for Inner<T> {
831    fn count(&self) -> usize {
832        self.order.borrow().len()
833    }
834
835    fn cell(&self, view_row: usize, column: &str) -> Option<(Kind, Value)> {
836        let columns = self.columns.borrow();
837        let column = columns.iter().find(|c| c.id == column)?;
838        let index = self.model_row(view_row)?;
839        let rows = self.rows.borrow();
840        Some((column.kind, (column.value)(rows.get(index)?)))
841    }
842
843    fn model_row(&self, view_row: usize) -> Option<usize> {
844        self.order.borrow().get(view_row).copied().filter(|m| m & HEADER == 0)
845    }
846
847    fn group_title(&self, view_row: usize) -> Option<String> {
848        let slot = *self.order.borrow().get(view_row)?;
849        (slot & HEADER != 0).then(|| self.groups.borrow().get(slot & !HEADER).cloned()).flatten()
850    }
851
852    fn icon(&self, view_row: usize, column: &str) -> Option<CellImage> {
853        let columns = self.columns.borrow();
854        let column = columns.iter().find(|c| c.id == column)?;
855        let index = self.model_row(view_row)?;
856        let rows = self.rows.borrow();
857        column.icon.as_ref().and_then(|f| f(rows.get(index)?))
858    }
859
860    fn has_icon(&self, column: &str) -> bool {
861        self.columns.borrow().iter().any(|c| c.id == column && c.icon.is_some())
862    }
863
864    fn editable(&self, column: &str) -> bool {
865        self.columns.borrow().iter().any(|c| c.id == column && c.editable && c.kind != Kind::Check)
866    }
867
868    fn title(&self, column: &str) -> Option<String> {
869        self.columns.borrow().iter().find(|c| c.id == column).map(|c| c.title.clone())
870    }
871
872    fn sort_changed(&self, sort: Option<Sort>) {
873        *self.sort.borrow_mut() = sort.clone();
874        if self.sorts_in_place.get() {
875            self.resort_keeping_selection();
876        }
877        if let Some(sort) = sort {
878            self.push(TableEvent::Sort(sort));
879        }
880    }
881
882    fn push(&self, event: TableEvent) {
883        let mut events = self.events.borrow_mut();
884        // Column resizes arrive continuously while dragging: keep one.
885        if event == TableEvent::ColumnsChanged && events.back() == Some(&TableEvent::ColumnsChanged) {
886            return;
887        }
888        events.push_back(event);
889        drop(events);
890        crate::request_redraw();
891    }
892
893    fn quiet(&self) -> bool {
894        self.quiet.get()
895    }
896
897    fn transfer(&self) -> Transfer {
898        self.transfer.borrow().clone()
899    }
900
901    fn sorted(&self) -> bool {
902        self.sort.borrow().is_some()
903    }
904
905    fn rows_text(&self, view_rows: &[usize], columns: &[String]) -> String {
906        let all = self.columns.borrow();
907        let columns: Vec<&Column<T>> = columns.iter().filter_map(|id| all.iter().find(|c| &c.id == id)).collect();
908        let order = self.order.borrow();
909        let rows = self.rows.borrow();
910        let clean = |s: String| s.replace(['\t', '\n', '\r'], " ");
911        view_rows
912            .iter()
913            .filter_map(|&r| rows.get(*order.get(r)?))
914            .map(|row| columns.iter().map(|c| clean(display(c.kind, &(c.value)(row)))).collect::<Vec<_>>().join("\t"))
915            .collect::<Vec<_>>()
916            .join("\n")
917    }
918}
919
920impl<T: 'static> Inner<T> {
921    /// Recomputes `order` from the current sort. Keys are computed once per
922    /// row (not per comparison) and the sort is stable.
923    fn compute_order(&self) {
924        let rows = self.rows.borrow();
925        let mut order: Vec<usize> = (0..rows.len()).collect();
926        let sort = self.sort.borrow().clone();
927        let columns = self.columns.borrow();
928        if let Some(column) = sort.as_ref().and_then(|s| columns.iter().find(|c| c.id == s.column)) {
929            // One key per row, built once: text becomes a natural-order key
930            // compared bytewise (comparing with case folding on every
931            // comparison took 160 ms for 100k rows).
932            enum Key {
933                Number(f64),
934                Text(String),
935            }
936            let keys: Vec<Key> = rows
937                .iter()
938                .map(|r| match (column.value)(r) {
939                    Value::Number(n) => Key::Number(n),
940                    Value::Bool(b) => Key::Number(b as u8 as f64),
941                    Value::Text(t) => Key::Text(natural_key(&t)),
942                })
943                .collect();
944            order.sort_by(|a, b| match (&keys[*a], &keys[*b]) {
945                (Key::Number(x), Key::Number(y)) => x.total_cmp(y),
946                (Key::Text(x), Key::Text(y)) => x.cmp(y),
947                (Key::Number(_), Key::Text(_)) => std::cmp::Ordering::Less,
948                (Key::Text(_), Key::Number(_)) => std::cmp::Ordering::Greater,
949            });
950            if sort.is_some_and(|s| !s.ascending) {
951                order.reverse();
952            }
953        }
954        // Groups: rows gathered by key (groups in order of first appearance
955        // in the model, rows in the sort's order within each), each run
956        // after a header slot.
957        let mut groups = Vec::new();
958        if let Some(key) = self.group_by.borrow().as_ref() {
959            let keys: Vec<String> = rows.iter().map(key).collect();
960            let mut index_of: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
961            for k in &keys {
962                if !index_of.contains_key(k.as_str()) {
963                    index_of.insert(k, groups.len());
964                    groups.push(k.clone());
965                }
966            }
967            let mut buckets: Vec<Vec<usize>> = vec![Vec::new(); groups.len()];
968            for &m in &order {
969                buckets[index_of[keys[m].as_str()]].push(m);
970            }
971            order = buckets.into_iter().enumerate().flat_map(|(g, rows)| std::iter::once(HEADER | g).chain(rows)).collect();
972        }
973        drop(rows);
974        *self.groups.borrow_mut() = groups;
975        *self.order.borrow_mut() = order;
976        self.fit_columns();
977    }
978
979    /// Sizes `fit` columns to their widest content: the title and, with many
980    /// rows, the 64 longest values by character count (all of them below
981    /// 2,000 rows), measured in the table's font.
982    fn fit_columns(&self) {
983        let rows = self.rows.borrow();
984        for column in self.columns.borrow().iter().filter(|c| c.fit) {
985            let Some(native) = self.table.tableColumnWithIdentifier(&NSString::from_str(&column.id)) else { continue };
986            let mut texts: Vec<String> = rows.iter().map(|r| display(column.kind, &(column.value)(r))).collect();
987            if texts.len() > 2_000 {
988                texts.sort_by_key(|t| std::cmp::Reverse(t.chars().count()));
989                texts.truncate(64);
990            }
991            let font = objc2_app_kit::NSFont::systemFontOfSize(objc2_app_kit::NSFont::systemFontSize());
992            let attrs = objc2_foundation::NSDictionary::from_retained_objects(
993                // SAFETY: AppKit's font attribute key.
994                &[unsafe { objc2_app_kit::NSFontAttributeName }],
995                &[Retained::into_super(Retained::into_super(font)) as Retained<AnyObject>],
996            );
997            // SAFETY: measuring a string with font attributes.
998            let width = |s: &str| unsafe { objc2_app_kit::NSStringDrawing::sizeWithAttributes(&*NSString::from_str(s), Some(&attrs)).width };
999            let widest = texts.iter().map(|t| width(t)).fold(width(&column.title) + 16.0, f64::max);
1000            let icon = if column.icon.is_some() { 22.0 } else { 0.0 };
1001            native.setWidth((widest + icon + 12.0).ceil().max(column.min_width));
1002        }
1003    }
1004
1005    fn selection_model_rows(&self) -> Vec<usize> {
1006        let order = self.order.borrow();
1007        indexes(&self.table.selectedRowIndexes()).into_iter().filter_map(|r| order.get(r).copied()).filter(|m| m & HEADER == 0).collect()
1008    }
1009
1010    fn select_model_rows(&self, rows: &[usize]) {
1011        let order = self.order.borrow();
1012        let mut position = vec![usize::MAX; self.rows.borrow().len()];
1013        for (view, &model) in order.iter().enumerate() {
1014            if model & HEADER == 0 {
1015                position[model] = view;
1016            }
1017        }
1018        drop(order);
1019        let set = NSMutableIndexSet::new();
1020        for &r in rows {
1021            if let Some(&p) = position.get(r).filter(|p| **p != usize::MAX) {
1022                set.addIndex(p);
1023            }
1024        }
1025        self.quiet.set(true);
1026        self.table.selectRowIndexes_byExtendingSelection(&set, false);
1027        self.quiet.set(false);
1028    }
1029
1030    fn resort_keeping_selection(&self) {
1031        let selected = self.selection_model_rows();
1032        self.compute_order();
1033        self.table.reloadData();
1034        self.select_model_rows(&selected);
1035    }
1036}
1037
1038impl<T: 'static> Drop for Inner<T> {
1039    fn drop(&mut self) {
1040        // AppKit holds these weakly: detach them before the source goes, in
1041        // case the table outlives the model (e.g. in an autorelease pool).
1042        // SAFETY: clearing to nil is always valid.
1043        unsafe {
1044            self.table.setDataSource(None);
1045            self.table.setDelegate(None);
1046            self.table.setTarget(None);
1047            self.table.setDoubleAction(None);
1048        }
1049        if self.mounted.get() {
1050            crate::unmount(self.id);
1051        }
1052        crate::testing::LIVE_MODELS.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
1053    }
1054}
1055
1056impl Drop for SourceIvars {
1057    fn drop(&mut self) {
1058        crate::testing::LIVE_OBJC.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
1059    }
1060}
1061
1062/// A sort key giving natural order under plain byte comparison:
1063/// case-insensitive, digit runs compared as numbers ("Item 9" < "Item 10"),
1064/// like the Finder. Digit runs become their length (as a char) then the
1065/// digits without leading zeros, so longer numbers sort later.
1066fn natural_key(s: &str) -> String {
1067    let mut key = String::with_capacity(s.len() + 4);
1068    let mut chars = s.chars().peekable();
1069    while let Some(c) = chars.next() {
1070        if c.is_ascii_digit() {
1071            let mut digits = String::from(c);
1072            while let Some(d) = chars.peek().filter(|d| d.is_ascii_digit()) {
1073                digits.push(*d);
1074                chars.next();
1075            }
1076            let trimmed = digits.trim_start_matches('0');
1077            // \u{1} sorts before any printable character.
1078            key.push('\u{1}');
1079            key.push(char::from_u32(0x30 + trimmed.len() as u32).unwrap_or('~'));
1080            key.push_str(trimmed);
1081        } else {
1082            key.extend(c.to_lowercase());
1083        }
1084    }
1085    key
1086}
1087
1088/// Natural order for text (reference implementation for the key's tests).
1089#[cfg(test)]
1090fn natural_cmp(a: &str, b: &str) -> std::cmp::Ordering {
1091    use std::cmp::Ordering;
1092    let (mut a, mut b) = (a.chars().peekable(), b.chars().peekable());
1093    loop {
1094        match (a.peek(), b.peek()) {
1095            (None, None) => return Ordering::Equal,
1096            (None, _) => return Ordering::Less,
1097            (_, None) => return Ordering::Greater,
1098            (Some(x), Some(y)) if x.is_ascii_digit() && y.is_ascii_digit() => {
1099                let take = |it: &mut std::iter::Peekable<std::str::Chars>| {
1100                    let mut n = String::new();
1101                    while let Some(c) = it.peek().filter(|c| c.is_ascii_digit()) {
1102                        n.push(*c);
1103                        it.next();
1104                    }
1105                    n
1106                };
1107                let (x, y) = (take(&mut a), take(&mut b));
1108                let (xt, yt) = (x.trim_start_matches('0'), y.trim_start_matches('0'));
1109                let o = xt.len().cmp(&yt.len()).then_with(|| xt.cmp(yt));
1110                if o != Ordering::Equal {
1111                    return o;
1112                }
1113            }
1114            (Some(x), Some(y)) => {
1115                let o = x.to_lowercase().cmp(y.to_lowercase());
1116                if o != Ordering::Equal {
1117                    return o;
1118                }
1119                a.next();
1120                b.next();
1121            }
1122        }
1123    }
1124}
1125
1126/// Adds a native column for each of `columns`.
1127fn add_columns<T>(table: &NSTableView, columns: &[Column<T>]) {
1128    for c in columns {
1129        let column = NSTableColumn::initWithIdentifier(NSTableColumn::alloc(mtm()), &NSString::from_str(&c.id));
1130        column.setTitle(&NSString::from_str(&c.title));
1131        column.setWidth(c.width);
1132        column.setMinWidth(c.min_width);
1133        column.setResizingMask(NSTableColumnResizingOptions::UserResizingMask);
1134        if c.sortable {
1135            let descriptor = NSSortDescriptor::sortDescriptorWithKey_ascending(Some(&NSString::from_str(&c.id)), true);
1136            column.setSortDescriptorPrototype(Some(&descriptor));
1137        }
1138        table.addTableColumn(&column);
1139    }
1140}
1141
1142/// A native table backed by rows of `T`. See the module docs.
1143pub struct TableModel<T: 'static> {
1144    inner: Rc<Inner<T>>,
1145}
1146
1147impl<T: 'static> Clone for TableModel<T> {
1148    fn clone(&self) -> Self {
1149        Self { inner: self.inner.clone() }
1150    }
1151}
1152
1153impl<T: 'static> std::fmt::Debug for TableModel<T> {
1154    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1155        write!(f, "TableModel({:?}, {} rows)", self.inner.id, self.inner.rows.borrow().len())
1156    }
1157}
1158
1159impl<T: 'static> TableModel<T> {
1160    /// Creates the native table (not yet in a window: it's added the first
1161    /// time the host draws it, see [`TableModel::ensure_mounted`]).
1162    pub fn new(id: ViewId, columns: Vec<Column<T>>) -> Self {
1163        let mtm = mtm();
1164        crate::testing::LIVE_OBJC.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1165        let source = Source::alloc(mtm).set_ivars(SourceIvars { data: RefCell::new(None), created: Cell::new(0) });
1166        // SAFETY: plain NSObject init.
1167        let source: Retained<Source> = unsafe { msg_send![super(source), init] };
1168
1169        let table: Retained<HostTableView> = unsafe { msg_send![HostTableView::alloc(mtm), init] };
1170        table.setStyle(NSTableViewStyle::FullWidth);
1171        table.setUsesAlternatingRowBackgroundColors(true);
1172        table.setAllowsMultipleSelection(true);
1173        table.setAllowsColumnReordering(true);
1174        table.setAllowsColumnResizing(true);
1175        add_columns(&table, &columns);
1176        let scroll = NSScrollView::new(mtm);
1177        scroll.setHasVerticalScroller(true);
1178        scroll.setHasHorizontalScroller(true);
1179        scroll.setAutohidesScrollers(true);
1180        scroll.setDocumentView(Some(&table));
1181
1182        let inner = Rc::new(Inner {
1183            id,
1184            columns: RefCell::new(columns),
1185            rows: RefCell::new(Vec::new()),
1186            order: RefCell::new(Vec::new()),
1187            groups: RefCell::new(Vec::new()),
1188            group_by: RefCell::new(None),
1189            sort: RefCell::new(None),
1190            sorts_in_place: Cell::new(true),
1191            events: RefCell::new(VecDeque::new()),
1192            quiet: Cell::new(false),
1193            mounted: Cell::new(false),
1194            transfer: RefCell::new(Transfer::default()),
1195            scroll,
1196            table: table.clone(),
1197            _source: source.clone(),
1198        });
1199        crate::testing::LIVE_MODELS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1200        let weak: Weak<dyn Data> = Rc::downgrade(&inner) as Weak<dyn Data>;
1201        *source.ivars().data.borrow_mut() = Some(weak);
1202        // SAFETY: the source is kept alive by the model (`_source`), and the
1203        // model removes the table when dropped.
1204        unsafe {
1205            table.setDataSource(Some(ProtocolObject::from_ref(&*source)));
1206            table.setDelegate(Some(ProtocolObject::from_ref(&*source)));
1207            table.setTarget(Some(&source));
1208            table.setDoubleAction(Some(sel!(activate:)));
1209        }
1210        Self { inner }
1211    }
1212
1213    /// The view id the table was created with.
1214    pub fn id(&self) -> ViewId {
1215        self.inner.id
1216    }
1217
1218    /// Adds the table to the attached window if it isn't yet. Called by the
1219    /// host widget before placing it.
1220    pub fn ensure_mounted(&self) {
1221        if !self.inner.mounted.get() && crate::is_attached() {
1222            crate::mount(self.inner.id, Retained::into_super(self.inner.scroll.clone()));
1223            self.inner.mounted.set(true);
1224        }
1225    }
1226
1227    /// Replaces the columns, keeping the same native table (a query
1228    /// browser's results change shape with every query). The sort is
1229    /// cleared. Call [`set_rows`](Self::set_rows) after it when the rows
1230    /// change too: nothing is drawn in between.
1231    pub fn set_columns(&self, columns: Vec<Column<T>>) {
1232        let table = &self.inner.table;
1233        *self.inner.sort.borrow_mut() = None;
1234        self.inner.quiet.set(true);
1235        table.setSortDescriptors(&NSArray::new());
1236        let old: Vec<_> = table.tableColumns().iter().collect();
1237        for column in old {
1238            table.removeTableColumn(&column);
1239        }
1240        add_columns(table, &columns);
1241        *self.inner.columns.borrow_mut() = columns;
1242        self.inner.compute_order();
1243        table.reloadData();
1244        self.inner.quiet.set(false);
1245    }
1246
1247    /// Replaces all rows (the current sort is applied). Clears the selection.
1248    pub fn set_rows(&self, rows: Vec<T>) {
1249        *self.inner.rows.borrow_mut() = rows;
1250        self.inner.compute_order();
1251        self.inner.quiet.set(true);
1252        self.inner.table.reloadData();
1253        // SAFETY: nil sender.
1254        unsafe { self.inner.table.deselectAll(None) };
1255        self.inner.quiet.set(false);
1256    }
1257
1258    /// The rows, in model order (unsorted).
1259    pub fn rows(&self) -> Ref<'_, Vec<T>> {
1260        self.inner.rows.borrow()
1261    }
1262
1263    /// Number of rows.
1264    pub fn len(&self) -> usize {
1265        self.inner.rows.borrow().len()
1266    }
1267
1268    /// Whether there are no rows.
1269    pub fn is_empty(&self) -> bool {
1270        self.len() == 0
1271    }
1272
1273    /// Replaces one row. Redraws only that row unless the table is sorted
1274    /// (then the order is recomputed; the selection is kept).
1275    pub fn update_row(&self, index: usize, row: T) {
1276        if let Some(slot) = self.inner.rows.borrow_mut().get_mut(index) {
1277            *slot = row;
1278        } else {
1279            return;
1280        }
1281        if self.inner.sort.borrow().is_some() && self.inner.sorts_in_place.get() {
1282            self.inner.resort_keeping_selection();
1283            return;
1284        }
1285        let Some(view_row) = self.inner.order.borrow().iter().position(|&m| m == index) else { return };
1286        let columns = NSIndexSet::indexSetWithIndexesInRange(objc2_foundation::NSRange::new(0, self.inner.columns.borrow().len()));
1287        self.inner.table.reloadDataForRowIndexes_columnIndexes(&NSIndexSet::indexSetWithIndex(view_row), &columns);
1288    }
1289
1290    /// Inserts a row at a model index (the selection is kept).
1291    pub fn insert(&self, index: usize, row: T) {
1292        let selected = self.inner.selection_model_rows();
1293        self.inner.rows.borrow_mut().insert(index, row);
1294        let selected: Vec<usize> = selected.into_iter().map(|r| if r >= index { r + 1 } else { r }).collect();
1295        self.inner.compute_order();
1296        self.inner.table.reloadData();
1297        self.inner.select_model_rows(&selected);
1298    }
1299
1300    /// Appends rows in one step, for live data (a log tail, a feed): when
1301    /// unsorted, the new rows are added to the end and AppKit only learns
1302    /// the new count (cost independent of the rows already there; the
1303    /// selection is kept). When sorted, the order is recomputed.
1304    pub fn append(&self, rows: Vec<T>) {
1305        if rows.is_empty() {
1306            return;
1307        }
1308        let start = self.len();
1309        self.inner.rows.borrow_mut().extend(rows);
1310        let grouped = self.inner.group_by.borrow().is_some();
1311        if grouped || (self.inner.sort.borrow().is_some() && self.inner.sorts_in_place.get()) {
1312            self.inner.resort_keeping_selection();
1313            return;
1314        }
1315        let end = self.len();
1316        self.inner.order.borrow_mut().extend(start..end);
1317        self.inner.table.noteNumberOfRowsChanged();
1318    }
1319
1320    /// Scrolls so the last row is visible.
1321    pub fn scroll_to_end(&self) {
1322        let n = self.inner.order.borrow().len();
1323        if n > 0 {
1324            self.inner.table.scrollRowToVisible((n - 1) as NSInteger);
1325        }
1326    }
1327
1328    /// Whether the table is scrolled to its last row (within one row), e.g.
1329    /// to keep following new rows only while the user hasn't scrolled up.
1330    pub fn is_at_end(&self) -> bool {
1331        let table = &self.inner.table;
1332        let visible = table.visibleRect();
1333        let bottom = visible.origin.y + visible.size.height;
1334        bottom >= table.bounds().size.height - table.rowHeight() - table.intercellSpacing().height - 1.0
1335    }
1336
1337    /// Appends a row.
1338    pub fn push(&self, row: T) {
1339        let len = self.len();
1340        self.insert(len, row);
1341    }
1342
1343    /// Removes a row (the selection is kept for the other rows).
1344    pub fn remove(&self, index: usize) -> Option<T> {
1345        if index >= self.len() {
1346            return None;
1347        }
1348        let selected = self.inner.selection_model_rows();
1349        let row = self.inner.rows.borrow_mut().remove(index);
1350        let selected: Vec<usize> =
1351            selected.into_iter().filter(|&r| r != index).map(|r| if r > index { r - 1 } else { r }).collect();
1352        self.inner.compute_order();
1353        self.inner.table.reloadData();
1354        self.inner.select_model_rows(&selected);
1355        Some(row)
1356    }
1357
1358    /// Moves `rows` (model indices) to just above the row `before` (or to
1359    /// the end), keeping their order, as a drop reported by
1360    /// [`TableEvent::RowsMoved`] asks. Returns their new model indices; they
1361    /// end up selected.
1362    pub fn move_rows(&self, rows: &[usize], before: Option<usize>) -> Vec<usize> {
1363        let mut moving: Vec<usize> = rows.iter().copied().filter(|&r| r < self.len()).collect();
1364        moving.sort_unstable();
1365        moving.dedup();
1366        let at = {
1367            let mut all = self.inner.rows.borrow_mut();
1368            let end = before.unwrap_or(all.len());
1369            // Rows staying put above the drop point.
1370            let at = (0..end.min(all.len())).filter(|r| moving.binary_search(r).is_err()).count();
1371            let mut taken = Vec::with_capacity(moving.len());
1372            for &r in moving.iter().rev() {
1373                taken.push(all.remove(r));
1374            }
1375            for (i, row) in taken.into_iter().rev().enumerate() {
1376                all.insert(at + i, row);
1377            }
1378            at
1379        };
1380        let moved: Vec<usize> = (at..at + moving.len()).collect();
1381        self.inner.compute_order();
1382        self.inner.table.reloadData();
1383        self.inner.select_model_rows(&moved);
1384        moved
1385    }
1386
1387    /// Lets rows be dragged out: each carries its cells as tab-separated
1388    /// text (for other apps), and its model index for
1389    /// [`set_reorderable`](Self::set_reorderable). Off by default (a drag
1390    /// then extends the selection).
1391    pub fn set_row_drag(&self, on: bool) {
1392        self.inner.transfer.borrow_mut().drag = on;
1393        self.inner.table.setDraggingSourceOperationMask_forLocal(NSDragOperation::Copy, false);
1394        self.register_drag_types();
1395    }
1396
1397    /// Lets the user drag rows to a new place (also turns on
1398    /// [`set_row_drag`](Self::set_row_drag)); each drop is reported as
1399    /// [`TableEvent::RowsMoved`]. Refused while the table is sorted.
1400    pub fn set_reorderable(&self, on: bool) {
1401        if on {
1402            self.set_row_drag(true);
1403            self.inner.table.setDraggingSourceOperationMask_forLocal(NSDragOperation::Move, true);
1404        }
1405        self.inner.transfer.borrow_mut().reorder = on;
1406        self.register_drag_types();
1407    }
1408
1409    /// Accepts files dropped from the Finder: `Some(&["csv", "txt"])` for
1410    /// those extensions, `Some(&[])` for any file, `None` to stop. Each drop
1411    /// is reported as [`TableEvent::FilesDropped`].
1412    pub fn set_file_drop(&self, extensions: Option<&[&str]>) {
1413        self.inner.transfer.borrow_mut().files = extensions.map(|e| e.iter().map(|s| s.to_string()).collect());
1414        self.register_drag_types();
1415    }
1416
1417    /// Reports ⌘V on the table as [`TableEvent::Paste`] (and enables Paste
1418    /// in the Edit menu while there is text to paste). Off by default.
1419    pub fn set_pastes(&self, on: bool) {
1420        self.inner.transfer.borrow_mut().pastes = on;
1421    }
1422
1423    fn register_drag_types(&self) {
1424        let t = self.inner.transfer.borrow();
1425        let mut types = Vec::new();
1426        if t.reorder {
1427            types.push(row_type());
1428        }
1429        if t.files.is_some() {
1430            // SAFETY: AppKit's pasteboard type constant.
1431            types.push(NSString::from_str(&unsafe { NSPasteboardTypeFileURL }.to_string()));
1432        }
1433        self.inner.table.unregisterDraggedTypes();
1434        if !types.is_empty() {
1435            self.inner.table.registerForDraggedTypes(&NSArray::from_retained_slice(&types));
1436        }
1437    }
1438
1439    /// The selected rows as tab-separated text (columns in their current
1440    /// order, one line per row, as ⌘C copies them).
1441    pub fn selected_text(&self) -> String {
1442        let rows = indexes(&self.inner.table.selectedRowIndexes());
1443        self.inner.rows_text(&rows, &column_ids(&self.inner.table))
1444    }
1445
1446    /// Copies the selected rows to `pasteboard` (what ⌘C does with the
1447    /// general pasteboard). False if nothing is selected.
1448    pub fn copy_to(&self, pasteboard: &NSPasteboard) -> bool {
1449        self.inner.table.copy_rows(pasteboard)
1450    }
1451
1452    /// Pastes `pasteboard`'s text (what ⌘V does with the general
1453    /// pasteboard): queues [`TableEvent::Paste`] if the table takes pastes.
1454    pub fn paste_from(&self, pasteboard: &NSPasteboard) -> bool {
1455        self.inner.table.paste_text(pasteboard)
1456    }
1457
1458    /// The model index of the row shown at `position` (0 = top row as
1459    /// currently sorted); `None` past the end or for a group header.
1460    pub fn row_at(&self, position: usize) -> Option<usize> {
1461        self.inner.model_row(position)
1462    }
1463
1464    /// Groups the rows under headers by `key` (e.g. a date or a category):
1465    /// groups appear in the order their first row has in the model, rows
1466    /// keep the sort's order within each group, and each group starts with
1467    /// a header row showing the key (full width, not selectable, floating
1468    /// while its rows scroll). `None` ungroups. Row indices in events stay
1469    /// model indices.
1470    pub fn set_group_by(&self, key: Option<GroupKey<T>>) {
1471        *self.inner.group_by.borrow_mut() = key;
1472        self.inner.table.setFloatsGroupRows(true);
1473        self.inner.resort_keeping_selection();
1474    }
1475
1476    /// The groups' titles, in the order shown (empty when not grouped).
1477    pub fn groups(&self) -> Vec<String> {
1478        self.inner.groups.borrow().clone()
1479    }
1480
1481    /// The number of rows shown, group headers included.
1482    pub fn shown_rows(&self) -> usize {
1483        self.inner.order.borrow().len()
1484    }
1485
1486    /// Selected rows (model indices, ascending in view order).
1487    pub fn selection(&self) -> Vec<usize> {
1488        self.inner.selection_model_rows()
1489    }
1490
1491    /// Selects rows by model index (emits no event).
1492    pub fn select(&self, rows: &[usize]) {
1493        self.inner.select_model_rows(rows);
1494        if let Some(&first) = rows.first()
1495            && let Some(view_row) = self.inner.order.borrow().iter().position(|&m| m == first)
1496        {
1497            self.inner.table.scrollRowToVisible(view_row as NSInteger);
1498        }
1499    }
1500
1501    /// The current sort, if any.
1502    pub fn sort(&self) -> Option<Sort> {
1503        self.inner.sort.borrow().clone()
1504    }
1505
1506    /// Sets the sort (shown in the header) and, with built-in sorting, applies it.
1507    pub fn set_sort(&self, sort: Option<Sort>) {
1508        let descriptors = match &sort {
1509            Some(s) => NSArray::from_retained_slice(&[NSSortDescriptor::sortDescriptorWithKey_ascending(
1510                Some(&NSString::from_str(&s.column)),
1511                s.ascending,
1512            )]),
1513            None => NSArray::new(),
1514        };
1515        *self.inner.sort.borrow_mut() = sort;
1516        // setSortDescriptors calls back sortDescriptorsDidChange; quiet the event.
1517        let events_before = self.inner.events.borrow().len();
1518        self.inner.table.setSortDescriptors(&descriptors);
1519        self.inner.events.borrow_mut().truncate(events_before);
1520        if self.inner.sorts_in_place.get() {
1521            self.inner.resort_keeping_selection();
1522        }
1523    }
1524
1525    /// Built-in sorting (default on): header clicks reorder the rows here.
1526    /// Turn it off to sort yourself on [`TableEvent::Sort`] (e.g. in a database)
1527    /// and call [`TableModel::set_rows`].
1528    pub fn set_sorts_in_place(&self, on: bool) {
1529        self.inner.sorts_in_place.set(on);
1530    }
1531
1532    /// Columns in their current order, with widths.
1533    pub fn column_state(&self) -> Vec<ColumnState> {
1534        self.inner
1535            .table
1536            .tableColumns()
1537            .iter()
1538            .map(|c| ColumnState { id: c.identifier().to_string(), width: c.width() })
1539            .collect()
1540    }
1541
1542    /// Restores a saved arrangement (unknown ids are ignored).
1543    pub fn set_column_state(&self, state: &[ColumnState]) {
1544        let table = &self.inner.table;
1545        for (target, s) in state.iter().enumerate() {
1546            let index = table.columnWithIdentifier(&NSString::from_str(&s.id));
1547            if index < 0 {
1548                continue;
1549            }
1550            if let Some(column) = table.tableColumns().iter().nth(index as usize) {
1551                column.setWidth(s.width);
1552            }
1553            if index as usize != target && target < table.numberOfColumns() as usize {
1554                table.moveColumn_toColumn(index, target as NSInteger);
1555            }
1556        }
1557        // moveColumn fires the delegate; this was the program, not the user.
1558        self.inner.events.borrow_mut().retain(|e| *e != TableEvent::ColumnsChanged);
1559    }
1560
1561    /// Takes the queued user events (for the host widget).
1562    pub fn drain_events(&self) -> Vec<TableEvent> {
1563        self.inner.events.borrow_mut().drain(..).collect()
1564    }
1565
1566    /// Diagnostics: cell views created so far (reuse keeps this near the
1567    /// number of visible cells).
1568    pub fn cells_created(&self) -> usize {
1569        self.inner._source.ivars().created.get()
1570    }
1571
1572    /// The `NSScrollView` holding the table, for hosts that place it
1573    /// themselves (no [`crate::attach`]ed window).
1574    pub fn scroll_view(&self) -> Retained<NSScrollView> {
1575        self.inner.scroll.clone()
1576    }
1577
1578    /// The underlying `NSTableView` (escape hatch).
1579    pub fn table_view(&self) -> Retained<NSTableView> {
1580        Retained::into_super(self.inner.table.clone())
1581    }
1582}
1583
1584#[cfg(test)]
1585mod tests {
1586    use super::natural_cmp;
1587    use std::cmp::Ordering::*;
1588
1589    #[test]
1590    fn key_matches_natural_order() {
1591        use super::natural_key;
1592        let words = ["Item 10", "item 9", "Item 009", "apple", "Banana", "x", "x1", "a2b", "a10b", "Zo", "zoe 2"];
1593        for a in words {
1594            for b in words {
1595                let by_key = natural_key(a).cmp(&natural_key(b));
1596                let by_cmp = natural_cmp(a, b);
1597                if by_cmp != std::cmp::Ordering::Equal {
1598                    assert_eq!(by_key, by_cmp, "{a:?} vs {b:?}");
1599                }
1600            }
1601        }
1602    }
1603
1604    #[test]
1605    fn natural_order() {
1606        assert_eq!(natural_cmp("Item 9", "Item 10"), Less);
1607        assert_eq!(natural_cmp("apple", "Banana"), Less);
1608        assert_eq!(natural_cmp("a2b", "a02b"), Equal);
1609        assert_eq!(natural_cmp("x", "x1"), Less);
1610    }
1611}