use std::cell::{Cell, Ref, RefCell};
use std::collections::VecDeque;
use std::rc::{Rc, Weak};
use objc2::rc::Retained;
use objc2::runtime::{AnyObject, NSObject, NSObjectProtocol, ProtocolObject};
use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel};
use objc2_app_kit::{
NSButton, NSControl, NSControlStateValueOff, NSControlStateValueOn, NSControlTextEditingDelegate, NSDragOperation,
NSDraggingInfo, NSEvent, NSLineBreakMode, NSMenuItem, NSPasteboard, NSPasteboardItem, NSPasteboardTypeFileURL, NSPasteboardTypeURL,
NSPasteboardTypeString, NSPasteboardTypeTabularText, NSPasteboardWriting, NSResponder, NSScrollView, NSTableColumn,
NSTableColumnResizingOptions, NSTableView, NSTableViewDataSource, NSTableViewDelegate, NSTableViewDropOperation,
NSTableViewStyle, NSTextAlignment, NSTextField, NSUserInterfaceItemIdentification, NSView, NSBezierPath, NSColor, NSTableRowView,
};
use objc2_foundation::{
NSArray, NSIndexSet, NSInteger, NSMutableIndexSet, NSNotification, NSRect, NSSortDescriptor, NSString, NSURL,
};
use crate::ViewId;
use crate::host::mtm;
use crate::kept::{UiCell, UiLocal};
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
Text(String),
Number(f64),
Bool(bool),
}
#[derive(Debug, Clone, PartialEq)]
enum Kind {
Text,
Number { decimals: usize },
Check,
Progress,
Date { time: bool, none: Option<std::rc::Rc<str>>, short: bool },
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum CellImage {
Symbol(String),
FileIcon(std::path::PathBuf),
Image(std::sync::Arc<[u8]>),
}
type IconFn<T> = Box<dyn Fn(&T) -> Option<CellImage>>;
type StyleFn<T> = Box<dyn Fn(&T) -> CellStyle>;
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct CellStyle {
pub color: Option<crate::text::Color>,
pub background: Option<crate::text::Color>,
pub italic: bool,
pub strikethrough: bool,
}
impl CellStyle {
pub fn new() -> Self {
Self::default()
}
pub fn color(mut self, color: impl Into<Option<crate::text::Color>>) -> Self {
self.color = color.into();
self
}
pub fn background(mut self, color: impl Into<Option<crate::text::Color>>) -> Self {
self.background = color.into();
self
}
pub fn italic(mut self, on: bool) -> Self {
self.italic = on;
self
}
pub fn strikethrough(mut self, on: bool) -> Self {
self.strikethrough = on;
self
}
}
pub type GroupKey<T> = Box<dyn Fn(&T) -> String>;
pub struct Column<T> {
id: String,
title: String,
width: f64,
min_width: f64,
kind: Kind,
sortable: bool,
editable: bool,
fit: bool,
icon: Option<IconFn<T>>,
icon_action: Option<String>,
style: Option<StyleFn<T>>,
value: Box<dyn Fn(&T) -> Value>,
}
impl<T> Column<T> {
fn new(id: &str, title: &str, kind: Kind, value: Box<dyn Fn(&T) -> Value>) -> Self {
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 }
}
pub fn text(id: &str, title: &str, value: impl Fn(&T) -> String + 'static) -> Self {
Self::new(id, title, Kind::Text, Box::new(move |row| Value::Text(value(row))))
}
pub fn number(id: &str, title: &str, value: impl Fn(&T) -> f64 + 'static) -> Self {
Self::new(id, title, Kind::Number { decimals: 0 }, Box::new(move |row| Value::Number(value(row))))
}
pub fn check(id: &str, title: &str, value: impl Fn(&T) -> bool + 'static) -> Self {
Self::new(id, title, Kind::Check, Box::new(move |row| Value::Bool(value(row)))).width(60.0)
}
pub fn progress(id: &str, title: &str, value: impl Fn(&T) -> f64 + 'static) -> Self {
Self::new(id, title, Kind::Progress, Box::new(move |row| Value::Number(value(row).clamp(0.0, 1.0)))).width(100.0)
}
pub fn date(id: &str, title: &str, value: impl Fn(&T) -> Option<std::time::SystemTime> + 'static) -> Self {
Self::new(
id,
title,
Kind::Date { time: false, none: None, short: false },
Box::new(move |row| {
let secs = value(row).map_or(f64::NEG_INFINITY, |t| match t.duration_since(std::time::UNIX_EPOCH) {
Ok(d) => d.as_secs_f64(),
Err(e) => -e.duration().as_secs_f64(),
});
Value::Number(secs)
}),
)
.width(150.0)
}
pub fn with_time(mut self) -> Self {
if let Kind::Date { time, .. } = &mut self.kind {
*time = true;
}
self
}
pub fn short_dates(mut self) -> Self {
if let Kind::Date { short, .. } = &mut self.kind {
*short = true;
}
self
}
pub fn none_text(mut self, text: &str) -> Self {
if let Kind::Date { none, .. } = &mut self.kind {
*none = Some(text.into());
}
self
}
pub fn icon(mut self, image: impl Fn(&T) -> Option<CellImage> + 'static) -> Self {
self.icon = Some(Box::new(image));
self
}
pub fn icon_action(mut self, label: &str) -> Self {
self.icon_action = Some(label.into());
self
}
pub fn style(mut self, style: impl Fn(&T) -> CellStyle + 'static) -> Self {
self.style = Some(Box::new(style));
self
}
pub fn fit(mut self) -> Self {
self.fit = true;
self
}
pub fn width(mut self, width: f64) -> Self {
self.width = width;
self
}
pub fn min_width(mut self, min_width: f64) -> Self {
self.min_width = min_width;
self
}
pub fn decimals(mut self, decimals: usize) -> Self {
if let Kind::Number { .. } = self.kind {
self.kind = Kind::Number { decimals };
}
self
}
pub fn editable(mut self, editable: bool) -> Self {
self.editable = editable;
self
}
pub fn sortable(mut self, sortable: bool) -> Self {
self.sortable = sortable;
self
}
}
fn display(kind: &Kind, value: &Value) -> String {
match (kind, value) {
(_, Value::Text(s)) => s.clone(),
(Kind::Date { none: Some(text), .. }, Value::Number(n)) if !n.is_finite() => text.to_string(),
(Kind::Date { time, short, .. }, Value::Number(n)) => format_date(*n, *time, *short),
(Kind::Number { .. }, Value::Number(n)) if n.is_nan() => String::new(),
(Kind::Number { decimals: 0 }, Value::Number(n)) => format!("{n:.0}"),
(Kind::Number { decimals }, Value::Number(n)) => format!("{n:.decimals$}").replacen('.', &decimal_separator(), 1),
(_, Value::Number(n)) => n.to_string(),
(_, Value::Bool(b)) => if *b { "Yes".into() } else { "No".into() },
}
}
thread_local! {
static DATE_FORMATS: UiCell<[Option<Retained<objc2_foundation::NSDateFormatter>>; 4]> = const { UiCell::new([None, None, None, None]) };
}
thread_local! {
static DECIMAL: UiCell<Option<String>> = const { UiCell::new(None) };
}
fn decimal_separator() -> String {
DECIMAL.with_borrow_mut(|d| d.get_or_insert_with(|| objc2_foundation::NSLocale::currentLocale().decimalSeparator().to_string()).clone())
}
fn format_date(secs: f64, time: bool, short: bool) -> String {
use objc2_foundation::{NSDate, NSDateFormatter, NSDateFormatterStyle};
if !secs.is_finite() {
return String::new();
}
let formatter = DATE_FORMATS.with_borrow_mut(|f| {
f[time as usize + 2 * short as usize]
.get_or_insert_with(|| {
let f = NSDateFormatter::new();
f.setDateStyle(if short { NSDateFormatterStyle::ShortStyle } else { NSDateFormatterStyle::MediumStyle });
f.setTimeStyle(if time { NSDateFormatterStyle::ShortStyle } else { NSDateFormatterStyle::NoStyle });
f.setDoesRelativeDateFormatting(!short);
f
})
.clone()
});
formatter.stringFromDate(&NSDate::dateWithTimeIntervalSince1970(secs)).to_string()
}
const ANIMATION: objc2_app_kit::NSTableViewAnimationOptions =
objc2_app_kit::NSTableViewAnimationOptions(objc2_app_kit::NSTableViewAnimationOptions::EffectFade.0 | objc2_app_kit::NSTableViewAnimationOptions::SlideDown.0);
const HEADER: usize = 1 << (usize::BITS - 1);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Sort {
pub column: String,
pub ascending: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ColumnState {
pub id: String,
pub width: f64,
}
#[doc(hidden)]
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum TableEvent {
Selection(Vec<usize>),
Activate(usize),
Sort(Sort),
Toggle {
row: usize,
column: String,
value: bool,
},
ColumnsChanged,
Edit {
row: usize,
column: String,
value: String,
},
RowsMoved {
rows: Vec<usize>,
before: Option<usize>,
},
FilesDropped {
paths: Vec<std::path::PathBuf>,
before: Option<usize>,
},
UrlsDropped {
urls: Vec<String>,
before: Option<usize>,
},
Paste(String),
Key {
key: TableKey,
rows: Vec<usize>,
},
FocusedColumn(Option<String>),
IconClicked {
row: usize,
column: String,
},
}
#[derive(Debug, Clone, Default)]
struct Transfer {
drag: bool,
reorder: bool,
keys: Vec<TableKey>,
files: Option<Vec<String>>,
urls: bool,
pastes: bool,
cell_focus: bool,
}
fn row_type() -> Retained<NSString> {
NSString::from_str("dev.ferrokit.table-row")
}
trait Data {
fn count(&self) -> usize;
fn cell(&self, view_row: usize, column: &str) -> Option<(Kind, Value)>;
fn editable(&self, column: &str) -> bool;
fn title(&self, column: &str) -> Option<String>;
fn model_row(&self, view_row: usize) -> Option<usize>;
fn sort_changed(&self, sort: Option<Sort>);
fn push(&self, event: TableEvent);
fn quiet(&self) -> bool;
fn transfer(&self) -> Transfer;
fn sorted(&self) -> bool;
fn rows_text(&self, view_rows: &[usize], columns: &[String]) -> String;
fn group_title(&self, view_row: usize) -> Option<String>;
fn icon(&self, view_row: usize, column: &str) -> Option<CellImage>;
fn has_icon(&self, column: &str) -> bool;
fn icon_action(&self, column: &str) -> Option<String>;
fn style(&self, view_row: usize, column: &str) -> Option<CellStyle>;
fn focus(&self) -> Option<String>;
fn set_focus(&self, column: Option<String>, report: bool);
}
struct SourceIvars {
data: RefCell<Option<Weak<dyn Data>>>,
created: Cell<usize>,
}
define_class!(
#[unsafe(super(NSObject))]
#[thread_kind = MainThreadOnly]
#[name = "FerrokitCoreTableSource"]
#[ivars = SourceIvars]
struct Source;
unsafe impl NSObjectProtocol for Source {}
unsafe impl NSControlTextEditingDelegate for Source {}
unsafe impl NSTableViewDataSource for Source {
#[unsafe(method(numberOfRowsInTableView:))]
fn number_of_rows(&self, _table: &NSTableView) -> NSInteger {
crate::boundary::guarded("a table (number_of_rows)", 0, || {
self.data().map_or(0, |d| d.count() as NSInteger)
})
}
#[unsafe(method(tableView:sortDescriptorsDidChange:))]
fn sort_descriptors_did_change(&self, table: &NSTableView, _old: &NSArray<NSSortDescriptor>) {
crate::boundary::guarded("a table (sort_descriptors_did_change)", (), || {
let sort = table.sortDescriptors().firstObject().and_then(|d| {
Some(Sort { column: d.key()?.to_string(), ascending: d.ascending() })
});
if let Some(data) = self.data() {
data.sort_changed(sort);
}
})
}
#[unsafe(method_id(tableView:pasteboardWriterForRow:))]
fn writer_for_row(&self, table: &NSTableView, row: NSInteger) -> Option<Retained<ProtocolObject<dyn NSPasteboardWriting>>> {
crate::boundary::guarded("a table (writer_for_row)", None, || {
self.row_writer(table, row)
})
}
#[unsafe(method(tableView:validateDrop:proposedRow:proposedDropOperation:))]
fn validate_drop(
&self,
table: &NSTableView,
info: &ProtocolObject<dyn NSDraggingInfo>,
row: NSInteger,
_operation: NSTableViewDropOperation,
) -> NSDragOperation {
crate::boundary::guarded("a table (validate_drop)", NSDragOperation::None, || {
let operation = match self.dropped(table, info) {
Some(Dropped::Rows(_)) => NSDragOperation::Move,
Some(Dropped::Files(_) | Dropped::Urls(_)) => NSDragOperation::Copy,
None => return NSDragOperation::None,
};
table.setDropRow_dropOperation(row, NSTableViewDropOperation::Above);
operation
})
}
#[unsafe(method(tableView:acceptDrop:row:dropOperation:))]
fn accept_drop(
&self,
table: &NSTableView,
info: &ProtocolObject<dyn NSDraggingInfo>,
row: NSInteger,
_operation: NSTableViewDropOperation,
) -> bool {
crate::boundary::guarded("a table (accept_drop)", false, || {
self.accept(table, info, row)
})
}
}
unsafe impl NSTableViewDelegate for Source {
#[unsafe(method_id(tableView:rowViewForRow:))]
fn row_view_for(&self, table: &NSTableView, _row: NSInteger) -> Option<Retained<NSTableRowView>> {
crate::boundary::guarded("a table (row_view_for)", None, || {
self.focus_row(table)
})
}
#[unsafe(method_id(tableView:viewForTableColumn:row:))]
fn view_for(&self, table: &NSTableView, column: Option<&NSTableColumn>, row: NSInteger) -> Option<Retained<NSView>> {
crate::boundary::guarded("a table (view_for)", None, || {
match column {
Some(column) => self.cell_view(table, column, row),
None => self.group_view(table, row),
}
})
}
#[unsafe(method(tableView:isGroupRow:))]
fn is_group_row(&self, _table: &NSTableView, row: NSInteger) -> bool {
crate::boundary::guarded("a table (is_group_row)", false, || {
self.data().is_some_and(|d| d.group_title(row as usize).is_some())
})
}
#[unsafe(method(tableView:shouldSelectRow:))]
fn should_select_row(&self, _table: &NSTableView, row: NSInteger) -> bool {
crate::boundary::guarded("a table (should_select_row)", false, || {
self.data().is_none_or(|d| d.group_title(row as usize).is_none())
})
}
#[unsafe(method(tableViewSelectionDidChange:))]
fn selection_did_change(&self, notification: &NSNotification) {
crate::boundary::guarded("a table (selection_did_change)", (), || {
let Some(data) = self.data() else { return };
if data.quiet() {
return;
}
let Some(table) = notification.object().and_then(|o| o.downcast::<NSTableView>().ok()) else { return };
let rows = indexes(&table.selectedRowIndexes()).into_iter().filter_map(|r| data.model_row(r)).collect();
data.push(TableEvent::Selection(rows));
})
}
#[unsafe(method_id(tableView:typeSelectStringForTableColumn:row:))]
fn type_select_string(&self, _table: &NSTableView, column: Option<&NSTableColumn>, row: NSInteger) -> Option<Retained<NSString>> {
crate::boundary::guarded("a table (type_select_string)", None, || {
self.cell_text(column, row)
})
}
#[unsafe(method(tableViewColumnDidMove:))]
fn column_did_move(&self, _notification: &NSNotification) {
crate::boundary::guarded("a table (column_did_move)", (), || {
if let Some(data) = self.data() {
data.push(TableEvent::ColumnsChanged);
}
})
}
#[unsafe(method(tableViewColumnDidResize:))]
fn column_did_resize(&self, _notification: &NSNotification) {
crate::boundary::guarded("a table (column_did_resize)", (), || {
if let Some(data) = self.data() {
data.push(TableEvent::ColumnsChanged);
}
})
}
}
impl Source {
#[unsafe(method(activate:))]
fn activate(&self, sender: &NSTableView) {
crate::boundary::guarded("a table (activate)", (), || {
let Some(data) = self.data() else { return };
let row = sender.clickedRow();
if let Some(row) = (row >= 0).then_some(row as usize).and_then(|r| data.model_row(r)) {
data.push(TableEvent::Activate(row));
}
})
}
#[unsafe(method(edit:))]
fn edit(&self, sender: &NSTextField) {
crate::boundary::guarded("a table (edit)", (), || {
let Some(data) = self.data() else { return };
let Some(table) = table_of(sender) else { return };
let row = table.rowForView(sender);
let Some(column) = sender.identifier().map(|i| i.to_string()) else { return };
let value = sender.stringValue().to_string();
let shown = (row >= 0).then(|| data.cell(row as usize, &column)).flatten().map(|(kind, v)| display(&kind, &v));
if shown.as_deref() == Some(value.as_str()) {
return;
}
if let Some(row) = (row >= 0).then_some(row as usize).and_then(|r| data.model_row(r)) {
data.push(TableEvent::Edit { row, column, value });
}
})
}
#[unsafe(method(iconClicked:))]
fn icon_clicked(&self, sender: &NSButton) {
crate::boundary::guarded("a table (icon clicked)", (), || {
let Some(data) = self.data() else { return };
let Some(table) = table_of(sender) else { return };
let row = table.rowForView(sender);
let Some(column) = sender.identifier().map(|i| i.to_string()) else { return };
if let Some(row) = (row >= 0).then_some(row as usize).and_then(|r| data.model_row(r)) {
data.push(TableEvent::IconClicked { row, column });
}
})
}
#[unsafe(method(toggle:))]
fn toggle(&self, sender: &NSButton) {
crate::boundary::guarded("a table (toggle)", (), || {
let Some(data) = self.data() else { return };
let Some(table) = table_of(sender) else { return };
let row = table.rowForView(sender);
let Some(column) = sender.identifier().map(|i| i.to_string()) else { return };
if let Some(row) = (row >= 0).then_some(row as usize).and_then(|r| data.model_row(r)) {
data.push(TableEvent::Toggle { row, column, value: sender.state() == NSControlStateValueOn });
}
})
}
}
);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum TableKey {
Delete,
Space,
}
impl TableKey {
fn of(event: &NSEvent) -> Option<TableKey> {
use objc2_app_kit::NSEventModifierFlags as F;
if event.modifierFlags().intersects(F::Command | F::Option | F::Control) {
return None;
}
match event.keyCode() {
51 | 117 => Some(TableKey::Delete),
49 => Some(TableKey::Space),
_ => None,
}
}
}
enum Dropped {
Rows(Vec<usize>),
Files(Vec<std::path::PathBuf>),
Urls(Vec<String>),
}
define_class!(
#[unsafe(super(NSTableView, NSControl, NSView, NSResponder, NSObject))]
#[thread_kind = MainThreadOnly]
#[name = "FerrokitCoreTableView"]
struct HostTableView;
impl HostTableView {
#[unsafe(method(keyDown:))]
fn key_down(&self, event: &NSEvent) {
crate::boundary::guarded("a table (key_down)", (), || {
if matches!(event.keyCode(), 36 | 76) {
let row = self.selectedRow();
let source = unsafe { self.dataSource() };
let source = source.and_then(|s| {
let any: &AnyObject = s.as_ref();
any.downcast_ref::<Source>().map(|s| s.retain())
});
if let (true, Some(source)) = (row >= 0, source) {
if let Some(data) = source.data()
&& let Some(row) = data.model_row(row as usize)
{
data.push(TableEvent::Activate(row));
}
return;
}
}
if matches!(event.keyCode(), 123 | 124) && self.move_focus(event) {
return;
}
if let Some(key) = TableKey::of(event)
&& let Some(data) = self.source().and_then(|s| s.data())
&& data.transfer().keys.contains(&key)
{
let rows: Vec<usize> = indexes(&self.selectedRowIndexes()).into_iter().filter_map(|r| data.model_row(r)).collect();
if !rows.is_empty() {
data.push(TableEvent::Key { key, rows });
return;
}
}
let () = unsafe { msg_send![super(self), keyDown: event] };
})
}
#[unsafe(method(mouseDown:))]
fn mouse_down(&self, event: &NSEvent) {
crate::boundary::guarded("a table (mouse_down)", (), || {
if let Some(data) = self.source().and_then(|s| s.data())
&& data.transfer().cell_focus
{
let point = self.convertPoint_fromView(event.locationInWindow(), None);
let column = self.columnAtPoint(point);
if column >= 0 && self.rowAtPoint(point) >= 0 {
let id = self.tableColumns().objectAtIndex(column as usize).identifier().to_string();
data.set_focus(Some(id), true);
}
}
let () = unsafe { msg_send![super(self), mouseDown: event] };
})
}
#[unsafe(method(copy:))]
fn copy(&self, _sender: Option<&AnyObject>) {
crate::boundary::guarded("a table (copy)", (), || {
self.copy_rows(&NSPasteboard::generalPasteboard());
})
}
#[unsafe(method(paste:))]
fn paste(&self, _sender: Option<&AnyObject>) {
crate::boundary::guarded("a table (paste)", (), || {
self.paste_text(&NSPasteboard::generalPasteboard());
})
}
#[unsafe(method(validateMenuItem:))]
fn validate_menu_item(&self, item: &NSMenuItem) -> bool {
crate::boundary::guarded("a table (validate_menu_item)", false, || {
let action = item.action();
if action == Some(sel!(copy:)) {
self.selectedRow() >= 0
} else if action == Some(sel!(paste:)) {
let pastes = self.source().and_then(|s| s.data()).is_some_and(|d| d.transfer().pastes);
pastes && NSPasteboard::generalPasteboard().stringForType(unsafe { NSPasteboardTypeString }).is_some()
} else {
true
}
})
}
}
);
impl HostTableView {
fn move_focus(&self, event: &NSEvent) -> bool {
use objc2_app_kit::NSEventModifierFlags as F;
let Some(data) = self.source().and_then(|s| s.data()) else { return false };
if !data.transfer().cell_focus || event.modifierFlags().intersects(F::Command | F::Option | F::Control | F::Shift) {
return false;
}
let ids = column_ids(self);
if ids.is_empty() {
return false;
}
let now = data.focus().and_then(|f| ids.iter().position(|i| *i == f));
let next = match (now, event.keyCode()) {
(None, _) => 0,
(Some(i), 123) => i.saturating_sub(1),
(Some(i), _) => (i + 1).min(ids.len() - 1),
};
self.scrollColumnToVisible(next as NSInteger);
data.set_focus(Some(ids[next].clone()), true);
true
}
fn source(&self) -> Option<Retained<Source>> {
let source = unsafe { self.dataSource() }?;
let any: &AnyObject = source.as_ref();
any.downcast_ref::<Source>().map(|s| s.retain())
}
fn copy_rows(&self, pasteboard: &NSPasteboard) -> bool {
let Some(data) = self.source().and_then(|s| s.data()) else { return false };
let rows = indexes(&self.selectedRowIndexes());
if rows.is_empty() {
return false;
}
let text = NSString::from_str(&data.rows_text(&rows, &column_ids(self)));
pasteboard.clearContents();
unsafe {
pasteboard.setString_forType(&text, NSPasteboardTypeString);
pasteboard.setString_forType(&text, NSPasteboardTypeTabularText);
}
true
}
fn paste_text(&self, pasteboard: &NSPasteboard) -> bool {
let Some(data) = self.source().and_then(|s| s.data()) else { return false };
let text = pasteboard.stringForType(unsafe { NSPasteboardTypeString });
match (data.transfer().pastes, text) {
(true, Some(text)) => {
data.push(TableEvent::Paste(text.to_string()));
true
}
_ => false,
}
}
}
define_class!(
#[unsafe(super(NSTableRowView, NSView, NSResponder, NSObject))]
#[thread_kind = MainThreadOnly]
#[name = "FerrokitFocusRowView"]
struct FocusRowView;
impl FocusRowView {
#[unsafe(method(drawSelectionInRect:))]
fn draw_selection(&self, rect: NSRect) {
crate::boundary::guarded("a table (draw_selection)", (), || {
let () = unsafe { msg_send![super(self), drawSelectionInRect: rect] };
let Some(cell) = self.focus_rect() else { return };
let path = NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(cell, 4.0, 4.0);
path.setLineWidth(1.5);
if self.isEmphasized() {
NSColor::whiteColor().colorWithAlphaComponent(0.18).setFill();
path.fill();
NSColor::whiteColor().setStroke();
} else {
NSColor::controlAccentColor().setStroke();
}
path.stroke();
})
}
}
);
impl FocusRowView {
fn focus_rect(&self) -> Option<NSRect> {
let table = unsafe { self.superview() }?.downcast::<HostTableView>().ok()?;
let focus = table.source()?.data()?.focus()?;
let column = table.columnWithIdentifier(&NSString::from_str(&focus));
if column < 0 {
return None;
}
let c = table.rectOfColumn(column);
let x = c.origin.x - self.frame().origin.x;
let h = self.bounds().size.height;
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))))
}
}
impl Source {
fn focus_row(&self, table: &NSTableView) -> Option<Retained<NSTableRowView>> {
if !self.data().is_some_and(|d| d.transfer().cell_focus) {
return None;
}
let id = NSString::from_str("FerrokitFocusRow");
let reused = unsafe { table.makeViewWithIdentifier_owner(&id, None) }.and_then(|v| v.downcast::<NSTableRowView>().ok());
Some(reused.unwrap_or_else(|| {
let row: Retained<FocusRowView> = unsafe { msg_send![FocusRowView::alloc(mtm()), init] };
row.setIdentifier(Some(&id));
Retained::into_super(row)
}))
}
}
fn redraw_selected_rows(table: &NSTableView) {
for row in indexes(&table.selectedRowIndexes()) {
if let Some(view) = table.rowViewAtRow_makeIfNecessary(row as NSInteger, false) {
view.setNeedsDisplay(true);
}
}
}
fn column_ids(table: &NSTableView) -> Vec<String> {
table.tableColumns().iter().map(|c| c.identifier().to_string()).collect()
}
use objc2::Message as _;
fn table_of(view: &NSView) -> Option<Retained<NSTableView>> {
let mut current = unsafe { view.superview() };
while let Some(v) = current {
if let Ok(table) = v.clone().downcast::<NSTableView>() {
return Some(table);
}
current = unsafe { v.superview() };
}
None
}
struct KeepFocus {
table: Retained<NSTableView>,
editing: bool,
}
impl KeepFocus {
fn new(table: &NSTableView) -> Self {
let editing = table.window().and_then(|w| w.firstResponder()).and_then(|r| r.downcast::<objc2_app_kit::NSText>().ok()).is_some_and(|editor| {
let field: Option<Retained<objc2::runtime::AnyObject>> = unsafe { objc2::msg_send![&*editor, delegate] };
field.and_then(|f| f.downcast::<NSView>().ok()).is_some_and(|f| f.isDescendantOf(table))
});
KeepFocus { table: table.retain(), editing }
}
}
impl Drop for KeepFocus {
fn drop(&mut self) {
if !self.editing {
return;
}
if let Some(window) = self.table.window() {
let lost = window.firstResponder().is_none_or(|r| std::ptr::eq(Retained::as_ptr(&r).cast::<u8>(), Retained::as_ptr(&window).cast::<u8>()));
if lost {
window.makeFirstResponder(Some(&self.table));
}
}
}
}
fn indexes(set: &NSIndexSet) -> Vec<usize> {
let mut out = Vec::with_capacity(set.count());
let mut i = set.firstIndex();
while i != usize::MAX && out.len() < set.count() {
out.push(i);
i = set.indexGreaterThanIndex(i);
}
out
}
impl Source {
fn cell_text(&self, column: Option<&NSTableColumn>, row: NSInteger) -> Option<Retained<NSString>> {
let (kind, value) = self.data()?.cell(row as usize, &column?.identifier().to_string())?;
Some(NSString::from_str(&display(&kind, &value)))
}
fn data(&self) -> Option<Rc<dyn Data>> {
self.ivars().data.borrow().as_ref().and_then(Weak::upgrade)
}
fn row_writer(&self, table: &NSTableView, row: NSInteger) -> Option<Retained<ProtocolObject<dyn NSPasteboardWriting>>> {
let data = self.data()?;
if !data.transfer().drag {
return None;
}
let model = data.model_row(usize::try_from(row).ok()?)?;
let item = NSPasteboardItem::new();
item.setString_forType(&NSString::from_str(&model.to_string()), &row_type());
let text = data.rows_text(&[row as usize], &column_ids(table));
item.setString_forType(&NSString::from_str(&text), unsafe { NSPasteboardTypeString });
Some(ProtocolObject::from_retained(item))
}
fn accept(&self, table: &NSTableView, info: &ProtocolObject<dyn NSDraggingInfo>, row: NSInteger) -> bool {
let Some(data) = self.data() else { return false };
let before = usize::try_from(row).ok().and_then(|r| data.model_row(r));
match self.dropped(table, info) {
Some(Dropped::Rows(rows)) => data.push(TableEvent::RowsMoved { rows, before }),
Some(Dropped::Files(paths)) => data.push(TableEvent::FilesDropped { paths, before }),
Some(Dropped::Urls(urls)) => data.push(TableEvent::UrlsDropped { urls, before }),
None => return false,
}
true
}
fn dropped(&self, table: &NSTableView, info: &ProtocolObject<dyn NSDraggingInfo>) -> Option<Dropped> {
let data = self.data()?;
let transfer = data.transfer();
let items = info.draggingPasteboard().pasteboardItems()?;
let own = info.draggingSource().is_some_and(|s| std::ptr::eq(&*s as *const AnyObject, table as *const NSTableView as *const AnyObject));
if own {
if !transfer.reorder || data.sorted() {
return None;
}
let rows: Vec<usize> = items.iter().filter_map(|i| i.stringForType(&row_type())?.to_string().parse().ok()).collect();
return (!rows.is_empty()).then_some(Dropped::Rows(rows));
}
let urls: Vec<String> = items
.iter()
.filter(|i| i.stringForType(unsafe { NSPasteboardTypeFileURL }).is_none())
.filter_map(|i| i.stringForType(unsafe { NSPasteboardTypeURL }).map(|u| u.to_string()))
.collect();
if transfer.urls && !urls.is_empty() {
return Some(Dropped::Urls(urls));
}
let extensions = transfer.files?;
let paths: Vec<std::path::PathBuf> = items
.iter()
.filter_map(|i| i.stringForType(unsafe { NSPasteboardTypeFileURL }))
.filter_map(|u| NSURL::URLWithString(&u)?.path().map(|p| std::path::PathBuf::from(p.to_string())))
.collect();
let accepted = |p: &std::path::PathBuf| {
extensions.is_empty()
|| p.extension().and_then(|e| e.to_str()).is_some_and(|e| extensions.iter().any(|x| x.eq_ignore_ascii_case(e)))
};
(!paths.is_empty() && paths.iter().all(accepted)).then_some(Dropped::Files(paths))
}
fn group_view(&self, table: &NSTableView, row: NSInteger) -> Option<Retained<NSView>> {
let title = self.data()?.group_title(row as usize)?;
let ident = NSString::from_str("ferrokit-core.group");
let field = match unsafe { table.makeViewWithIdentifier_owner(&ident, None) }.and_then(|v| v.downcast::<NSTextField>().ok()) {
Some(f) => f,
None => {
let f = NSTextField::labelWithString(&NSString::new(), MainThreadMarker::from(self));
f.setIdentifier(Some(&ident));
f.setFont(Some(&objc2_app_kit::NSFont::boldSystemFontOfSize(objc2_app_kit::NSFont::smallSystemFontSize())));
f.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
f
}
};
field.setStringValue(&NSString::from_str(&title));
Some(Retained::into_super(Retained::into_super(field)))
}
fn progress_view(&self, table: &NSTableView, ident: &NSString, value: f64) -> Retained<NSView> {
use objc2_app_kit::{NSProgressIndicator, NSProgressIndicatorStyle, NSTableCellView};
let mtm = MainThreadMarker::from(self);
let cell = match unsafe { table.makeViewWithIdentifier_owner(ident, None) }.and_then(|v| v.downcast::<NSTableCellView>().ok()) {
Some(c) => c,
None => {
self.ivars().created.set(self.ivars().created.get() + 1);
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)));
c.setIdentifier(Some(ident));
let bar = NSProgressIndicator::new(mtm);
bar.setStyle(NSProgressIndicatorStyle::Bar);
bar.setIndeterminate(false);
bar.setMinValue(0.0);
bar.setMaxValue(1.0);
bar.setControlSize(objc2_app_kit::NSControlSize::Small);
bar.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable | objc2_app_kit::NSAutoresizingMaskOptions::ViewMinYMargin | objc2_app_kit::NSAutoresizingMaskOptions::ViewMaxYMargin);
bar.setFrame(objc2_foundation::NSRect::new(objc2_foundation::NSPoint::new(2.0, 2.0), objc2_foundation::NSSize::new(96.0, 12.0)));
c.addSubview(&bar);
if let Some(title) = self.data().and_then(|d| d.title(&ident.to_string())) {
let () = unsafe { msg_send![&*bar, setAccessibilityLabel: &*NSString::from_str(&title)] };
}
c
}
};
if let Some(bar) = cell.subviews().iter().find_map(|v| v.downcast::<objc2_app_kit::NSProgressIndicator>().ok()) {
bar.setDoubleValue(value);
}
Retained::into_super(cell)
}
fn cell_view(&self, table: &NSTableView, column: &NSTableColumn, row: NSInteger) -> Option<Retained<NSView>> {
let ident = column.identifier();
let (kind, value) = self.data()?.cell(row as usize, &ident.to_string())?;
let mtm = MainThreadMarker::from(self);
if kind == Kind::Progress {
let v = if let Value::Number(n) = value { n } else { 0.0 };
return Some(self.progress_view(table, &ident, v));
}
if self.data().is_some_and(|d| d.has_icon(&ident.to_string())) {
return Some(self.icon_view(table, &ident, kind, &value, row));
}
let reused = unsafe { table.makeViewWithIdentifier_owner(&ident, None) };
if kind == Kind::Check {
let button = match reused.and_then(|v| v.downcast::<NSButton>().ok()) {
Some(b) => b,
None => {
self.ivars().created.set(self.ivars().created.get() + 1);
let b = unsafe { NSButton::checkboxWithTitle_target_action(&NSString::new(), Some(self), Some(sel!(toggle:)), mtm) };
b.setIdentifier(Some(&ident));
if let Some(title) = self.data().and_then(|d| d.title(&ident.to_string())) {
let title = NSString::from_str(&title);
b.setTitle(&title);
b.setImagePosition(objc2_app_kit::NSCellImagePosition::ImageOnly);
unsafe {
let () = msg_send![&*b, setAccessibilityLabel: &*title];
let cell: Option<Retained<AnyObject>> = msg_send![&*b, cell];
if let Some(cell) = cell {
let () = msg_send![&*cell, setAccessibilityLabel: &*title];
}
}
}
b
}
};
button.setState(if value == Value::Bool(true) { NSControlStateValueOn } else { NSControlStateValueOff });
return Some(Retained::into_super(Retained::into_super(button)));
}
let field = match reused.and_then(|v| v.downcast::<NSTextField>().ok()) {
Some(f) => f,
None => {
self.ivars().created.set(self.ivars().created.get() + 1);
let f = NSTextField::labelWithString(&NSString::new(), mtm);
f.setIdentifier(Some(&ident));
f.setLineBreakMode(NSLineBreakMode::ByTruncatingTail);
if self.data().is_some_and(|d| d.editable(&ident.to_string())) {
f.setEditable(true);
f.setSelectable(true);
if let Some(cell) = f.cell() {
cell.setSendsActionOnEndEditing(true);
}
unsafe {
f.setTarget(Some(self));
f.setAction(Some(sel!(edit:)));
}
let title = column.title();
let () = unsafe { msg_send![&*f, setAccessibilityLabel: &*title] };
}
f
}
};
field.setAlignment(if let Kind::Number { .. } = kind { NSTextAlignment::Right } else { NSTextAlignment::Natural });
let style = self.data().and_then(|d| d.style(row as usize, &ident.to_string()));
Self::show_text(&field, &display(&kind, &value), style.as_ref());
Some(Retained::into_super(Retained::into_super(field)))
}
fn show_text(field: &NSTextField, text: &str, style: Option<&CellStyle>) {
use objc2_app_kit::{NSColor, NSFont, NSFontManager, NSFontTraitMask};
let size = NSFont::systemFontSize();
let font = match style {
Some(s) if s.italic => NSFontManager::sharedFontManager(MainThreadMarker::from(field)).convertFont_toHaveTrait(&NSFont::systemFontOfSize(size), NSFontTraitMask::ItalicFontMask),
_ => NSFont::systemFontOfSize(size),
};
let color = style.and_then(|s| s.color).map_or_else(NSColor::labelColor, |c| c.ns());
field.setFont(Some(&font));
field.setTextColor(Some(&color));
match style.and_then(|s| s.background) {
Some(bg) => {
field.setDrawsBackground(true);
field.setBackgroundColor(Some(&bg.ns()));
}
None => field.setDrawsBackground(false),
}
if style.is_some_and(|s| s.strikethrough) {
use objc2_app_kit::{NSFontAttributeName, NSForegroundColorAttributeName, NSStrikethroughStyleAttributeName};
use objc2_foundation::{NSAttributedString, NSDictionary, NSNumber};
let one = NSNumber::new_isize(1);
let attrs = unsafe {
NSDictionary::<NSString, objc2::runtime::AnyObject>::from_slices(
&[NSStrikethroughStyleAttributeName, NSForegroundColorAttributeName, NSFontAttributeName],
&[&*one as &objc2::runtime::AnyObject, &*color as &objc2::runtime::AnyObject, &*font as &objc2::runtime::AnyObject],
)
};
let text = unsafe { NSAttributedString::new_with_attributes(&NSString::from_str(text), &attrs) };
field.setAttributedStringValue(&text);
} else {
field.setStringValue(&NSString::from_str(text));
}
}
fn icon_view(&self, table: &NSTableView, ident: &NSString, kind: Kind, value: &Value, row: NSInteger) -> Retained<NSView> {
use objc2_app_kit::{NSImageView, NSTableCellView};
let mtm = MainThreadMarker::from(self);
let cell = match unsafe { table.makeViewWithIdentifier_owner(ident, None) }.and_then(|v| v.downcast::<NSTableCellView>().ok()) {
Some(c) => c,
None => {
self.ivars().created.set(self.ivars().created.get() + 1);
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)));
c.setIdentifier(Some(ident));
let action = self.data().and_then(|d| d.icon_action(&ident.to_string()));
if let Some(label) = action {
let b = unsafe { NSButton::buttonWithImage_target_action(&objc2_app_kit::NSImage::new(), Some(self), Some(sel!(iconClicked:)), mtm) };
b.setBordered(false);
b.setImagePosition(objc2_app_kit::NSCellImagePosition::ImageOnly);
b.setImageScaling(objc2_app_kit::NSImageScaling::ScaleProportionallyDown);
b.setIdentifier(Some(ident));
let () = unsafe { msg_send![&*b, setAccessibilityLabel: &*NSString::from_str(&label)] };
b.setFrame(objc2_foundation::NSRect::new(objc2_foundation::NSPoint::new(2.0, 0.5), objc2_foundation::NSSize::new(16.0, 16.0)));
b.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewMinYMargin);
c.addSubview(&b);
}
let image = NSImageView::new(mtm);
image.setFrame(objc2_foundation::NSRect::new(objc2_foundation::NSPoint::new(2.0, 0.5), objc2_foundation::NSSize::new(16.0, 16.0)));
image.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewMinYMargin);
unsafe {
let () = msg_send![&*image, setAccessibilityElement: false];
if let Some(cell) = image.cell() {
let () = msg_send![&*cell, setAccessibilityElement: false];
}
}
let text = NSTextField::labelWithString(&NSString::new(), mtm);
text.setLineBreakMode(NSLineBreakMode::ByTruncatingTail);
text.setFrame(objc2_foundation::NSRect::new(objc2_foundation::NSPoint::new(22.0, 0.0), objc2_foundation::NSSize::new(100.0, 17.0)));
text.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable | objc2_app_kit::NSAutoresizingMaskOptions::ViewMinYMargin);
if let Kind::Number { .. } = kind {
text.setAlignment(NSTextAlignment::Right);
}
c.addSubview(&image);
c.addSubview(&text);
unsafe {
c.setImageView(Some(&image));
c.setTextField(Some(&text));
}
c
}
};
let image = self.data().and_then(|d| d.icon(row as usize, &ident.to_string())).and_then(|i| match i {
CellImage::Symbol(name) => objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(&NSString::from_str(&name), None),
CellImage::FileIcon(path) => Some(objc2_app_kit::NSWorkspace::sharedWorkspace().iconForFile(&NSString::from_str(&path.to_string_lossy()))),
CellImage::Image(bytes) => objc2_app_kit::NSImage::initWithData(<objc2_app_kit::NSImage as objc2::AnyThread>::alloc(), &objc2_foundation::NSData::with_bytes(&bytes)),
});
let button = cell.subviews().iter().find_map(|v| v.downcast::<NSButton>().ok());
if let Some(b) = &button {
b.setImage(image.as_deref());
b.setHidden(image.is_none());
}
if let Some(iv) = unsafe { cell.imageView() } {
iv.setImage(if button.is_some() { None } else { image.as_deref() });
}
if let Some(tf) = unsafe { cell.textField() } {
let style = self.data().and_then(|d| d.style(row as usize, &ident.to_string()));
Self::show_text(&tf, &display(&kind, value), style.as_ref());
}
Retained::into_super(cell)
}
}
struct Inner<T: 'static> {
id: ViewId,
columns: RefCell<Vec<Column<T>>>,
rows: RefCell<Vec<T>>,
order: RefCell<Vec<usize>>,
groups: RefCell<Vec<String>>,
group_by: RefCell<Option<GroupKey<T>>>,
sort: RefCell<Option<Sort>>,
sorts_in_place: Cell<bool>,
animates: Cell<bool>,
events: RefCell<VecDeque<TableEvent>>,
quiet: Cell<bool>,
mounted: Cell<bool>,
transfer: RefCell<Transfer>,
focus: RefCell<Option<String>>,
scroll: Retained<NSScrollView>,
table: Retained<HostTableView>,
_source: Retained<Source>,
}
impl<T: 'static> Data for Inner<T> {
fn count(&self) -> usize {
self.order.borrow().len()
}
fn cell(&self, view_row: usize, column: &str) -> Option<(Kind, Value)> {
let columns = self.columns.borrow();
let column = columns.iter().find(|c| c.id == column)?;
let index = self.model_row(view_row)?;
let rows = self.rows.borrow();
Some((column.kind.clone(), (column.value)(rows.get(index)?)))
}
fn model_row(&self, view_row: usize) -> Option<usize> {
self.order.borrow().get(view_row).copied().filter(|m| m & HEADER == 0)
}
fn group_title(&self, view_row: usize) -> Option<String> {
let slot = *self.order.borrow().get(view_row)?;
(slot & HEADER != 0).then(|| self.groups.borrow().get(slot & !HEADER).cloned()).flatten()
}
fn icon(&self, view_row: usize, column: &str) -> Option<CellImage> {
let columns = self.columns.borrow();
let column = columns.iter().find(|c| c.id == column)?;
let index = self.model_row(view_row)?;
let rows = self.rows.borrow();
column.icon.as_ref().and_then(|f| f(rows.get(index)?))
}
fn has_icon(&self, column: &str) -> bool {
self.columns.borrow().iter().any(|c| c.id == column && c.icon.is_some())
}
fn icon_action(&self, column: &str) -> Option<String> {
self.columns.borrow().iter().find(|c| c.id == column).and_then(|c| c.icon_action.clone())
}
fn style(&self, view_row: usize, column: &str) -> Option<CellStyle> {
let columns = self.columns.borrow();
let column = columns.iter().find(|c| c.id == column)?;
let index = self.model_row(view_row)?;
let rows = self.rows.borrow();
column.style.as_ref().map(|f| f(&rows[index]))
}
fn editable(&self, column: &str) -> bool {
self.columns.borrow().iter().any(|c| c.id == column && c.editable && c.kind != Kind::Check && !matches!(c.kind, Kind::Date { .. }))
}
fn title(&self, column: &str) -> Option<String> {
self.columns.borrow().iter().find(|c| c.id == column).map(|c| c.title.clone())
}
fn sort_changed(&self, sort: Option<Sort>) {
*self.sort.borrow_mut() = sort.clone();
if self.sorts_in_place.get() {
self.resort_keeping_selection();
}
if let Some(sort) = sort {
self.push(TableEvent::Sort(sort));
}
}
fn push(&self, event: TableEvent) {
let mut events = self.events.borrow_mut();
if event == TableEvent::ColumnsChanged && events.back() == Some(&TableEvent::ColumnsChanged) {
return;
}
events.push_back(event);
drop(events);
crate::request_redraw();
}
fn quiet(&self) -> bool {
self.quiet.get()
}
fn transfer(&self) -> Transfer {
self.transfer.borrow().clone()
}
fn focus(&self) -> Option<String> {
self.focus.borrow().clone()
}
fn set_focus(&self, column: Option<String>, report: bool) {
if *self.focus.borrow() == column {
return;
}
*self.focus.borrow_mut() = column.clone();
redraw_selected_rows(&self.table);
if report {
self.push(TableEvent::FocusedColumn(column));
}
}
fn sorted(&self) -> bool {
self.sort.borrow().is_some()
}
fn rows_text(&self, view_rows: &[usize], columns: &[String]) -> String {
let all = self.columns.borrow();
let columns: Vec<&Column<T>> = columns.iter().filter_map(|id| all.iter().find(|c| &c.id == id)).collect();
let order = self.order.borrow();
let rows = self.rows.borrow();
let clean = |s: String| s.replace(['\t', '\n', '\r'], " ");
view_rows
.iter()
.filter_map(|&r| rows.get(*order.get(r)?))
.map(|row| columns.iter().map(|c| clean(display(&c.kind, &(c.value)(row)))).collect::<Vec<_>>().join("\t"))
.collect::<Vec<_>>()
.join("\n")
}
}
impl<T: 'static> Inner<T> {
fn compute_order(&self) {
let rows = self.rows.borrow();
let mut order: Vec<usize> = (0..rows.len()).collect();
let sort = self.sort.borrow().clone().filter(|_| self.sorts_in_place.get());
let columns = self.columns.borrow();
if let Some(column) = sort.as_ref().and_then(|s| columns.iter().find(|c| c.id == s.column)) {
enum Key {
Number(f64),
Text(String),
}
let keys: Vec<Key> = rows
.iter()
.map(|r| match (column.value)(r) {
Value::Number(n) => Key::Number(n),
Value::Bool(b) => Key::Number(b as u8 as f64),
Value::Text(t) => Key::Text(natural_key(&t)),
})
.collect();
order.sort_by(|a, b| match (&keys[*a], &keys[*b]) {
(Key::Number(x), Key::Number(y)) => x.total_cmp(y),
(Key::Text(x), Key::Text(y)) => x.cmp(y),
(Key::Number(_), Key::Text(_)) => std::cmp::Ordering::Less,
(Key::Text(_), Key::Number(_)) => std::cmp::Ordering::Greater,
});
if sort.is_some_and(|s| !s.ascending) {
order.reverse();
}
}
let mut groups = Vec::new();
if let Some(key) = self.group_by.borrow().as_ref() {
let keys: Vec<String> = rows.iter().map(key).collect();
let mut index_of: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
for k in &keys {
if !index_of.contains_key(k.as_str()) {
index_of.insert(k, groups.len());
groups.push(k.clone());
}
}
let mut buckets: Vec<Vec<usize>> = vec![Vec::new(); groups.len()];
for &m in &order {
buckets[index_of[keys[m].as_str()]].push(m);
}
order = buckets.into_iter().enumerate().flat_map(|(g, rows)| std::iter::once(HEADER | g).chain(rows)).collect();
}
drop(rows);
*self.groups.borrow_mut() = groups;
*self.order.borrow_mut() = order;
self.fit_columns();
}
fn fit_columns(&self) {
let rows = self.rows.borrow();
for column in self.columns.borrow().iter().filter(|c| c.fit) {
let Some(native) = self.table.tableColumnWithIdentifier(&NSString::from_str(&column.id)) else { continue };
const SAMPLE: usize = 2_000;
let n = rows.len();
let mut texts: Vec<String> = if n > SAMPLE {
(0..SAMPLE).map(|k| display(&column.kind, &(column.value)(&rows[k * n / SAMPLE]))).collect()
} else {
rows.iter().map(|r| display(&column.kind, &(column.value)(r))).collect()
};
if texts.len() > 64 {
texts.sort_by_key(|t| std::cmp::Reverse(t.chars().count()));
texts.truncate(64);
}
let font = objc2_app_kit::NSFont::systemFontOfSize(objc2_app_kit::NSFont::systemFontSize());
let attrs = objc2_foundation::NSDictionary::from_retained_objects(
&[unsafe { objc2_app_kit::NSFontAttributeName }],
&[Retained::into_super(Retained::into_super(font)) as Retained<AnyObject>],
);
let width = |s: &str| unsafe { objc2_app_kit::NSStringDrawing::sizeWithAttributes(&*NSString::from_str(s), Some(&attrs)).width };
let widest = texts.iter().map(|t| width(t)).fold(width(&column.title) + 16.0, f64::max);
let icon = if column.icon.is_some() { 22.0 } else { 0.0 };
native.setWidth((widest + icon + 12.0).ceil().max(column.min_width));
}
}
fn selection_model_rows(&self) -> Vec<usize> {
let order = self.order.borrow();
indexes(&self.table.selectedRowIndexes()).into_iter().filter_map(|r| order.get(r).copied()).filter(|m| m & HEADER == 0).collect()
}
fn select_model_rows(&self, rows: &[usize]) {
let order = self.order.borrow();
let mut position = vec![usize::MAX; self.rows.borrow().len()];
for (view, &model) in order.iter().enumerate() {
if model & HEADER == 0 {
position[model] = view;
}
}
drop(order);
let set = NSMutableIndexSet::new();
for &r in rows {
if let Some(&p) = position.get(r).filter(|p| **p != usize::MAX) {
set.addIndex(p);
}
}
self.quiet.set(true);
self.table.selectRowIndexes_byExtendingSelection(&set, false);
self.quiet.set(false);
}
fn animated_position(&self, index: usize) -> Option<usize> {
if !self.animates.get() || self.group_by.borrow().is_some() || self.table.window().is_none() {
return None;
}
self.order.borrow().iter().position(|&m| m == index)
}
fn resort_keeping_selection(&self) {
let _focus = KeepFocus::new(&self.table);
let selected = self.selection_model_rows();
self.compute_order();
self.table.reloadData();
self.select_model_rows(&selected);
}
}
impl<T: 'static> Drop for Inner<T> {
fn drop(&mut self) {
unsafe {
self.table.setDataSource(None);
self.table.setDelegate(None);
self.table.setTarget(None);
self.table.setDoubleAction(None);
}
if self.mounted.get() {
crate::unmount(self.id);
}
crate::testing::LIVE_MODELS.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
}
}
impl Drop for SourceIvars {
fn drop(&mut self) {
crate::testing::LIVE_OBJC.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
}
}
fn natural_key(s: &str) -> String {
let mut key = String::with_capacity(s.len() + 4);
let mut chars = s.chars().peekable();
while let Some(c) = chars.next() {
if c.is_ascii_digit() {
let mut digits = String::from(c);
while let Some(d) = chars.peek().filter(|d| d.is_ascii_digit()) {
digits.push(*d);
chars.next();
}
let trimmed = digits.trim_start_matches('0');
key.push('\u{1}');
key.push(char::from_u32(0x30 + trimmed.len() as u32).unwrap_or('~'));
key.push_str(trimmed);
} else {
key.extend(c.to_lowercase());
}
}
key
}
#[cfg(test)]
fn natural_cmp(a: &str, b: &str) -> std::cmp::Ordering {
use std::cmp::Ordering;
let (mut a, mut b) = (a.chars().peekable(), b.chars().peekable());
loop {
match (a.peek(), b.peek()) {
(None, None) => return Ordering::Equal,
(None, _) => return Ordering::Less,
(_, None) => return Ordering::Greater,
(Some(x), Some(y)) if x.is_ascii_digit() && y.is_ascii_digit() => {
let take = |it: &mut std::iter::Peekable<std::str::Chars>| {
let mut n = String::new();
while let Some(c) = it.peek().filter(|c| c.is_ascii_digit()) {
n.push(*c);
it.next();
}
n
};
let (x, y) = (take(&mut a), take(&mut b));
let (xt, yt) = (x.trim_start_matches('0'), y.trim_start_matches('0'));
let o = xt.len().cmp(&yt.len()).then_with(|| xt.cmp(yt));
if o != Ordering::Equal {
return o;
}
}
(Some(x), Some(y)) => {
let o = x.to_lowercase().cmp(y.to_lowercase());
if o != Ordering::Equal {
return o;
}
a.next();
b.next();
}
}
}
}
fn add_columns<T>(table: &NSTableView, columns: &[Column<T>]) {
for c in columns {
let column = NSTableColumn::initWithIdentifier(NSTableColumn::alloc(mtm()), &NSString::from_str(&c.id));
column.setTitle(&NSString::from_str(&c.title));
column.setWidth(c.width);
column.setMinWidth(c.min_width);
column.setResizingMask(NSTableColumnResizingOptions::UserResizingMask | NSTableColumnResizingOptions::AutoresizingMask);
if c.sortable {
let descriptor = NSSortDescriptor::sortDescriptorWithKey_ascending(Some(&NSString::from_str(&c.id)), true);
column.setSortDescriptorPrototype(Some(&descriptor));
}
table.addTableColumn(&column);
}
}
pub struct TableModel<T: 'static> {
inner: Rc<Inner<T>>,
}
impl<T: 'static> Clone for TableModel<T> {
fn clone(&self) -> Self {
Self { inner: self.inner.clone() }
}
}
impl<T: 'static> std::fmt::Debug for TableModel<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "TableModel({:?}, {} rows)", self.inner.id, self.inner.rows.borrow().len())
}
}
impl<T: 'static> TableModel<T> {
pub fn new(columns: Vec<Column<T>>) -> Self {
Self::with_id(ViewId::next(), columns)
}
fn with_id(id: ViewId, columns: Vec<Column<T>>) -> Self {
let mtm = mtm();
crate::testing::LIVE_OBJC.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let source = Source::alloc(mtm).set_ivars(SourceIvars { data: RefCell::new(None), created: Cell::new(0) });
let source: Retained<Source> = unsafe { msg_send![super(source), init] };
let table: Retained<HostTableView> = unsafe { msg_send![HostTableView::alloc(mtm), init] };
table.setStyle(NSTableViewStyle::FullWidth);
table.setUsesAlternatingRowBackgroundColors(true);
table.setAllowsMultipleSelection(true);
table.setAllowsColumnReordering(true);
table.setAllowsColumnResizing(true);
table.setColumnAutoresizingStyle(objc2_app_kit::NSTableViewColumnAutoresizingStyle::LastColumnOnlyAutoresizingStyle);
add_columns(&table, &columns);
let scroll = NSScrollView::new(mtm);
scroll.setHasVerticalScroller(true);
scroll.setHasHorizontalScroller(true);
scroll.setAutohidesScrollers(true);
scroll.setDocumentView(Some(&table));
let inner = Rc::new(Inner {
id,
columns: RefCell::new(columns),
rows: RefCell::new(Vec::new()),
order: RefCell::new(Vec::new()),
animates: Cell::new(false),
groups: RefCell::new(Vec::new()),
group_by: RefCell::new(None),
sort: RefCell::new(None),
sorts_in_place: Cell::new(true),
events: RefCell::new(VecDeque::new()),
quiet: Cell::new(false),
mounted: Cell::new(false),
transfer: RefCell::new(Transfer::default()),
focus: RefCell::new(None),
scroll,
table: table.clone(),
_source: source.clone(),
});
crate::testing::LIVE_MODELS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let weak: Weak<dyn Data> = Rc::downgrade(&inner) as Weak<dyn Data>;
*source.ivars().data.borrow_mut() = Some(weak);
unsafe {
table.setDataSource(Some(ProtocolObject::from_ref(&*source)));
table.setDelegate(Some(ProtocolObject::from_ref(&*source)));
table.setTarget(Some(&source));
table.setDoubleAction(Some(sel!(activate:)));
}
Self { inner }
}
pub fn id(&self) -> ViewId {
self.inner.id
}
#[doc(hidden)]
pub fn ensure_mounted(&self) {
if !self.inner.mounted.get() && crate::is_attached() {
crate::mount(self.inner.id, Retained::into_super(self.inner.scroll.clone()));
self.inner.mounted.set(true);
}
}
pub fn set_columns(&self, columns: Vec<Column<T>>) {
let _focus = KeepFocus::new(&self.inner.table);
let table = &self.inner.table;
*self.inner.sort.borrow_mut() = None;
self.inner.quiet.set(true);
table.setSortDescriptors(&NSArray::new());
let old: Vec<_> = table.tableColumns().iter().collect();
for column in old {
table.removeTableColumn(&column);
}
add_columns(table, &columns);
let gone = self.inner.focus().is_some_and(|f| !columns.iter().any(|c| c.id == f));
*self.inner.columns.borrow_mut() = columns;
self.inner.compute_order();
table.reloadData();
self.inner.quiet.set(false);
if gone {
self.inner.set_focus(None, true);
}
}
pub fn set_rows(&self, rows: Vec<T>) {
let _focus = KeepFocus::new(&self.inner.table);
*self.inner.rows.borrow_mut() = rows;
self.inner.compute_order();
self.inner.quiet.set(true);
self.inner.table.reloadData();
unsafe { self.inner.table.deselectAll(None) };
self.inner.quiet.set(false);
crate::request_redraw();
}
pub fn rows(&self) -> Ref<'_, Vec<T>> {
self.inner.rows.borrow()
}
pub fn len(&self) -> usize {
self.inner.rows.borrow().len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn update_row(&self, index: usize, row: T) {
if let Some(slot) = self.inner.rows.borrow_mut().get_mut(index) {
*slot = row;
} else {
return;
}
if self.inner.group_by.borrow().is_some() || (self.inner.sort.borrow().is_some() && self.inner.sorts_in_place.get()) {
self.inner.resort_keeping_selection();
return;
}
let Some(view_row) = self.inner.order.borrow().iter().position(|&m| m == index) else { return };
let columns = NSIndexSet::indexSetWithIndexesInRange(objc2_foundation::NSRange::new(0, self.inner.columns.borrow().len()));
self.inner.table.reloadDataForRowIndexes_columnIndexes(&NSIndexSet::indexSetWithIndex(view_row), &columns);
}
pub fn insert(&self, index: usize, row: T) {
let _focus = KeepFocus::new(&self.inner.table);
let selected = self.inner.selection_model_rows();
let index = index.min(self.inner.rows.borrow().len());
self.inner.rows.borrow_mut().insert(index, row);
let selected: Vec<usize> = selected.into_iter().map(|r| if r >= index { r + 1 } else { r }).collect();
self.inner.compute_order();
match self.inner.animated_position(index) {
Some(at) => self.inner.table.insertRowsAtIndexes_withAnimation(&NSIndexSet::indexSetWithIndex(at), ANIMATION),
None => self.inner.table.reloadData(),
}
self.inner.select_model_rows(&selected);
}
pub fn append(&self, rows: Vec<T>) {
if rows.is_empty() {
return;
}
let start = self.len();
self.inner.rows.borrow_mut().extend(rows);
let grouped = self.inner.group_by.borrow().is_some();
if grouped || (self.inner.sort.borrow().is_some() && self.inner.sorts_in_place.get()) {
self.inner.resort_keeping_selection();
return;
}
let end = self.len();
self.inner.order.borrow_mut().extend(start..end);
self.inner.table.noteNumberOfRowsChanged();
}
pub fn scroll_to_end(&self) {
let n = self.inner.order.borrow().len();
if n > 0 {
self.inner.table.scrollRowToVisible((n - 1) as NSInteger);
}
}
pub fn is_at_end(&self) -> bool {
let table = &self.inner.table;
let visible = table.visibleRect();
let bottom = visible.origin.y + visible.size.height;
bottom >= table.bounds().size.height - table.rowHeight() - table.intercellSpacing().height - 1.0
}
pub fn push(&self, row: T) {
let len = self.len();
self.insert(len, row);
}
pub fn remove(&self, index: usize) -> Option<T> {
let _focus = KeepFocus::new(&self.inner.table);
if index >= self.len() {
return None;
}
let selected = self.inner.selection_model_rows();
let at = self.inner.animated_position(index);
let row = self.inner.rows.borrow_mut().remove(index);
let selected: Vec<usize> =
selected.into_iter().filter(|&r| r != index).map(|r| if r > index { r - 1 } else { r }).collect();
self.inner.compute_order();
match at {
Some(at) => self.inner.table.removeRowsAtIndexes_withAnimation(&NSIndexSet::indexSetWithIndex(at), ANIMATION),
None => self.inner.table.reloadData(),
}
self.inner.select_model_rows(&selected);
Some(row)
}
pub fn move_rows(&self, rows: &[usize], before: Option<usize>) -> Vec<usize> {
let _focus = KeepFocus::new(&self.inner.table);
let mut moving: Vec<usize> = rows.iter().copied().filter(|&r| r < self.len()).collect();
moving.sort_unstable();
moving.dedup();
let at = {
let mut all = self.inner.rows.borrow_mut();
let end = before.unwrap_or(all.len());
let at = (0..end.min(all.len())).filter(|r| moving.binary_search(r).is_err()).count();
let mut taken = Vec::with_capacity(moving.len());
for &r in moving.iter().rev() {
taken.push(all.remove(r));
}
for (i, row) in taken.into_iter().rev().enumerate() {
all.insert(at + i, row);
}
at
};
let moved: Vec<usize> = (at..at + moving.len()).collect();
self.inner.compute_order();
self.inner.table.reloadData();
self.inner.select_model_rows(&moved);
moved
}
#[doc(hidden)]
pub fn set_row_drag(&self, on: bool) {
self.inner.transfer.borrow_mut().drag = on;
self.inner.table.setDraggingSourceOperationMask_forLocal(NSDragOperation::Copy, false);
self.register_drag_types();
}
#[doc(hidden)]
pub fn set_reorderable(&self, on: bool) {
if on {
self.set_row_drag(true);
self.inner.table.setDraggingSourceOperationMask_forLocal(NSDragOperation::Move, true);
}
self.inner.transfer.borrow_mut().reorder = on;
self.register_drag_types();
}
#[doc(hidden)]
pub fn set_file_drop(&self, extensions: Option<&[&str]>) {
self.inner.transfer.borrow_mut().files = extensions.map(|e| e.iter().map(|s| s.to_string()).collect());
self.register_drag_types();
}
#[doc(hidden)]
pub fn set_animates(&self, on: bool) {
self.inner.animates.set(on);
}
#[doc(hidden)]
pub fn set_url_drop(&self, on: bool) {
self.inner.transfer.borrow_mut().urls = on;
self.register_drag_types();
}
#[doc(hidden)]
pub fn set_pastes(&self, on: bool) {
self.inner.transfer.borrow_mut().pastes = on;
}
#[doc(hidden)]
pub fn set_keys(&self, keys: &[TableKey]) {
self.inner.transfer.borrow_mut().keys = keys.to_vec();
}
#[doc(hidden)]
pub fn set_cell_focus(&self, on: bool) {
if self.inner.transfer.borrow().cell_focus == on {
return;
}
self.inner.transfer.borrow_mut().cell_focus = on;
if !on {
*self.inner.focus.borrow_mut() = None;
}
self.inner.table.reloadData();
}
pub fn focused_column(&self) -> Option<String> {
self.inner.focus()
}
pub fn set_focused_column(&self, column: Option<&str>) {
let index = column.map(|c| self.inner.table.columnWithIdentifier(&NSString::from_str(c))).unwrap_or(-1);
if index >= 0 {
self.inner.table.scrollColumnToVisible(index);
}
self.inner.set_focus(column.filter(|_| index >= 0).map(str::to_string), false);
}
#[doc(hidden)]
pub fn focus_ring(&self, view_row: usize) -> Option<(f64, f64, f64, f64)> {
let table = &self.inner.table;
if !table.isRowSelected(view_row as NSInteger) {
return None;
}
let row = table.rowViewAtRow_makeIfNecessary(view_row as NSInteger, false)?;
let row = row.downcast::<FocusRowView>().ok()?;
let r = row.focus_rect()?;
Some((r.origin.x, r.origin.y, r.size.width, r.size.height))
}
fn register_drag_types(&self) {
let t = self.inner.transfer.borrow();
let mut types = Vec::new();
if t.reorder {
types.push(row_type());
}
if t.files.is_some() {
types.push(NSString::from_str(&unsafe { NSPasteboardTypeFileURL }.to_string()));
}
if t.urls {
types.push(NSString::from_str(&unsafe { NSPasteboardTypeURL }.to_string()));
}
self.inner.table.unregisterDraggedTypes();
if !types.is_empty() {
self.inner.table.registerForDraggedTypes(&NSArray::from_retained_slice(&types));
}
}
pub fn selected_text(&self) -> String {
let rows = indexes(&self.inner.table.selectedRowIndexes());
self.inner.rows_text(&rows, &column_ids(&self.inner.table))
}
pub fn copy_to(&self, pasteboard: &NSPasteboard) -> bool {
self.inner.table.copy_rows(pasteboard)
}
pub fn paste_from(&self, pasteboard: &NSPasteboard) -> bool {
self.inner.table.paste_text(pasteboard)
}
pub fn row_at(&self, position: usize) -> Option<usize> {
self.inner.model_row(position)
}
pub fn set_group_by(&self, key: Option<GroupKey<T>>) {
*self.inner.group_by.borrow_mut() = key;
self.inner.table.setFloatsGroupRows(true);
self.inner.resort_keeping_selection();
}
pub fn groups(&self) -> Vec<String> {
self.inner.groups.borrow().clone()
}
pub fn shown_rows(&self) -> usize {
self.inner.order.borrow().len()
}
pub fn selection(&self) -> Vec<usize> {
self.inner.selection_model_rows()
}
pub fn select(&self, rows: &[usize]) {
self.inner.select_model_rows(rows);
if let Some(&first) = rows.first()
&& let Some(view_row) = self.inner.order.borrow().iter().position(|&m| m == first)
{
self.inner.table.scrollRowToVisible(view_row as NSInteger);
}
}
pub fn sort(&self) -> Option<Sort> {
self.inner.sort.borrow().clone()
}
pub fn set_sort(&self, sort: Option<Sort>) {
let descriptors = match &sort {
Some(s) => NSArray::from_retained_slice(&[NSSortDescriptor::sortDescriptorWithKey_ascending(
Some(&NSString::from_str(&s.column)),
s.ascending,
)]),
None => NSArray::new(),
};
*self.inner.sort.borrow_mut() = sort;
let events_before = self.inner.events.borrow().len();
self.inner.table.setSortDescriptors(&descriptors);
self.inner.events.borrow_mut().truncate(events_before);
if self.inner.sorts_in_place.get() {
self.inner.resort_keeping_selection();
}
}
pub fn set_sorts_in_place(&self, on: bool) {
self.inner.sorts_in_place.set(on);
}
pub fn column_state(&self) -> Vec<ColumnState> {
self.inner
.table
.tableColumns()
.iter()
.map(|c| ColumnState { id: c.identifier().to_string(), width: c.width() })
.collect()
}
pub fn set_column_state(&self, state: &[ColumnState]) {
let table = &self.inner.table;
for (target, s) in state.iter().enumerate() {
let index = table.columnWithIdentifier(&NSString::from_str(&s.id));
if index < 0 {
continue;
}
if let Some(column) = table.tableColumns().iter().nth(index as usize) {
column.setWidth(s.width);
}
if index as usize != target && target < table.numberOfColumns() as usize {
table.moveColumn_toColumn(index, target as NSInteger);
}
}
self.inner.events.borrow_mut().retain(|e| *e != TableEvent::ColumnsChanged);
}
#[doc(hidden)]
pub fn drain_events(&self) -> Vec<TableEvent> {
self.inner.events.borrow_mut().drain(..).collect()
}
#[doc(hidden)]
pub fn cells_created(&self) -> usize {
self.inner._source.ivars().created.get()
}
pub fn scroll_view(&self) -> Retained<NSScrollView> {
self.inner.scroll.clone()
}
pub fn table_view(&self) -> Retained<NSTableView> {
Retained::into_super(self.inner.table.clone())
}
}
#[cfg(test)]
mod tests {
use super::natural_cmp;
use std::cmp::Ordering::*;
#[test]
fn key_matches_natural_order() {
use super::natural_key;
let words = ["Item 10", "item 9", "Item 009", "apple", "Banana", "x", "x1", "a2b", "a10b", "Zo", "zoe 2"];
for a in words {
for b in words {
let by_key = natural_key(a).cmp(&natural_key(b));
let by_cmp = natural_cmp(a, b);
if by_cmp != std::cmp::Ordering::Equal {
assert_eq!(by_key, by_cmp, "{a:?} vs {b:?}");
}
}
}
}
#[test]
fn dates_shown_in_the_users_format() {
use super::{Kind, Value, display};
let none = display(&Kind::Date { time: false, none: None, short: false }, &Value::Number(f64::NEG_INFINITY));
assert_eq!(none, "");
let day = display(&Kind::Date { time: false, none: None, short: false }, &Value::Number(1_600_000_000.0));
let with_time = display(&Kind::Date { time: true, none: None, short: false }, &Value::Number(1_600_000_000.0));
assert!(day.contains("2020") && with_time.contains("2020") && with_time.len() > day.len(), "{day:?} {with_time:?}");
let short = display(&Kind::Date { time: true, none: None, short: true }, &Value::Number(1_600_000_000.0));
assert!(short.len() < with_time.len() && short.chars().filter(char::is_ascii_digit).count() >= 6 && !short.contains("Sep"), "{short:?} {with_time:?}");
let col = super::Column::<Option<std::time::SystemTime>>::date("end", "End", |t| *t).with_time().none_text("Running");
assert_eq!(display(&col.kind, &(col.value)(&None)), "Running");
assert_eq!(display(&col.kind, &(col.value)(&Some(std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_600_000_000)))), with_time);
}
#[test]
fn natural_order() {
assert_eq!(natural_cmp("Item 9", "Item 10"), Less);
assert_eq!(natural_cmp("apple", "Banana"), Less);
assert_eq!(natural_cmp("a2b", "a02b"), Equal);
assert_eq!(natural_cmp("x", "x1"), Less);
}
}
#[cfg(test)]
mod number_cells {
use super::*;
#[test]
fn nan_is_no_value() {
assert_eq!(display(&Kind::Number { decimals: 2 }, &Value::Number(f64::NAN)), "");
assert_eq!(display(&Kind::Number { decimals: 2 }, &Value::Number(1.5)), format!("1{}50", decimal_separator()));
assert_eq!(display(&Kind::Number { decimals: 0 }, &Value::Number(2026.0)), "2026");
}
}