mitsuami-appkit 1.0.0

AppKit (macOS) backend for mitsuami
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! A window's sidebar: a view-based `NSTableView` in the source list
//! style, in the sidebar item of an `NSSplitViewController` whose other
//! item holds the window's content, as in System Settings and Finder.
//!
//! The sidebar node owns the table ([`Sidebar`]); the window makes the
//! split when the sidebar is inserted ([`Split`]), with the window's
//! content under the title bar, as the sidebar is full height.
//!
//! Like a list's, the table's data source reads only the sidebar's own
//! [`SidebarData`], and only emits.

use std::cell::{Cell, RefCell};
use std::ffi::c_void;
use std::rc::Rc;

use mitsuami_core::{EventSink, EventValue, NodeId, SidebarItemData, SidebarSectionData, UiEvent};
use objc2::rc::Retained;
use objc2::runtime::{AnyObject, NSObject, NSObjectProtocol, ProtocolObject};
use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, Message, define_class, msg_send};
use objc2_app_kit::{
    NSControlTextEditingDelegate, NSImage, NSImageScaling, NSImageView, NSLayoutConstraint, NSLineBreakMode,
    NSScrollView, NSSplitViewController, NSSplitViewItem, NSTableCellView, NSTableColumn, NSTableColumnResizingOptions,
    NSTableView, NSTableViewColumnAutoresizingStyle, NSTableViewDataSource, NSTableViewDelegate,
    NSTableViewRowSizeStyle, NSTableViewStyle, NSTextField, NSView, NSViewController, NSWindow, NSWindowStyleMask,
};
use objc2_foundation::{
    NSArray, NSIndexSet, NSInteger, NSKeyValueObservingOptions, NSNotification, NSObjectNSKeyValueObserverRegistration,
    NSString,
};

use crate::classes::zero_rect;

/// A row of the table: a section's heading, or an item (its index across
/// the sections).
#[derive(Clone, Copy, PartialEq)]
enum Row {
    Heading(usize),
    Item(usize),
}

/// What the table shows, shared by the backend and the table's data source.
#[derive(Default)]
pub(crate) struct SidebarData {
    sections: Vec<SidebarSectionData>,
    items: Vec<SidebarItemData>,
    rows: Vec<Row>,
    /// Set while the backend changes the selection itself.
    muted: bool,
}

impl SidebarData {
    fn row_of(&self, item: usize) -> Option<usize> {
        self.rows.iter().position(|r| *r == Row::Item(item))
    }

    fn item_at(&self, row: NSInteger) -> Option<usize> {
        match self.rows.get(usize::try_from(row).ok()?)? {
            Row::Item(item) => Some(*item),
            Row::Heading(_) => None,
        }
    }
}

type Shared = Rc<RefCell<SidebarData>>;

pub(crate) struct SourceIvars {
    id: NodeId,
    events: EventSink,
    data: Shared,
}

define_class!(
    /// The table's data source and delegate.
    #[unsafe(super(NSObject))]
    #[thread_kind = MainThreadOnly]
    #[ivars = SourceIvars]
    pub(crate) struct SidebarSource;

    unsafe impl NSObjectProtocol for SidebarSource {}

    unsafe impl NSControlTextEditingDelegate for SidebarSource {}

    unsafe impl NSTableViewDataSource for SidebarSource {
        #[unsafe(method(numberOfRowsInTableView:))]
        fn number_of_rows(&self, _table: &NSTableView) -> NSInteger {
            self.ivars().data.borrow().rows.len() as NSInteger
        }
    }

    unsafe impl NSTableViewDelegate for SidebarSource {
        /// A section's heading, which a source list draws as one.
        #[unsafe(method(tableView:isGroupRow:))]
        fn is_group_row(&self, _table: &NSTableView, row: NSInteger) -> bool {
            let data = self.ivars().data.borrow();
            matches!(data.rows.get(row as usize), Some(Row::Heading(_)))
        }

        #[unsafe(method_id(tableView:viewForTableColumn:row:))]
        fn view_for_row(
            &self,
            _table: &NSTableView,
            _column: Option<&NSTableColumn>,
            row: NSInteger,
        ) -> Option<Retained<NSView>> {
            let data = self.ivars().data.borrow();
            let cell = data.rows.get(row as usize).map(|row| match *row {
                Row::Heading(section) => cell(self.mtm(), data.sections[section].title.as_deref().unwrap_or(""), None),
                Row::Item(item) => cell(self.mtm(), &data.items[item].title, data.items[item].icon.as_deref()),
            });
            cell.map(Retained::into_super)
        }

        #[unsafe(method(tableView:shouldSelectRow:))]
        fn should_select_row(&self, _table: &NSTableView, row: NSInteger) -> bool {
            self.ivars().data.borrow().item_at(row).is_some()
        }

        /// A sidebar keeps its selection: a click on empty space doesn't
        /// take it away, as none does in Finder's or System Settings'.
        #[unsafe(method_id(tableView:selectionIndexesForProposedSelection:))]
        fn selection_for_proposed(&self, table: &NSTableView, proposed: &NSIndexSet) -> Retained<NSIndexSet> {
            if proposed.count() == 0 && !self.ivars().data.borrow().muted {
                table.selectedRowIndexes()
            } else {
                proposed.retain()
            }
        }

        #[unsafe(method(tableViewSelectionDidChange:))]
        fn selection_did_change(&self, notification: &NSNotification) {
            let Some(table) = notification.object().and_then(|o| o.downcast::<NSTableView>().ok()) else { return };
            let SourceIvars { id, events, data } = self.ivars();
            let data = data.borrow();
            if let (false, Some(item)) = (data.muted, data.item_at(table.selectedRow())) {
                events.emit(*id, UiEvent::Changed(EventValue::Index(item)));
            }
        }
    }
);

/// How wide a row's icon is: a slot of its own, so titles line up whatever
/// their symbols' widths, as in Finder's sidebar.
const ICON_WIDTH: f64 = 20.0;

/// A row's view: its icon and title, which the source list sizes and
/// styles for the row size the user chose (System Settings' "Sidebar icon
/// size"), as Interface Builder's image and text cell.
fn cell(mtm: MainThreadMarker, title: &str, icon: Option<&str>) -> Retained<NSTableCellView> {
    let cell = NSTableCellView::new(mtm);
    let label = NSTextField::labelWithString(&NSString::from_str(title), mtm);
    label.setLineBreakMode(NSLineBreakMode::ByTruncatingTail);
    label.setTranslatesAutoresizingMaskIntoConstraints(false);
    cell.addSubview(&label);
    unsafe { cell.setTextField(Some(&label)) };
    let image = icon
        .and_then(|name| NSImage::imageWithSystemSymbolName_accessibilityDescription(&NSString::from_str(name), None));
    let leading = match image {
        Some(image) => {
            let view = NSImageView::imageViewWithImage(&image, mtm);
            // Centred in its slot at its own size, not scaled to it.
            view.setImageScaling(NSImageScaling::ScaleNone);
            view.setTranslatesAutoresizingMaskIntoConstraints(false);
            cell.addSubview(&view);
            unsafe { cell.setImageView(Some(&view)) };
            NSLayoutConstraint::activateConstraints(&NSArray::from_retained_slice(&[
                view.leadingAnchor().constraintEqualToAnchor_constant(&cell.leadingAnchor(), 2.0),
                view.widthAnchor().constraintEqualToConstant(ICON_WIDTH),
                view.centerYAnchor().constraintEqualToAnchor(&cell.centerYAnchor()),
            ]));
            view.trailingAnchor().constraintEqualToAnchor_constant(&label.leadingAnchor(), -6.0)
        }
        None => label.leadingAnchor().constraintEqualToAnchor_constant(&cell.leadingAnchor(), 2.0),
    };
    NSLayoutConstraint::activateConstraints(&NSArray::from_retained_slice(&[
        leading,
        label.trailingAnchor().constraintLessThanOrEqualToAnchor_constant(&cell.trailingAnchor(), -2.0),
        label.centerYAnchor().constraintEqualToAnchor(&cell.centerYAnchor()),
    ]));
    cell
}

/// The sidebar node's native parts: the table in its scroll view, which
/// becomes the split's sidebar when the window takes it.
pub(crate) struct Sidebar {
    pub scroll: Retained<NSScrollView>,
    pub table: Retained<NSTableView>,
    _source: Retained<SidebarSource>,
    data: Shared,
    /// Shown as the app wants it, if it said: the split shows it.
    pub shown: Cell<Option<bool>>,
}

impl Sidebar {
    pub(crate) fn new(mtm: MainThreadMarker, id: NodeId, events: EventSink) -> Sidebar {
        let data = Shared::default();
        let source: Retained<SidebarSource> = unsafe {
            msg_send![super(SidebarSource::alloc(mtm).set_ivars(SourceIvars { id, events, data: data.clone() })), init]
        };
        let table = NSTableView::initWithFrame(NSTableView::alloc(mtm), zero_rect());
        table.setHeaderView(None);
        table.setStyle(NSTableViewStyle::SourceList);
        // The system's row size, which follows the user's sidebar icon size.
        table.setRowSizeStyle(NSTableViewRowSizeStyle::Default);
        table.setFloatsGroupRows(false);
        table.setAllowsEmptySelection(true);
        table.setAllowsMultipleSelection(false);
        table.setColumnAutoresizingStyle(NSTableViewColumnAutoresizingStyle::FirstColumnOnlyAutoresizingStyle);
        let column = NSTableColumn::initWithIdentifier(NSTableColumn::alloc(mtm), &NSString::from_str("item"));
        column.setResizingMask(NSTableColumnResizingOptions::AutoresizingMask);
        table.addTableColumn(&column);
        unsafe {
            table.setDataSource(Some(ProtocolObject::from_ref(&*source)));
            table.setDelegate(Some(ProtocolObject::from_ref(&*source)));
        }
        let scroll = NSScrollView::initWithFrame(NSScrollView::alloc(mtm), zero_rect());
        scroll.setHasVerticalScroller(true);
        scroll.setAutohidesScrollers(true);
        scroll.setDrawsBackground(false);
        scroll.setDocumentView(Some(&table));
        Sidebar { scroll, table, _source: source, data, shown: Cell::new(None) }
    }

    /// New items: the table reloads, and keeps the selected item, which
    /// the core sends again if it moved.
    pub(crate) fn set_sections(&self, sections: Vec<SidebarSectionData>) {
        let selected = self.selected();
        {
            let mut data = self.data.borrow_mut();
            data.items = sections.iter().flat_map(|s| s.items.iter().cloned()).collect();
            data.rows.clear();
            let mut item = 0;
            for (index, section) in sections.iter().enumerate() {
                if section.title.is_some() {
                    data.rows.push(Row::Heading(index));
                }
                for _ in &section.items {
                    data.rows.push(Row::Item(item));
                    item += 1;
                }
            }
            data.sections = sections;
            data.muted = true;
        }
        self.table.reloadData();
        self.show_selected(selected.filter(|i| *i < self.data.borrow().items.len()));
        self.data.borrow_mut().muted = false;
    }

    pub(crate) fn sections(&self) -> Vec<SidebarSectionData> {
        self.data.borrow().sections.clone()
    }

    /// Selects an item without reporting it.
    pub(crate) fn set_selected(&self, item: Option<usize>) {
        self.data.borrow_mut().muted = true;
        self.show_selected(item);
        self.data.borrow_mut().muted = false;
    }

    fn show_selected(&self, item: Option<usize>) {
        let row = item.and_then(|i| self.data.borrow().row_of(i));
        match row {
            Some(row) => {
                self.table.selectRowIndexes_byExtendingSelection(&NSIndexSet::indexSetWithIndex(row), false);
                self.table.scrollRowToVisible(row as NSInteger);
            }
            None => unsafe { self.table.deselectAll(None) },
        }
    }

    /// Stops the table from calling its data source, which goes with the
    /// sidebar, while the split may still hold the table.
    pub(crate) fn detach(&self) {
        unsafe {
            self.table.setDataSource(None);
            self.table.setDelegate(None);
        }
    }

    /// The item the table shows selected.
    pub(crate) fn selected(&self) -> Option<usize> {
        self.data.borrow().item_at(self.table.selectedRow())
    }

    /// Selects the first item with this title as the user would, which the
    /// delegate reports: what a screen reader's select does. `false` if
    /// there's none.
    pub(crate) fn choose(&self, title: &str) -> bool {
        let row = {
            let data = self.data.borrow();
            let item = data.items.iter().position(|i| i.title == title);
            item.and_then(|i| data.row_of(i))
        };
        let Some(row) = row else { return false };
        self.table.selectRowIndexes_byExtendingSelection(&NSIndexSet::indexSetWithIndex(row), false);
        true
    }
}

pub(crate) struct WatchIvars {
    sidebar: NodeId,
    events: EventSink,
    /// Collapsed as last reported or set, to tell the user's changes from
    /// the backend's.
    collapsed: Cell<bool>,
}

define_class!(
    /// Watches the sidebar item's `collapsed` (KVO): the user collapsed or
    /// expanded it (its divider, the toolbar's toggle, View â–¸ Hide
    /// Sidebar), or AppKit did for a narrow window.
    #[unsafe(super(NSObject))]
    #[thread_kind = MainThreadOnly]
    #[ivars = WatchIvars]
    pub(crate) struct CollapseWatch;

    impl CollapseWatch {
        #[unsafe(method(observeValueForKeyPath:ofObject:change:context:))]
        fn observe_value(
            &self,
            _key_path: Option<&NSString>,
            object: Option<&AnyObject>,
            _change: Option<&AnyObject>,
            _context: *mut c_void,
        ) {
            let Some(item) = object.and_then(|o| o.downcast_ref::<NSSplitViewItem>()) else { return };
            let WatchIvars { sidebar, events, collapsed } = self.ivars();
            let now = item.isCollapsed();
            if collapsed.replace(now) != now {
                events.emit(*sidebar, UiEvent::SidebarShownChanged(!now));
            }
        }
    }

    unsafe impl NSObjectProtocol for CollapseWatch {}
);

const COLLAPSED: &str = "collapsed";

/// A window split in two: the sidebar, and a view holding the window's
/// content (its host), below the title bar and toolbar.
pub(crate) struct Split {
    pub sidebar: NodeId,
    controller: Retained<NSSplitViewController>,
    item: Retained<NSSplitViewItem>,
    watch: Retained<CollapseWatch>,
}

impl Split {
    /// Puts the window's content beside the sidebar. The sidebar is full
    /// height, under the title bar, as on macOS 11 and later; the content
    /// stays below it.
    pub(crate) fn new(
        mtm: MainThreadMarker,
        window: &NSWindow,
        host: &NSView,
        sidebar: NodeId,
        scroll: &NSScrollView,
        events: EventSink,
    ) -> Split {
        let side = NSViewController::new(mtm);
        side.setView(scroll);
        let item = NSSplitViewItem::sidebarWithViewController(&side);
        let detail = NSView::new(mtm);
        let content = NSViewController::new(mtm);
        content.setView(&detail);
        let controller = NSSplitViewController::new(mtm);
        controller.addSplitViewItem(&item);
        controller.addSplitViewItem(&NSSplitViewItem::splitViewItemWithViewController(&content));
        let frame = window.contentView().map_or(zero_rect(), |v| v.frame());
        controller.view().setFrame(frame);
        window.setStyleMask(window.styleMask() | NSWindowStyleMask::FullSizeContentView);
        window.setContentViewController(Some(&controller));
        host.removeFromSuperview();
        host.setTranslatesAutoresizingMaskIntoConstraints(false);
        detail.addSubview(host);
        NSLayoutConstraint::activateConstraints(&NSArray::from_retained_slice(&[
            host.topAnchor().constraintEqualToAnchor(&detail.safeAreaLayoutGuide().topAnchor()),
            host.leadingAnchor().constraintEqualToAnchor(&detail.leadingAnchor()),
            host.trailingAnchor().constraintEqualToAnchor(&detail.trailingAnchor()),
            host.bottomAnchor().constraintEqualToAnchor(&detail.bottomAnchor()),
        ]));
        let watch = CollapseWatch::alloc(mtm).set_ivars(WatchIvars {
            sidebar,
            events,
            collapsed: Cell::new(item.isCollapsed()),
        });
        let watch: Retained<CollapseWatch> = unsafe { msg_send![super(watch), init] };
        unsafe {
            item.addObserver_forKeyPath_options_context(
                &watch,
                &NSString::from_str(COLLAPSED),
                NSKeyValueObservingOptions::New,
                std::ptr::null_mut(),
            );
        }
        Split { sidebar, controller, item, watch }
    }

    /// Shows or hides the sidebar without reporting it, as the toolbar's
    /// toggle does (`toggleSidebar:`), animated in a shown window.
    pub(crate) fn set_shown(&self, shown: bool) {
        self.watch.ivars().collapsed.set(!shown);
        if self.item.isCollapsed() == shown {
            self.item.setCollapsed(!shown);
        }
    }

    /// Stops watching the item: KVO doesn't retain the watch, which goes
    /// with the split while the item may live on in the window.
    pub(crate) fn detach(&self) {
        unsafe { self.item.removeObserver_forKeyPath(&self.watch, &NSString::from_str(COLLAPSED)) };
    }

    /// Gives the window its content back, as it was before the split.
    pub(crate) fn remove(self, window: &NSWindow, host: &NSView) {
        self.detach();
        window.setContentViewController(None);
        host.removeFromSuperview();
        host.setTranslatesAutoresizingMaskIntoConstraints(true);
        window.setStyleMask(window.styleMask() & !NSWindowStyleMask::FullSizeContentView);
        window.setContentView(Some(host));
        drop(self.controller);
    }

    /// Collapsed: the user dragged it away, or the window is too narrow.
    pub(crate) fn collapsed(&self) -> bool {
        self.item.isCollapsed()
    }
}