Skip to main content

ferrokit_core/
table.rs

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