Skip to main content

ferrokit/
models.rs

1//! Views over `ferrokit-core`'s models: the native table and the text editor. The model owns the AppKit view and the data; the view places
2//! it and turns the model's events into callbacks.
3
4use ferrokit_core::kept::{UiCell, UiLocal};
5use std::path::PathBuf;
6use std::rc::{Rc, Weak};
7
8use ferrokit_core::table::{ColumnState, Sort, TableEvent, TableModel};
9use ferrokit_core::text::{TextEvent, TextModel, TextStyle};
10use objc2::rc::Retained;
11
12use crate::signal::{Effect, Signal, batch, untrack};
13use crate::view::{Cx, Node, Size, View};
14
15type Drain = Rc<dyn Fn()>;
16
17thread_local! {
18    /// Event drains of the models currently in a window (owned by their nodes).
19    static DRAINS: UiCell<Vec<Weak<dyn Fn()>>> = const { UiCell::new(Vec::new()) };
20}
21
22/// Delivers queued model events (called on the run-loop pass after
23/// `ferrokit-core` asks for a redraw).
24/// Delivers editors' and tables' pending changes now: before a menu item,
25/// a button or a command acts, so it sees what was just typed (typing and
26/// a shortcut can arrive in the same run-loop turn, before the next pass
27/// would deliver them).
28pub(crate) fn flush() {
29    if !DRAINS.with_borrow(Vec::is_empty) {
30        drain_all();
31    }
32}
33
34pub(crate) fn drain_all() {
35    ferrokit_core::begin_frame();
36    let live: Vec<Drain> = DRAINS.with_borrow_mut(|d| {
37        d.retain(|w| w.strong_count() > 0);
38        d.iter().filter_map(Weak::upgrade).collect()
39    });
40    batch(|| live.iter().for_each(|f| f()));
41}
42
43fn register(drain: &Drain) {
44    DRAINS.with_borrow_mut(|d| d.push(Rc::downgrade(drain)));
45}
46
47type Callback<A> = Option<Box<dyn Fn(A)>>;
48/// A row-menu item: its title and the action given the row.
49type RowAction = (String, Box<dyn Fn(usize)>);
50
51/// A native `NSTableView` showing a [`TableModel`]: millions of rows,
52/// sorting, column resizing, type-select and VoiceOver come from AppKit.
53pub struct Table<T: 'static> {
54    model: Rc<TableModel<T>>,
55    on_select: Callback<Vec<usize>>,
56    on_activate: Callback<usize>,
57    on_sort: Callback<Sort>,
58    on_toggle: Callback<(usize, String, bool)>,
59    on_edit: Callback<(usize, String, String)>,
60    on_columns: Callback<Vec<ColumnState>>,
61    on_move: Callback<(Vec<usize>, Option<usize>)>,
62    on_files: Callback<(Vec<PathBuf>, Option<usize>)>,
63    file_types: Vec<String>,
64    on_paste: Callback<String>,
65    row_drag: bool,
66    row_menu: Vec<RowAction>,
67}
68
69impl<T: 'static> Table<T> {
70    /// A right-click menu for rows: each action gets the clicked row (model
71    /// index), or the selected row when invoked another way.
72    pub fn row_menu(mut self, title: &str, action: impl Fn(usize) + 'static) -> Self {
73        self.row_menu.push((title.into(), Box::new(action)));
74        self
75    }
76
77    /// The selected rows (model indices) changed.
78    pub fn on_select(mut self, f: impl Fn(Vec<usize>) + 'static) -> Self {
79        self.on_select = Some(Box::new(f));
80        self
81    }
82
83    /// A row was double-clicked, or Return pressed on it.
84    pub fn on_activate(mut self, f: impl Fn(usize) + 'static) -> Self {
85        self.on_activate = Some(Box::new(f));
86        self
87    }
88
89    /// The user sorted by a column (rows are already shown in the new order).
90    pub fn on_sort(mut self, f: impl Fn(Sort) + 'static) -> Self {
91        self.on_sort = Some(Box::new(f));
92        self
93    }
94
95    /// A checkbox cell was clicked: (row, column id, new value).
96    pub fn on_toggle(mut self, f: impl Fn(usize, String, bool) + 'static) -> Self {
97        self.on_toggle = Some(Box::new(move |(r, c, v)| f(r, c, v)));
98        self
99    }
100
101    /// An editable cell was edited: (row, column id, new text). Apply it to
102    /// the row with [`TableModel::update_row`].
103    pub fn on_edit(mut self, f: impl Fn(usize, String, String) + 'static) -> Self {
104        self.on_edit = Some(Box::new(move |(r, c, v)| f(r, c, v)));
105        self
106    }
107
108    /// Rows can be dragged to other apps (as tab-separated text). ⌘C copies
109    /// the selected rows the same way, always.
110    pub fn row_drag(mut self) -> Self {
111        self.row_drag = true;
112        self
113    }
114
115    /// The user can drag rows to a new place: `f` gets the dragged rows and
116    /// the row they were dropped above (`None`: the end), as model indices.
117    /// Apply it with [`TableModel::move_rows`]. Not while the table is sorted.
118    pub fn reorderable(mut self, f: impl Fn(Vec<usize>, Option<usize>) + 'static) -> Self {
119        self.on_move = Some(Box::new(move |(rows, before)| f(rows, before)));
120        self
121    }
122
123    /// Files with these extensions (any file if empty) can be dropped on the
124    /// table: `f` gets their paths and the row they were dropped above.
125    pub fn on_files_dropped(mut self, extensions: &[&str], f: impl Fn(Vec<PathBuf>, Option<usize>) + 'static) -> Self {
126        self.file_types = extensions.iter().map(|e| e.to_string()).collect();
127        self.on_files = Some(Box::new(move |(paths, before)| f(paths, before)));
128        self
129    }
130
131    /// ⌘V on the table: `f` gets the pasted text (rows copied from a table
132    /// arrive as tab-separated lines).
133    pub fn on_paste(mut self, f: impl Fn(String) + 'static) -> Self {
134        self.on_paste = Some(Box::new(f));
135        self
136    }
137
138    /// Columns were moved or resized (save them to restore later).
139    pub fn on_columns_changed(mut self, f: impl Fn(Vec<ColumnState>) + 'static) -> Self {
140        self.on_columns = Some(Box::new(f));
141        self
142    }
143}
144
145impl<T: 'static> View for Table<T> {
146    fn build(mut self, cx: &mut Cx) -> Node {
147        let scroll = self.model.scroll_view();
148        let (mut node, _) = Node::leaf(cx, Retained::into_super(scroll), (true, true), Size { w: 200.0, h: 120.0 });
149        if let crate::view::Kind::Leaf(l) = &node.kind {
150            // A scroll view has no useful fitting size: it takes what it's given.
151            l.content.set(Some(Size { w: 200.0, h: 120.0 }));
152        }
153        if !self.row_menu.is_empty() {
154            let tv = self.model.table_view();
155            let items = std::mem::take(&mut self.row_menu)
156                .into_iter()
157                .map(|(title, action)| {
158                    let (tv, model) = (tv.clone(), self.model.clone());
159                    crate::chrome::menu_item(&title, move || {
160                        let clicked = tv.clickedRow();
161                        let view_row = if clicked >= 0 { clicked } else { tv.selectedRow() };
162                        if let Some(row) = usize::try_from(view_row).ok().and_then(|r| model.row_at(r)) {
163                            action(row);
164                        }
165                    })
166                })
167                .collect();
168            let (menu, targets) = crate::chrome::build_menu(cx.mtm, items);
169            // SAFETY: the node keeps the menu's targets alive.
170            unsafe { tv.setMenu(Some(&menu)) };
171            targets.into_iter().for_each(|t| node.keep(t));
172        }
173        if self.row_drag {
174            self.model.set_row_drag(true);
175        }
176        if self.on_move.is_some() {
177            self.model.set_reorderable(true);
178        }
179        if self.on_files.is_some() {
180            let types: Vec<&str> = self.file_types.iter().map(String::as_str).collect();
181            self.model.set_file_drop(Some(&types));
182        }
183        if self.on_paste.is_some() {
184            self.model.set_pastes(true);
185        }
186        let model = self.model.clone();
187        let Table { on_select, on_activate, on_sort, on_toggle, on_edit, on_columns, on_move, on_files, on_paste, .. } = self;
188        let drain: Drain = Rc::new(move || {
189            for event in model.drain_events() {
190                match event {
191                    TableEvent::Selection(rows) => on_select.iter().for_each(|f| f(rows.clone())),
192                    TableEvent::Activate(row) => on_activate.iter().for_each(|f| f(row)),
193                    TableEvent::Sort(sort) => on_sort.iter().for_each(|f| f(sort.clone())),
194                    TableEvent::Toggle { row, column, value } => on_toggle.iter().for_each(|f| f((row, column.clone(), value))),
195                    TableEvent::Edit { row, column, value } => on_edit.iter().for_each(|f| f((row, column.clone(), value.clone()))),
196                    TableEvent::ColumnsChanged => on_columns.iter().for_each(|f| f(model.column_state())),
197                    TableEvent::RowsMoved { rows, before } => on_move.iter().for_each(|f| f((rows.clone(), before))),
198                    TableEvent::FilesDropped { paths, before } => on_files.iter().for_each(|f| f((paths.clone(), before))),
199                    TableEvent::Paste(text) => on_paste.iter().for_each(|f| f(text.clone())),
200                    _ => {}
201                }
202            }
203        });
204        register(&drain);
205        node.hold(drain);
206        node
207    }
208}
209
210/// A native table showing `model` (see [`Table`]).
211pub fn table<T: 'static>(model: &Rc<TableModel<T>>) -> Table<T> {
212    Table {
213        model: model.clone(),
214        on_select: None,
215        on_activate: None,
216        on_sort: None,
217        on_toggle: None,
218        on_edit: None,
219        on_columns: None,
220        on_move: None,
221        on_files: None,
222        file_types: Vec::new(),
223        on_paste: None,
224        row_drag: false,
225        row_menu: Vec::new(),
226    }
227}
228
229/// A native plain-text editor (`NSTextView` in a scroll view) showing a
230/// [`TextModel`]: input methods, spell checking, find, undo, text services
231/// and VoiceOver come from AppKit.
232pub struct TextEditor {
233    model: TextModel,
234    bound: Option<Signal<String>>,
235    on_change: Callback<String>,
236    on_selection: Callback<std::ops::Range<usize>>,
237    on_composition: Callback<Option<String>>,
238    shared_undo: bool,
239    highlight: Option<Rc<Highlight>>,
240    code: bool,
241    rich: Option<Rich>,
242}
243
244/// A rich text editor's settings (see [`TextEditor::rich`]).
245#[derive(Default)]
246struct Rich {
247    ruler: bool,
248    format_bar: bool,
249    rtf: Option<Signal<Vec<u8>>>,
250}
251
252type Highlight = dyn Fn(&str) -> Vec<(std::ops::Range<usize>, TextStyle)>;
253
254impl TextEditor {
255    /// Records edits in the window's undo history, with its text fields and
256    /// app-level changes ([`undoable`](crate::undoable)), instead of the
257    /// editor's own. Then ⌘Z anywhere in the window undoes the latest
258    /// change, wherever it was made.
259    pub fn shared_undo(mut self) -> Self {
260        self.shared_undo = true;
261        self
262    }
263
264    /// Binds the text two ways to `text`: edits set it (not while an input
265    /// method is composing); setting it replaces the editor's text (clearing
266    /// undo, like [`TextModel::set_text`]) unless it already matches.
267    pub fn bind(mut self, text: &Signal<String>) -> Self {
268        self.bound = Some(*text);
269        self
270    }
271
272    /// The text changed (typing, paste, undo, a committed composition).
273    pub fn on_change(mut self, f: impl Fn(String) + 'static) -> Self {
274        self.on_change = Some(Box::new(f));
275        self
276    }
277
278    /// The selection or caret moved (UTF-8 byte range).
279    pub fn on_selection(mut self, f: impl Fn(std::ops::Range<usize>) + 'static) -> Self {
280        self.on_selection = Some(Box::new(f));
281        self
282    }
283
284    /// An input method is composing (`Some(marked text)`) or stopped (`None`).
285    pub fn on_composition(mut self, f: impl Fn(Option<String>) + 'static) -> Self {
286        self.on_composition = Some(Box::new(f));
287        self
288    }
289
290    /// Styles the text: `f` gets the text and returns runs (UTF-8 byte
291    /// ranges) with their [`TextStyle`]s. It runs after every edit, before
292    /// it's drawn, and again when signals it reads change (a search term to
293    /// mark, say). See [`TextModel::set_highlighter`].
294    pub fn highlight(mut self, f: impl Fn(&str) -> Vec<(std::ops::Range<usize>, TextStyle)> + 'static) -> Self {
295        self.highlight = Some(Rc::new(f));
296        self
297    }
298
299    /// Syntax highlighting with `syntax` (e.g. [`Syntax::sql`](crate::Syntax::sql)),
300    /// for code: see [`code`](Self::code).
301    pub fn syntax(self, syntax: crate::Syntax) -> Self {
302        self.code().highlight(move |text| syntax.highlight(text))
303    }
304
305    /// Rich text: the user styles it (fonts, bold, colours, alignment,
306    /// lists, pictures) with ⌘B and friends, the font panel and
307    /// [`format_menu`](crate::format_menu); see [`TextModel::set_rich`].
308    /// Read and load it as RTF or HTML on the model, or bind it with
309    /// [`bind_rtf`](Self::bind_rtf).
310    pub fn rich(mut self) -> Self {
311        self.rich.get_or_insert_with(Rich::default);
312        self
313    }
314
315    /// Rich text with the ruler shown (margins, tabs, alignment, lists).
316    pub fn ruler(mut self) -> Self {
317        self.rich.get_or_insert_with(Rich::default).ruler = true;
318        self
319    }
320
321    /// Rich text with TextEdit's format bar above it (font, size, colours,
322    /// bold, italic, alignment, spacing, lists).
323    pub fn format_bar(mut self) -> Self {
324        self.rich.get_or_insert_with(Rich::default).format_bar = true;
325        self
326    }
327
328    /// Rich text bound two ways to `rtf`, its RTF (what a rich document
329    /// saves): edits, styling ones too, set it; setting it loads it
330    /// (clearing undo) unless it's what the editor shows.
331    pub fn bind_rtf(mut self, rtf: &Signal<Vec<u8>>) -> Self {
332        self.rich.get_or_insert_with(Rich::default).rtf = Some(*rtf);
333        self
334    }
335
336    /// An editor for code: quotes and dashes stay as typed (no smart
337    /// quotes), and no text replacement, autocorrection or spell checking
338    /// ([`TextModel::set_code_input`]). [`syntax`](Self::syntax) implies it.
339    pub fn code(mut self) -> Self {
340        self.code = true;
341        self
342    }
343}
344
345impl View for TextEditor {
346    fn build(self, cx: &mut Cx) -> Node {
347        let scroll = self.model.scroll_view();
348        let (mut node, _) = Node::leaf(cx, Retained::into_super(scroll), (true, true), Size { w: 200.0, h: 80.0 });
349        if let crate::view::Kind::Leaf(l) = &node.kind {
350            l.content.set(Some(Size { w: 200.0, h: 80.0 }));
351        }
352        if self.shared_undo {
353            self.model.share_undo(crate::undo::manager_for(&cx.container).as_deref());
354        }
355        if self.code {
356            self.model.set_code_input(true);
357        }
358        let rtf = self.rich.as_ref().and_then(|r| r.rtf);
359        if let Some(rich) = &self.rich {
360            self.model.set_rich(true);
361            self.model.set_ruler_visible(rich.ruler);
362            self.model.set_format_bar(rich.format_bar);
363        }
364        if let Some(rtf) = rtf {
365            // Signal → editor (skipped when it's what the editor shows).
366            let model = self.model.clone();
367            node.own(Effect::new(move || {
368                let want = rtf.get();
369                untrack(|| {
370                    if model.rtf() != want && !model.set_rtf(&want) && want.is_empty() {
371                        model.set_text("");
372                    }
373                });
374            }));
375        }
376        if let Some(f) = self.highlight.clone() {
377            let g = f.clone();
378            self.model.set_highlighter(Some(move |text: &str| g(text)));
379            // Restyle when signals the highlighter reads change.
380            let model = self.model.clone();
381            node.own(Effect::new(move || {
382                let _ = f(&untrack(|| model.text()));
383                untrack(|| model.restyle());
384            }));
385        }
386        if let Some(bound) = &self.bound {
387            // Signal → editor (skipped when equal: the editor is the source).
388            let (bound, model) = (*bound, self.model.clone());
389            node.own(Effect::new(move || {
390                let want = bound.get();
391                untrack(|| {
392                    if model.text() != want {
393                        model.set_text(&want);
394                    }
395                });
396            }));
397        }
398        let model = self.model.clone();
399        let TextEditor { bound, on_change, on_selection, on_composition, .. } = self;
400        let drain: Drain = Rc::new(move || {
401            for event in model.drain_events() {
402                match event {
403                    TextEvent::Changed => {
404                        if let Some(r) = &rtf {
405                            r.set_if_changed(model.rtf());
406                        }
407                        let text = model.text();
408                        if let Some(b) = &bound {
409                            b.set_if_changed(text.clone());
410                        }
411                        on_change.iter().for_each(|f| f(text.clone()));
412                    }
413                    TextEvent::Selection(r) => on_selection.iter().for_each(|f| f(r.clone())),
414                    TextEvent::Composition(c) => on_composition.iter().for_each(|f| f(c.clone())),
415                }
416            }
417        });
418        register(&drain);
419        node.hold(drain);
420        node
421    }
422}
423
424/// A native text editor showing `model` (see [`TextEditor`]).
425pub fn text_editor(model: &TextModel) -> TextEditor {
426    TextEditor { model: model.clone(), bound: None, on_change: None, on_selection: None, on_composition: None, shared_undo: false, highlight: None, code: false, rich: None }
427}