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