Skip to main content

ferrokit_core/
table.rs

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