use std::cell::{Cell, RefCell};
use std::path::PathBuf;
use std::rc::{Rc, Weak};
use objc2::rc::Retained;
use objc2::runtime::{NSObject, NSObjectProtocol, ProtocolObject};
use objc2::{ClassType, DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send};
use objc2_app_kit::{
NSAccessibility, NSIndexPathNSCollectionViewAdditions,
NSBox, NSBoxType, NSCollectionView, NSCollectionViewDataSource, NSCollectionViewDelegate, NSCollectionViewFlowLayout, NSCollectionViewItem,
NSColor, NSEvent, NSImage, NSImageScaling, NSImageView, NSScrollView, NSTextAlignment, NSTextField, NSView, NSViewController, NSWorkspace,
};
use objc2_foundation::{NSEdgeInsets, NSIndexPath, NSInteger, NSPoint, NSRect, NSSet, NSSize, NSString};
use ferrokit_core::text::Color;
use crate::signal::{Effect, Signal, untrack};
use crate::view::{Cx, Identifiable, Kind, Node, Size, View};
#[derive(Debug, Clone, PartialEq)]
pub enum ItemImage {
Symbol(String),
FileIcon(PathBuf),
Color(Color),
None,
}
#[derive(Debug, Clone, PartialEq)]
pub struct CollectionItem {
pub title: String,
pub subtitle: Option<String>,
pub image: ItemImage,
}
impl CollectionItem {
pub fn new(title: impl Into<String>, image: ItemImage) -> Self {
CollectionItem { title: title.into(), subtitle: None, image }
}
pub fn subtitle(mut self, text: impl Into<String>) -> Self {
self.subtitle = Some(text.into());
self
}
}
#[derive(Default)]
struct State {
entries: Vec<CollectionItem>,
on_select: Option<Rc<dyn Fn(Vec<usize>)>>,
on_activate: Option<Box<dyn Fn(usize)>>,
quiet: bool,
}
thread_local! {
static CELLS_MADE: Cell<u64> = const { Cell::new(0) };
}
pub fn collection_cells_made() -> u64 {
CELLS_MADE.with(Cell::get)
}
const CELL_ID: &str = "ferrokit.cell";
struct CellParts {
highlight: Retained<NSBox>,
swatch: Retained<NSBox>,
image: Retained<NSImageView>,
title: Retained<NSTextField>,
subtitle: Retained<NSTextField>,
index: Cell<usize>,
state: RefCell<Weak<RefCell<State>>>,
}
define_class!(
#[unsafe(super(NSView))]
#[thread_kind = MainThreadOnly]
#[name = "FerrokitCellView"]
#[ivars = CellParts]
struct CellView;
impl CellView {
#[unsafe(method(isFlipped))]
fn is_flipped(&self) -> bool {
true
}
#[unsafe(method(layout))]
fn layout(&self) {
crate::failure::guard("a collection (layout)", (), || {
let p = self.ivars();
let b = self.bounds().size;
let line = 17.0;
let lines = if p.subtitle.isHidden() { 1.0 } else { 2.0 };
let image_h = (b.height - 8.0 - lines * line - 4.0).max(0.0);
p.highlight.setFrame(NSRect::new(NSPoint::new(0.0, 0.0), b));
let art = NSRect::new(NSPoint::new(6.0, 4.0), NSSize::new((b.width - 12.0).max(0.0), image_h));
p.image.setFrame(art);
p.swatch.setFrame(art);
p.title.setFrame(NSRect::new(NSPoint::new(2.0, 4.0 + image_h + 2.0), NSSize::new((b.width - 4.0).max(0.0), line)));
p.subtitle.setFrame(NSRect::new(NSPoint::new(2.0, 4.0 + image_h + 2.0 + line), NSSize::new((b.width - 4.0).max(0.0), line)));
})
}
#[unsafe(method(mouseDown:))]
fn mouse_down(&self, event: &NSEvent) {
crate::failure::guard("a collection (mouse_down)", (), || {
let () = unsafe { msg_send![super(self), mouseDown: event] };
if event.clickCount() == 2 {
activate(&self.ivars().state.borrow(), self.ivars().index.get());
}
})
}
}
);
fn activate(state: &Weak<RefCell<State>>, index: usize) {
let Some(state) = state.upgrade() else { return };
let f = state.borrow_mut().on_activate.take();
if let Some(f) = &f {
crate::failure::entry("a collection's activation", (), || f(index));
}
if state.borrow().on_activate.is_none() {
state.borrow_mut().on_activate = f;
}
}
fn label(mtm: MainThreadMarker, small: bool) -> Retained<NSTextField> {
let l = NSTextField::labelWithString(&NSString::from_str(""), mtm);
l.setAlignment(NSTextAlignment::Center);
l.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingMiddle);
if small {
l.setTextColor(Some(&NSColor::secondaryLabelColor()));
l.setFont(Some(&objc2_app_kit::NSFont::systemFontOfSize(objc2_app_kit::NSFont::smallSystemFontSize())));
}
l
}
fn filled_box(mtm: MainThreadMarker, radius: f64) -> Retained<NSBox> {
let b = NSBox::new(mtm);
b.setBoxType(NSBoxType::Custom);
b.setBorderWidth(0.0);
b.setCornerRadius(radius);
b.setTitlePosition(objc2_app_kit::NSTitlePosition::NoTitle);
b.setFillColor(&NSColor::clearColor());
b
}
define_class!(
#[unsafe(super(NSCollectionViewItem, NSViewController))]
#[thread_kind = MainThreadOnly]
#[name = "FerrokitCollectionCell"]
struct GridCell;
impl GridCell {
#[unsafe(method(loadView))]
fn load_view(&self) {
crate::failure::guard("a collection (load_view)", (), || {
let mtm = MainThreadMarker::new().expect("main thread");
CELLS_MADE.with(|c| c.set(c.get() + 1));
let parts = CellParts {
highlight: filled_box(mtm, 8.0),
swatch: filled_box(mtm, 6.0),
image: NSImageView::new(mtm),
title: label(mtm, false),
subtitle: label(mtm, true),
index: Cell::new(0),
state: RefCell::new(Weak::new()),
};
parts.image.setImageScaling(NSImageScaling::ScaleProportionallyUpOrDown);
let view = CellView::alloc(mtm).set_ivars(parts);
let view: Retained<CellView> = unsafe { msg_send![super(view), initWithFrame: NSRect::ZERO] };
let p = view.ivars();
for v in [&**p.highlight as &NSView, &p.swatch, &p.image, &p.title, &p.subtitle] {
view.addSubview(v);
}
view.setAccessibilityElement(true);
view.setAccessibilityRole(Some(unsafe { objc2_app_kit::NSAccessibilityImageRole }));
for v in [&**p.image as &NSView, &p.title, &p.subtitle, &p.swatch, &p.highlight] {
<crate::platform::Native as crate::platform::Platform>::set_accessibility_element(v, false);
}
self.setView(&view);
})
}
#[unsafe(method(setSelected:))]
fn set_selected(&self, selected: bool) {
crate::failure::guard("a collection (set_selected)", (), || {
let () = unsafe { msg_send![super(self), setSelected: selected] };
if let Some(v) = self.cell_view() {
let fill = if selected { NSColor::selectedContentBackgroundColor() } else { NSColor::clearColor() };
v.ivars().highlight.setFillColor(&fill);
let text = if selected { NSColor::alternateSelectedControlTextColor() } else { NSColor::labelColor() };
v.ivars().title.setTextColor(Some(&text));
}
})
}
}
);
impl GridCell {
fn cell_view(&self) -> Option<Retained<CellView>> {
self.view().downcast::<CellView>().ok()
}
fn fill(&self, item: &CollectionItem, index: usize, state: &Weak<RefCell<State>>) {
let Some(v) = self.cell_view() else { return };
let p = v.ivars();
p.index.set(index);
*p.state.borrow_mut() = state.clone();
p.title.setStringValue(&NSString::from_str(&item.title));
p.subtitle.setStringValue(&NSString::from_str(item.subtitle.as_deref().unwrap_or("")));
p.subtitle.setHidden(item.subtitle.is_none());
let (image, swatch) = match &item.image {
ItemImage::Symbol(name) => (NSImage::imageWithSystemSymbolName_accessibilityDescription(&NSString::from_str(name), None), None),
ItemImage::FileIcon(path) => (Some(NSWorkspace::sharedWorkspace().iconForFile(&NSString::from_str(&path.to_string_lossy()))), None),
ItemImage::Color(c) => (None, Some(c.ns())),
ItemImage::None => (None, None),
};
p.image.setImage(image.as_deref());
p.image.setHidden(image.is_none());
p.swatch.setHidden(swatch.is_none());
if let Some(c) = &swatch {
p.swatch.setFillColor(c);
}
let name = match &item.subtitle {
Some(s) => format!("{}, {s}", item.title),
None => item.title.clone(),
};
v.setAccessibilityLabel(Some(&NSString::from_str(&name)));
v.setNeedsLayout(true);
}
}
define_class!(
#[unsafe(super(NSCollectionView))]
#[thread_kind = MainThreadOnly]
#[name = "FerrokitCollectionView"]
#[ivars = RefCell<Weak<RefCell<State>>>]
struct GridView;
impl GridView {
#[unsafe(method(keyDown:))]
fn key_down(&self, event: &NSEvent) {
crate::failure::guard("a collection (key_down)", (), || {
let ret = matches!(event.keyCode(), 36 | 76);
let first = self.selectionIndexPaths().iter().map(|p| p.item() as usize).min();
match (ret, first) {
(true, Some(i)) => activate(&self.ivars().borrow(), i),
_ => unsafe { msg_send![super(self), keyDown: event] },
}
})
}
}
);
define_class!(
#[unsafe(super(NSObject))]
#[thread_kind = MainThreadOnly]
#[name = "FerrokitCollectionSource"]
#[ivars = Weak<RefCell<State>>]
struct GridSource;
unsafe impl NSObjectProtocol for GridSource {}
unsafe impl NSCollectionViewDataSource for GridSource {
#[unsafe(method(collectionView:numberOfItemsInSection:))]
fn count(&self, _cv: &NSCollectionView, _section: NSInteger) -> NSInteger {
crate::failure::guard("a collection (count)", 0, || {
self.ivars().upgrade().map_or(0, |s| s.borrow().entries.len()) as NSInteger
})
}
#[unsafe(method_id(collectionView:itemForRepresentedObjectAtIndexPath:))]
fn item(&self, cv: &NSCollectionView, path: &NSIndexPath) -> Retained<NSCollectionViewItem> {
let made = cv.makeItemWithIdentifier_forIndexPath(&NSString::from_str(CELL_ID), path);
crate::failure::guard("a collection (item)", (), || {
if let (Ok(cell), Some(state)) = (made.clone().downcast::<GridCell>(), self.ivars().upgrade()) {
let index = path.item() as usize;
if let Some(entry) = state.borrow().entries.get(index) {
cell.fill(entry, index, self.ivars());
}
}
});
made
}
}
unsafe impl NSCollectionViewDelegate for GridSource {
#[unsafe(method(collectionView:didSelectItemsAtIndexPaths:))]
fn did_select(&self, cv: &NSCollectionView, _paths: &NSSet<NSIndexPath>) {
crate::failure::guard("a collection (did_select)", (), || {
self.selection_changed(cv);
})
}
#[unsafe(method(collectionView:didDeselectItemsAtIndexPaths:))]
fn did_deselect(&self, cv: &NSCollectionView, _paths: &NSSet<NSIndexPath>) {
crate::failure::guard("a collection (did_deselect)", (), || {
self.selection_changed(cv);
})
}
}
);
impl GridSource {
fn selection_changed(&self, cv: &NSCollectionView) {
let Some(state) = self.ivars().upgrade() else { return };
if state.borrow().quiet {
return;
}
let mut rows: Vec<usize> = cv.selectionIndexPaths().iter().map(|p| p.item() as usize).collect();
rows.sort_unstable();
let on_select = state.borrow().on_select.clone();
if let Some(f) = on_select {
crate::failure::entry("a collection's selection", (), || f(rows));
}
}
}
type Describe<T> = Rc<dyn Fn(&T) -> CollectionItem>;
pub struct Collection<T: Identifiable + 'static> {
items: Box<dyn Fn() -> Vec<T>>,
describe: Describe<T>,
item_size: (f64, f64),
selection: Option<Signal<Vec<T::Id>>>,
multiple: bool,
on_activate: Option<Rc<dyn Fn(T)>>,
}
impl<T: Identifiable + Clone + 'static> Collection<T> {
pub fn item_size(mut self, width: f64, height: f64) -> Self {
self.item_size = (width, height);
self
}
pub fn selection(mut self, selected: &Signal<Vec<T::Id>>) -> Self {
self.selection = Some(*selected);
self
}
pub fn multiple(mut self) -> Self {
self.multiple = true;
self
}
pub fn on_activate(mut self, f: impl Fn(T) + 'static) -> Self {
self.on_activate = Some(Rc::new(f));
self
}
}
impl<T: Identifiable + Clone + 'static> View for Collection<T> {
fn build(self, cx: &mut Cx) -> Node {
let mtm = cx.mtm;
let state = Rc::new(RefCell::new(State::default()));
let grid = GridView::alloc(mtm).set_ivars(RefCell::new(Rc::downgrade(&state)));
let grid: Retained<GridView> = unsafe { msg_send![super(grid), initWithFrame: NSRect::ZERO] };
let cv: Retained<NSCollectionView> = Retained::into_super(grid);
let layout = NSCollectionViewFlowLayout::new(mtm);
layout.setItemSize(NSSize::new(self.item_size.0, self.item_size.1));
layout.setMinimumInteritemSpacing(8.0);
layout.setMinimumLineSpacing(8.0);
layout.setSectionInset(NSEdgeInsets { top: 12.0, left: 12.0, bottom: 12.0, right: 12.0 });
cv.setCollectionViewLayout(Some(&layout));
unsafe { cv.registerClass_forItemWithIdentifier(Some(GridCell::class()), &NSString::from_str(CELL_ID)) };
cv.setSelectable(true);
cv.setAllowsMultipleSelection(self.multiple);
cv.setAllowsEmptySelection(true);
cv.setBackgroundColors(Some(&objc2_foundation::NSArray::from_retained_slice(&[NSColor::controlBackgroundColor()])));
let source = GridSource::alloc(mtm).set_ivars(Rc::downgrade(&state));
let source: Retained<GridSource> = unsafe { msg_send![super(source), init] };
cv.setDataSource(Some(ProtocolObject::from_ref(&*source)));
cv.setDelegate(Some(ProtocolObject::from_ref(&*source)));
let scroll = NSScrollView::new(mtm);
scroll.setDocumentView(Some(&cv));
scroll.setHasVerticalScroller(true);
scroll.setAutohidesScrollers(true);
let values: Rc<RefCell<Vec<T>>> = Rc::default();
if let Some(sel) = &self.selection {
let (sel, values) = (*sel, values.clone());
state.borrow_mut().on_select = Some(Rc::new(move |rows| {
let ids = {
let v = values.borrow();
rows.iter().filter_map(|&i| v.get(i).map(Identifiable::id)).collect()
};
sel.set(ids);
}));
}
if let Some(f) = self.on_activate.clone() {
let values = values.clone();
state.borrow_mut().on_activate = Some(Box::new(move |i| {
let item = values.borrow().get(i).cloned();
if let Some(item) = item {
f(item);
}
}));
}
let (mut node, _) = Node::leaf(cx, Retained::into_super(scroll), (true, true), Size { w: 240.0, h: 200.0 });
if let Kind::Leaf(l) = &node.kind {
l.content.set(Some(Size { w: 240.0, h: 200.0 }));
}
let restore: Rc<dyn Fn()> = {
let (st, values, cv, sel) = (state.clone(), values.clone(), cv.clone(), self.selection);
Rc::new(move || {
let Some(sel) = &sel else { return };
let want = sel.get();
untrack(|| {
let wanted: std::collections::HashSet<&T::Id> = want.iter().collect();
let rows: Vec<usize> = values.borrow().iter().enumerate().filter(|(_, v)| wanted.contains(&v.id())).map(|(i, _)| i).collect();
let mut now: Vec<usize> = cv.selectionIndexPaths().iter().map(|p| p.item() as usize).collect();
now.sort_unstable();
if now != rows {
st.borrow_mut().quiet = true;
let paths: Vec<Retained<NSIndexPath>> = rows.iter().map(|&i| NSIndexPath::indexPathForItem_inSection(i as NSInteger, 0)).collect();
let set = NSSet::from_retained_slice(&paths);
cv.setSelectionIndexPaths(&set);
st.borrow_mut().quiet = false;
}
});
})
};
let (items_fn, describe) = (self.items, self.describe);
let (st, vals, cv2, restore2) = (state.clone(), values.clone(), cv.clone(), restore.clone());
node.own(Effect::new(move || {
let items = items_fn();
untrack(|| {
let entries: Vec<CollectionItem> = items.iter().map(|i| describe(i)).collect();
*vals.borrow_mut() = items;
st.borrow_mut().entries = entries;
st.borrow_mut().quiet = true;
cv2.reloadData();
st.borrow_mut().quiet = false;
restore2();
});
}));
if self.selection.is_some() {
node.own(Effect::new(move || restore()));
}
node.keep(Retained::into_super(source));
node.hold(state);
node
}
}
pub fn collection<T: Identifiable + Clone + 'static>(items: impl Fn() -> Vec<T> + 'static, describe: impl Fn(&T) -> CollectionItem + 'static) -> Collection<T> {
Collection { items: Box::new(items), describe: Rc::new(describe), item_size: (120.0, 110.0), selection: None, multiple: false, on_activate: None }
}