Guide API
Skip to main content

tvision_rs/widgets/table/
mod.rs

1//! A multi-column table: a column header with click-to-sort over a scrolling
2//! row list, with single or multi selection that follows a stable row key
3//! across sorting and reloads.
4//!
5//! # Structure
6//!
7//! [`Table`] is a [`Group`]-based composite with two children, each with its
8//! own [`ViewState`](crate::view::ViewState):
9//!
10//! - a one-row header that draws the column labels and the sort marker
11//!   (`▲`/`▼`); a click on a label sorts by that column, a second click flips
12//!   the direction (see [Columns](#columns) for the drags and the popup);
13//! - a row body that is a [`ListViewer`](crate::widgets::ListViewer) (one
14//!   column, item text = the formatted row), so keys, mouse, focus colours,
15//!   type-to-search and the vertical scroll bar behave exactly like a
16//!   [`ListBox`](crate::widgets::ListBox).
17//!
18//! The body is the selectable child: focusing the table focuses the body, and
19//! the `focused` state reaches it through the group. The header stretches
20//! horizontally and the body in both directions when the table is resized. The
21//! vertical scroll bar is an external sibling passed by id, the `ListBox`
22//! convention.
23//!
24//! # Layout
25//!
26//! Column widths follow the view width on every draw. Columns that do not fit
27//! shrink widest first, never below their
28//! [`min_width`](ColumnSpec::min_width); spare width goes to the
29//! [`flex`](ColumnSpec::flex) columns by weight (the cells the rounding leaves
30//! over go one each to the leftmost flex columns), or stays empty without
31//! one. When the columns still do not fit at their `min_width`s, they scroll
32//! horizontally by display cells: the header scrolls with the rows, the
33//! multi-select check column stays put, ←/→ scroll one cell (past the cell
34//! cursor's stops, see [Editing](#editing)), and an optional
35//! horizontal bar ([`Table::with_h_bar`]) shows and drives the offset
36//! ([`Table::h_offset`] / [`Table::set_h_offset`]); while the columns fit,
37//! the bar's range is 0. A resize changes the bars' page steps and the
38//! horizontal range; the table re-publishes them at once (every framework
39//! resize path calls [`on_bounds_changed`](View::on_bounds_changed)), or on
40//! its next event after app code called `change_bounds` directly.
41//!
42//! # Columns
43//!
44//! The user arranges the columns from the header:
45//!
46//! - **Resize:** drag the separator cell right of a label (the cell after the
47//!   last column too, or the last column's own last cell when it ends at the
48//!   view's right edge). The width follows the pointer, clamped to the column's
49//!   [`min_width`](ColumnSpec::min_width) and to
50//!   [`MAX_COLUMN_WIDTH`](layout::MAX_COLUMN_WIDTH); the column turns
51//!   [`fixed`](ColumnSpec::fixed) (a flex column stops stretching), so the
52//!   layout keeps that width and scrolls instead of shrinking it.
53//! - **Move:** press a label and drag off it; a marker shows the gap the
54//!   column lands in, the release moves it there. A press and release without
55//!   leaving the label sorts instead. Sort, width and hidden state belong to
56//!   the column, so they move with it.
57//! - **Show/hide:** a right-click on the header (or
58//!   [`Command::TABLE_COLUMNS`]) opens a popup listing every column with a
59//!   check mark; choosing one shows or hides it. The last visible column
60//!   stays: the popup cannot grey it out, so choosing it does nothing. Each
61//!   item posts [`Table::toggle_column_command`].
62//!
63//! [`ColumnSpec::resizable`] and [`ColumnSpec::movable`] turn the drags off
64//! per column. [`Table::column_layout`] / [`Table::set_column_layout`] read
65//! and restore the arrangement for persisting it.
66//!
67//! # Editing
68//!
69//! A column built with [`ColumnSpec::editable`] can be edited in place. While
70//! at least one visible column is editable the focused row shows a **cell
71//! cursor** ([`Role::TableCellCursor`](crate::theme::Role::TableCellCursor)):
72//! ←/→ move it between the editable columns in display order, scrolling it
73//! into view; at the first or last one the keys scroll the columns as usual.
74//! A click on an editable cell puts the cursor there.
75//!
76//! Enter or F2 on the cell cursor, or a double-click on an editable cell,
77//! opens an [`InputLine`](crate::widgets::InputLine) over the cell,
78//! pre-filled with its text, all selected, with the column's
79//! [`validator`](ColumnSpec::validator) if it has one. Enter stores the text
80//! through [`TableModel::set_cell`]; a validator or a `set_cell` that refuses
81//! it shows its message in an error box and the editor stays open. After a
82//! store the cell cursor stays on the cell, so the next Enter edits it again;
83//! the Enter that stores does nothing else (it does not press the dialog's
84//! default button). Esc cancels; so does losing the focus or a click outside
85//! the editor. Tab and Shift-Tab store and open the next/previous editable
86//! cell of the row; past the last (first) one the edit ends and the Tab goes
87//! on, moving the focus as usual. An unchanged text stores nothing. A
88//! dialog's OK (any end command but Cancel, through [`View::valid`]) stores
89//! an open edit first, and a refusal keeps the dialog open; Cancel cancels
90//! it. Without a cell cursor (no visible editable column) or without rows,
91//! the table does not use Enter, so it reaches the dialog's default button;
92//! with a cursor and a row it is always the table's, like F2, even when the
93//! cell has no room to show an editor. With modifiers (Ctrl, Alt, Shift)
94//! Enter never edits. A double-click on a cell
95//! that is not editable still chooses (single mode) or toggles (multi mode)
96//! the row, and Space still marks it in multi mode.
97//!
98//! The status line sees every key first. An app that binds F2 app-wide (the
99//! Turbo Vision `~F2~ Save` convention) turns F2 into its command before the
100//! table gets it; Enter and a double-click still open the editor there. Bind
101//! such keys only in a status def for the help context of the view that
102//! owns them.
103//!
104//! After a store the sort is re-applied and the focus follows the row's key.
105//! The editor stays over its cell through a re-sort, a horizontal scroll, a
106//! column resize or move, a [`Table::set_model`] reload (with the typed text)
107//! and a table resize (a resize scrolls the cell back into view). A cell
108//! scrolled off screen hides the editor without ending the edit: the next
109//! key scrolls it back and goes to the editor. When the cell is gone (its
110//! row left the model in a [`Table::set_model`] reload, its column was
111//! hidden) the edit ends without storing anything or showing a box — at once
112//! for a reload, at the table's next event for a hidden column — and the next
113//! key after that is used up, so an Enter meant for the editor cannot press
114//! the dialog's default button. A press on the header
115//! cancels the edit, and so does moving the focus to another row
116//! ([`Table::set_focused_key`], [`View::set_value`]).
117//!
118//! # Data
119//!
120//! The rows come from a [`TableModel`] ([`VecModel`] for plain strings). The
121//! table never reorders the model; it keeps a row permutation for the current
122//! sort. Every row has a [`RowKey`]: focus and the multi-selection follow the
123//! key through a re-sort and through [`Table::set_model`].
124//!
125//! # Wiring
126//!
127//! Build with [`Table::new`] and [`Table::with_model`] (plus
128//! [`Table::with_h_bar`] for a horizontal bar), insert, done: the table
129//! publishes its ranges and scroll steps to the bars on activation or on its
130//! first event.
131//! Reload later with [`Table::set_model`].
132//!
133//! ```rust,ignore
134//! let vsb_id = dlg.insert_child(Box::new(ScrollBar::new(Rect::new(41, 2, 42, 12))));
135//! let table = Table::new(
136//!     Rect::new(2, 2, 41, 12),
137//!     vec![ColumnSpec::new("Name", 16), ColumnSpec::new("Size", 8).right()],
138//!     Some(vsb_id),
139//! )
140//! .with_model(Box::new(VecModel::new(rows).with_keys(keys)));
141//! let table_id = dlg.insert_child(Box::new(table));
142//! ```
143//!
144//! # Notifications
145//!
146//! User actions broadcast with the **table's** id as `source`:
147//! [`Command::TABLE_SORT_CHANGED`] (header click, [`Command::TABLE_SORT_NEXT`],
148//! [`Command::TABLE_SORT_FLIP`]), [`Command::TABLE_SELECTION_CHANGED`] (multi
149//! mode: a click on a row's `[ ]` box, Space or a double-click toggled a row)
150//! and
151//! [`Command::LIST_ITEM_SELECTED`] (single mode: Space or a double-click chose
152//! the focused row) and [`Command::TABLE_COLUMNS_CHANGED`] (a column resized,
153//! moved, shown or hidden) and [`Command::TABLE_CELL_EDITED`] (a cell editor
154//! stored a new text). Programmatic setters do not broadcast — the caller already
155//! knows what it changed.
156//!
157//! # Turbo Vision heritage
158//!
159//! **tvision-rs extension**: no Turbo Vision counterpart. Like
160//! [`Splitter`](crate::widgets::Splitter) and
161//! [`TabBar`](crate::widgets::TabBar), it is listed on the guide's
162//! "Extensions beyond Turbo Vision" page. Its feature set and the pure helpers in
163//! [`layout`] are adapted from the `Table` of tvdocker
164//! (<https://github.com/supertorpe/tvdocker>, MIT, by supertorpe), rebuilt on
165//! the list viewer.
166
167mod body;
168mod columns;
169mod edit;
170pub mod layout;
171pub mod model;
172
173use std::cell::{Ref, RefCell};
174use std::collections::{BTreeSet, HashSet};
175use std::rc::Rc;
176
177use crate::command::Command;
178use crate::data::FieldValue;
179use crate::event::Event;
180use crate::view::{Context, DrawCtx, Group, Point, Rect, StateFlag, View, ViewId};
181use crate::widgets::list_viewer;
182
183use body::{TableBody, TableHeader};
184pub use columns::ColumnState;
185pub use layout::{Align, ColumnSpec, Separators, SortDir, ValidatorFactory};
186pub use model::{RowKey, SortKey, TableModel, VecModel};
187
188/// How a [`Table`] selects rows.
189#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
190pub enum SelectionMode {
191    /// The focused row is the selection (the [`value`](View::value) is its
192    /// key); Space or a double-click broadcasts
193    /// [`Command::LIST_ITEM_SELECTED`].
194    #[default]
195    Single,
196    /// A set of marked rows. The rows get a leading, fixed check column drawn
197    /// like [`CheckBoxes`](crate::widgets::CheckBoxes) (`[ ]` / `[X]`, blank
198    /// header cell). A click on a row's box, Space, or a double-click toggles
199    /// the row's mark and broadcasts [`Command::TABLE_SELECTION_CHANGED`]; a
200    /// click elsewhere on a row only focuses it. Marked rows also draw in the
201    /// list-selected colour.
202    Multi,
203}
204
205/// The state the table and its two children share.
206struct TableData {
207    model: Box<dyn TableModel>,
208    columns: Vec<ColumnSpec>,
209    /// Display order: `order[display_row] = model_row`.
210    order: Vec<usize>,
211    sort: Option<(usize, SortDir)>,
212    mode: SelectionMode,
213    selected: BTreeSet<RowKey>,
214    /// Mirror of the body's focused display row (the body updates it on every
215    /// focus move), for the table's `&self` accessors.
216    focused: usize,
217    /// User notifications queued by the children, broadcast by the table with
218    /// its own id after it routed the event.
219    pending: Vec<Command>,
220    /// Display order of the columns: `col_order[display_col] = model_col`
221    /// (hidden columns included). Sort, width and hidden state stay keyed by
222    /// the model column, so they follow a moved column.
223    col_order: Vec<usize>,
224    /// Header-local x of a column drag's drop indicator, drawn by the header.
225    drop_x: Option<i32>,
226    /// Horizontal scroll offset of the non-frozen columns, in display cells.
227    /// Clamped to the overflow wherever a layout is at hand (draw, publish).
228    h_offset: i32,
229    /// The model column the cell cursor was last put on; see
230    /// [`cursor_col`](TableData::cursor_col) for the one in effect.
231    cursor: Option<usize>,
232    /// Which column separators the table draws (see [`Separators`]).
233    separators: Separators,
234}
235
236type Shared = Rc<RefCell<TableData>>;
237
238impl TableData {
239    /// Recompute the display order from the model and the sort.
240    fn reorder(&mut self) {
241        self.order = match self.sort {
242            Some((col, dir)) => layout::sort_order(&*self.model, col, dir),
243            None => (0..self.model.row_count()).collect(),
244        };
245    }
246
247    /// The key of the row at display position `display`.
248    fn key_at(&self, display: usize) -> Option<RowKey> {
249        self.order.get(display).map(|&row| self.model.row_key(row))
250    }
251
252    /// The display position of the row with `key`.
253    fn display_of(&self, key: &RowKey) -> Option<usize> {
254        self.order
255            .iter()
256            .position(|&row| self.model.row_key(row) == *key)
257    }
258
259    /// Every key of the model.
260    fn all_keys(&self) -> HashSet<RowKey> {
261        (0..self.model.row_count())
262            .map(|row| self.model.row_key(row))
263            .collect()
264    }
265
266    /// Drop marks whose row no longer exists.
267    fn prune_selection(&mut self) {
268        let keys = self.all_keys();
269        self.selected.retain(|k| keys.contains(k));
270    }
271
272    /// The columns the layout runs over: in multi mode the fixed check column
273    /// leads, so the layout index of user column `c` is `c + check_cols()`.
274    fn layout_columns(&self) -> Vec<ColumnSpec> {
275        let mut cols = Vec::with_capacity(self.columns.len() + 1);
276        if self.mode == SelectionMode::Multi {
277            cols.push(layout::check_column());
278        }
279        cols.extend(self.display_columns());
280        cols
281    }
282
283    /// The column specs in display order.
284    fn display_columns(&self) -> Vec<ColumnSpec> {
285        self.col_order
286            .iter()
287            .map(|&c| self.columns[c].clone())
288            .collect()
289    }
290
291    /// The model column at layout index `layout_col` (`None` for the check
292    /// column or past the end).
293    fn model_col(&self, layout_col: usize) -> Option<usize> {
294        layout_col
295            .checked_sub(self.check_cols())
296            .and_then(|i| self.col_order.get(i).copied())
297    }
298
299    /// How many layout columns precede the user columns (1 in multi mode).
300    fn check_cols(&self) -> usize {
301        usize::from(self.mode == SelectionMode::Multi)
302    }
303
304    /// The model column of the first visible column at or after display
305    /// position `from` (wrapping), if any.
306    fn visible_from(&self, from: usize) -> Option<usize> {
307        let n = self.col_order.len();
308        (0..n)
309            .map(|step| self.col_order[(from + step) % n])
310            .find(|&c| !self.columns[c].hidden)
311    }
312
313    /// The display position of model column `col`.
314    fn display_pos(&self, col: usize) -> Option<usize> {
315        self.col_order.iter().position(|&c| c == col)
316    }
317}
318
319/// A multi-column table view. See the [module docs](self).
320pub struct Table {
321    group: Group,
322    data: Shared,
323    body_id: ViewId,
324    /// Set until the range and scroll steps have been published to the bars —
325    /// that needs a [`Context`], which construction and
326    /// [`change_bounds`](View::change_bounds) do not have.
327    needs_publish: bool,
328    /// The bars have been published once: a later resize re-publishes the
329    /// vertical page step with the resize formula, not the construction one.
330    published: bool,
331    /// The size changed since the last publish.
332    resized: bool,
333    /// A header press being tracked (resize or move), if any.
334    drag: Option<columns::HeaderDrag>,
335    /// Absolute screen position of the table's `(0, 0)` and the screen size,
336    /// cached by `draw`: the drag tracking localizes against the first, the
337    /// column popup is placed with both.
338    abs_origin: Point,
339    screen: Point,
340    /// The open cell editor, if any.
341    edit: Option<edit::CellEdit>,
342    /// An edit ended because its cell vanished: the next key is used up
343    /// (cleared by a click or a focus loss).
344    eat_key: bool,
345}
346
347impl Table {
348    /// A table at `bounds` (header on the first row, rows below) with
349    /// `columns`, wired to the optional vertical scroll bar `v_scroll_bar`.
350    /// It starts with an empty model; add rows with
351    /// [`with_model`](Self::with_model) or, after insertion,
352    /// [`set_model`](Self::set_model).
353    pub fn new(bounds: Rect, columns: Vec<ColumnSpec>, v_scroll_bar: Option<ViewId>) -> Self {
354        let mut group = Group::new(bounds);
355        // A click on an unfocused table both focuses it and acts (selects the
356        // row, sorts the column), like a list box.
357        group.state_mut().options.first_click = true;
358        let size = group.state().size;
359        let col_order = (0..columns.len()).collect();
360        let data: Shared = Rc::new(RefCell::new(TableData {
361            model: Box::new(VecModel::default()),
362            columns,
363            order: Vec::new(),
364            sort: None,
365            mode: SelectionMode::Single,
366            selected: BTreeSet::new(),
367            focused: 0,
368            pending: Vec::new(),
369            col_order,
370            drop_x: None,
371            h_offset: 0,
372            cursor: None,
373            separators: Separators::default(),
374        }));
375        group.insert(Box::new(TableHeader::new(size.x, data.clone())));
376        let body_bounds = Rect::new(0, 1, size.x, size.y.max(1));
377        let body_id = group.insert(Box::new(TableBody::new(
378            body_bounds,
379            v_scroll_bar,
380            data.clone(),
381        )));
382        Table {
383            group,
384            data,
385            body_id,
386            needs_publish: true,
387            published: false,
388            resized: false,
389            drag: None,
390            abs_origin: Point::new(0, 0),
391            screen: Point::new(0, 0),
392            edit: None,
393            eat_key: false,
394        }
395    }
396
397    /// Builder: wire the horizontal scroll bar `h_bar` (an external sibling,
398    /// like the vertical one). Its range is the columns' overflow past the
399    /// view: 0 while they fit. The table publishes range and steps itself.
400    pub fn with_h_bar(mut self, h_bar: ViewId) -> Self {
401        // The list viewer's bar wiring gives the bar its visibility and the
402        // changed/clicked broadcasts; the body turns its value into the
403        // table's offset.
404        self.body_mut().lv_state().h_scroll_bar = Some(h_bar);
405        self.needs_publish = true;
406        self
407    }
408
409    /// How far the columns are scrolled to the left, in display cells (0 when
410    /// they fit).
411    pub fn h_offset(&self) -> i32 {
412        let d = self.data.borrow();
413        body::row_layout(&d, self.group.state().size.x).clamp(d.h_offset)
414    }
415
416    /// Scroll the columns to `offset` display cells (clamped to the
417    /// overflow) and move the horizontal bar with them.
418    pub fn set_h_offset(&mut self, offset: i32, ctx: &mut Context) {
419        self.ensure_published(ctx);
420        self.data.borrow_mut().h_offset = offset;
421        self.publish_h(ctx);
422    }
423
424    /// Builder: the initial rows (no [`Context`] needed; the table publishes
425    /// them to its scroll bar on its first event).
426    pub fn with_model(mut self, model: Box<dyn TableModel>) -> Self {
427        let idx = self.load_model(model);
428        // The rows draw right away; the bar learns the range on publish.
429        let len = self.data.borrow().order.len();
430        self.body_mut().lv_state().range = len as i32;
431        self.place_focus(idx.min(len.saturating_sub(1)));
432        self.needs_publish = true;
433        self
434    }
435
436    /// Builder: the selection mode (default [`SelectionMode::Single`]).
437    pub fn with_selection_mode(self, mode: SelectionMode) -> Self {
438        self.data.borrow_mut().mode = mode;
439        self
440    }
441
442    /// The selection mode.
443    pub fn selection_mode(&self) -> SelectionMode {
444        self.data.borrow().mode
445    }
446
447    /// Builder: which column separators to draw (see [`Separators`]).
448    /// The default, [`Separators::Off`], leaves the one-cell separators
449    /// blank; [`Separators::Header`] draws the theme's vertical frame glyph
450    /// (`│` by default) in the header row only, making the resize handle
451    /// visible; [`Separators::All`] draws the header rule and the same rule
452    /// between every row's cells as well. When the columns leave spare width,
453    /// the header also rules the cell after the last column (its resize
454    /// handle); the rows leave that cell blank.
455    pub fn with_separators(self, separators: Separators) -> Self {
456        self.data.borrow_mut().separators = separators;
457        self
458    }
459
460    /// The column separators drawn between the table's columns.
461    pub fn separators(&self) -> Separators {
462        self.data.borrow().separators
463    }
464
465    /// The current model.
466    pub fn model(&self) -> Ref<'_, dyn TableModel> {
467        Ref::map(self.data.borrow(), |d| &*d.model)
468    }
469
470    /// Replace the rows. Focus stays on the same [`RowKey`] when it still
471    /// exists (else the focused position is clamped into the new rows), the
472    /// sort is re-applied, marks of vanished rows are dropped, and the scroll
473    /// bar's range is updated. Does not broadcast.
474    pub fn set_model(&mut self, model: Box<dyn TableModel>, ctx: &mut Context) {
475        let idx = self.load_model(model);
476        self.publish(idx, ctx);
477        // An open edit survives the reload, typed text and all, while its row
478        // is still there.
479        if self.edit.is_some() && !self.edit_alive() {
480            self.end_dead_edit(ctx);
481        }
482    }
483
484    /// Swap in `model`, re-apply the sort and prune the marks; return the
485    /// display row focus should land on: the focused key's new position, else
486    /// the old position (the caller clamps it).
487    fn load_model(&mut self, model: Box<dyn TableModel>) -> usize {
488        let key = self.focused_key();
489        let mut d = self.data.borrow_mut();
490        let old = d.focused;
491        d.model = model;
492        d.reorder();
493        d.prune_selection();
494        key.and_then(|k| d.display_of(&k)).unwrap_or(old)
495    }
496
497    /// Publish the range and the scroll steps to the bar, then focus display
498    /// row `idx` (clamped). The steps use the list viewer's construction
499    /// formula the first time and its resize formula (page = height, arrow
500    /// kept) after a resize, as `TListViewer::changeBounds` does.
501    fn publish(&mut self, idx: usize, ctx: &mut Context) {
502        let len = self.data.borrow().order.len() as i32;
503        let resize = self.published && self.resized;
504        let body = self.body_mut();
505        if resize {
506            list_viewer::on_bounds_changed(body, ctx);
507        } else {
508            list_viewer::update_steps(body, ctx);
509        }
510        list_viewer::set_range(body, len, ctx);
511        // Keep the viewport inside the new rows so a shrunken model does not
512        // leave the visible window scrolled past its end.
513        let lv = body.lv_state();
514        lv.top_item = lv.top_item.min((len - lv.state.size.y).max(0));
515        list_viewer::focus_item_num(body, idx as i32, ctx);
516        if len == 0 {
517            self.data.borrow_mut().focused = 0;
518        }
519        self.publish_h(ctx);
520        self.needs_publish = false;
521        self.published = true;
522        self.resized = false;
523    }
524
525    /// Clamp the horizontal offset to the current overflow and publish it,
526    /// the range (`0..=overflow`) and the steps (page = the visible width of
527    /// the scrolling columns, arrow = 1) to the horizontal bar.
528    fn publish_h(&mut self, ctx: &mut Context) {
529        let size_x = self.group.state().size.x;
530        let (off, max, page) = {
531            let mut d = self.data.borrow_mut();
532            let l = body::row_layout(&d, size_x);
533            d.h_offset = l.clamp(d.h_offset);
534            (d.h_offset, l.max_offset(), l.view)
535        };
536        // The h bar id is stored once, in the body's list-viewer wiring.
537        if let Some(h) = self.body_mut().lv_state().h_scroll_bar {
538            ctx.request_scroll_bar_params(
539                h,
540                Some(off),
541                Some(0),
542                Some(max),
543                Some(page.max(1)),
544                Some(1),
545            );
546        }
547    }
548
549    /// Publish to the bar if construction left that pending.
550    fn ensure_published(&mut self, ctx: &mut Context) {
551        if self.needs_publish {
552            let idx = self.data.borrow().focused;
553            self.publish(idx, ctx);
554        }
555    }
556
557    /// The row body, by downcast through the group.
558    fn body_mut(&mut self) -> &mut TableBody {
559        self.group
560            .child_mut(self.body_id)
561            .and_then(|v| v.as_any_mut())
562            .and_then(|a| a.downcast_mut::<TableBody>())
563            .expect("the table body is a fixed child of the table")
564    }
565
566    /// The display order: model row indices, top to bottom.
567    pub fn row_order(&self) -> Vec<usize> {
568        self.data.borrow().order.clone()
569    }
570
571    /// The model index of the focused row, `None` when there are no rows.
572    pub fn focused_row(&self) -> Option<usize> {
573        let d = self.data.borrow();
574        d.order.get(d.focused).copied()
575    }
576
577    /// The key of the focused row, `None` when there are no rows.
578    pub fn focused_key(&self) -> Option<RowKey> {
579        let d = self.data.borrow();
580        d.key_at(d.focused)
581    }
582
583    /// Move focus to the row with `key` (scrolling it into view). Returns
584    /// `false` if no row has that key.
585    pub fn set_focused_key(&mut self, key: &RowKey, ctx: &mut Context) -> bool {
586        self.ensure_published(ctx);
587        let idx = self.data.borrow().display_of(key);
588        if idx.is_some() {
589            self.cancel_edit_unless(key, ctx);
590        }
591        match idx {
592            Some(i) => {
593                list_viewer::focus_item_num(self.body_mut(), i as i32, ctx);
594                true
595            }
596            None => false,
597        }
598    }
599
600    /// Focus display row `idx` without a [`Context`] (no scroll-bar update):
601    /// the D10 context-free scatter path.
602    fn place_focus(&mut self, idx: usize) {
603        let lv = self.body_mut().lv_state();
604        let idx = idx as i32;
605        let rows = lv.state.size.y;
606        lv.focused = idx;
607        if idx < lv.top_item {
608            lv.top_item = idx;
609        } else if rows > 0 && idx >= lv.top_item + rows {
610            lv.top_item = idx - rows + 1;
611        }
612        self.data.borrow_mut().focused = idx as usize;
613    }
614
615    /// The current sort: column and direction, `None` for model order.
616    pub fn sort_spec(&self) -> Option<(usize, SortDir)> {
617        self.data.borrow().sort
618    }
619
620    /// Sort by column `col` (an index into the columns) in `dir`, keeping
621    /// focus on its row. An out-of-range column is ignored. Does not
622    /// broadcast.
623    pub fn sort_by(&mut self, col: usize, dir: SortDir, ctx: &mut Context) {
624        if col >= self.data.borrow().columns.len() {
625            return;
626        }
627        self.resort(Some((col, dir)), ctx);
628    }
629
630    /// Back to model order, keeping focus on its row. Does not broadcast.
631    pub fn clear_sort(&mut self, ctx: &mut Context) {
632        self.resort(None, ctx);
633    }
634
635    fn resort(&mut self, sort: Option<(usize, SortDir)>, ctx: &mut Context) {
636        self.ensure_published(ctx);
637        let key = self.focused_key();
638        let idx = {
639            let mut d = self.data.borrow_mut();
640            d.sort = sort;
641            d.reorder();
642            key.and_then(|k| d.display_of(&k)).unwrap_or(0)
643        };
644        list_viewer::focus_item_num(self.body_mut(), idx as i32, ctx);
645    }
646
647    /// User sort: apply and queue the broadcast.
648    fn user_sort(&mut self, sort: Option<(usize, SortDir)>, ctx: &mut Context) {
649        if sort.is_some() && sort != self.sort_spec() {
650            self.resort(sort, ctx);
651            self.data
652                .borrow_mut()
653                .pending
654                .push(Command::TABLE_SORT_CHANGED);
655        }
656    }
657
658    /// The sort a click on column `col` asks for: the same column flips,
659    /// another starts ascending.
660    fn click_sort(&self, col: usize) -> Option<(usize, SortDir)> {
661        match self.sort_spec() {
662            Some((c, dir)) if c == col => Some((c, dir.flip())),
663            _ => Some((col, SortDir::Asc)),
664        }
665    }
666
667    /// [`Command::TABLE_SORT_NEXT`]: the next visible column (in display
668    /// order), ascending.
669    fn next_sort(&self) -> Option<(usize, SortDir)> {
670        let d = self.data.borrow();
671        let from = d
672            .sort
673            .and_then(|(c, _)| d.display_pos(c))
674            .map_or(0, |p| p + 1);
675        d.visible_from(from).map(|c| (c, SortDir::Asc))
676    }
677
678    /// [`Command::TABLE_SORT_FLIP`]: flip the current column; with no sort,
679    /// the first visible column ascending.
680    fn flip_sort(&self) -> Option<(usize, SortDir)> {
681        match self.sort_spec() {
682            Some((c, dir)) => Some((c, dir.flip())),
683            None => self
684                .data
685                .borrow()
686                .visible_from(0)
687                .map(|c| (c, SortDir::Asc)),
688        }
689    }
690
691    /// Hide or show column `col`. A hidden column takes no space; a hidden
692    /// sort column keeps ordering the rows (its marker is just not shown).
693    pub fn set_column_hidden(&mut self, col: usize, hidden: bool) {
694        if let Some(c) = self.data.borrow_mut().columns.get_mut(col) {
695            c.hidden = hidden;
696        }
697        // The horizontal range changes with the visible columns.
698        self.needs_publish = true;
699    }
700
701    /// Whether column `col` is hidden (`false` for an unknown column).
702    pub fn is_column_hidden(&self, col: usize) -> bool {
703        self.data
704            .borrow()
705            .columns
706            .get(col)
707            .is_some_and(|c| c.hidden)
708    }
709
710    /// The keys of the marked rows, in model order (multi mode; empty in
711    /// single mode unless set programmatically).
712    pub fn selected_keys(&self) -> Vec<RowKey> {
713        let d = self.data.borrow();
714        (0..d.model.row_count())
715            .map(|row| d.model.row_key(row))
716            .filter(|k| d.selected.contains(k))
717            .collect()
718    }
719
720    /// Replace the marks with `keys`; keys without a row are ignored. Does not
721    /// broadcast.
722    pub fn set_selected_keys(&mut self, keys: impl IntoIterator<Item = RowKey>) {
723        let mut d = self.data.borrow_mut();
724        let all = d.all_keys();
725        d.selected = keys.into_iter().filter(|k| all.contains(k)).collect();
726    }
727
728    /// Clear every mark, leaving focus where it is. Does not broadcast.
729    pub fn clear_selection(&mut self) {
730        self.data.borrow_mut().selected.clear();
731    }
732
733    /// Broadcast the queued user notifications with this table's id as
734    /// `source`.
735    fn drain(&mut self, ctx: &mut Context) {
736        let pending = std::mem::take(&mut self.data.borrow_mut().pending);
737        let source = self.group.state().id();
738        for command in pending {
739            ctx.broadcast(command, source);
740        }
741    }
742}
743
744#[crate::delegate(to = group)]
745impl View for Table {
746    /// Publish the rows to the scroll bar if that is still pending, then let
747    /// the group fan the flag out. The owner sends `Active` to every child
748    /// when its window or dialog activates, so a table publishes even when no
749    /// event ever reaches it (another control holds focus).
750    fn set_state(&mut self, flag: StateFlag, enable: bool, ctx: &mut Context) {
751        self.ensure_published(ctx);
752        self.group.set_state(flag, enable, ctx);
753        if flag == StateFlag::Focused {
754            if !enable {
755                self.eat_key = false;
756            }
757            self.edit_focus(enable, ctx);
758        }
759    }
760
761    /// Remember where the table sits on screen (for the drag tracking and
762    /// the column popup), then draw the header and the rows.
763    fn draw(&mut self, ctx: &mut DrawCtx) {
764        self.abs_origin = ctx.origin();
765        self.screen = ctx.screen_size();
766        self.place_editor(false);
767        self.group.draw(ctx);
768    }
769
770    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
771        self.ensure_published(ctx);
772        match ev {
773            Event::KeyDown(_) if self.eat_key => {
774                self.eat_key = false;
775                ev.clear();
776                return;
777            }
778            Event::MouseDown(_) => self.eat_key = false,
779            _ => {}
780        }
781        self.close_dropped_edit(ctx);
782        let used = if self.edit.is_some() {
783            self.edit_event(ev, ctx)
784        } else {
785            self.start_event(ev, ctx)
786        };
787        if used || self.header_event(ev, ctx) {
788            ev.clear();
789        }
790        if let Event::Command(command) = *ev {
791            let sort = if command == Command::TABLE_SORT_NEXT {
792                Some(self.next_sort())
793            } else if command == Command::TABLE_SORT_FLIP {
794                Some(self.flip_sort())
795            } else {
796                None
797            };
798            if let Some(sort) = sort {
799                self.user_sort(sort, ctx);
800                ev.clear();
801            }
802        }
803        if !ev.is_nothing() {
804            self.group.handle_event(ev, ctx);
805        }
806        self.drain(ctx);
807    }
808
809    /// With a cell editor open, [`Command::CANCEL`] cancels the edit and any
810    /// other command commits it first — a dialog's OK, but also a window's
811    /// [`Command::CLOSE`] and the program's [`Command::QUIT`], as C++
812    /// `TInputLine::valid` validates for every command but `cmCancel`. A
813    /// refused text shows its box and vetoes the command, so closing never
814    /// drops what the field shows. [`Command::VALID`] and a focus release
815    /// leave the edit alone, and an edit whose cell is gone is discarded.
816    /// Then the children are checked as usual.
817    ///
818    /// The [`Command::TABLE_CELL_EDITED`] broadcast of a commit made here is
819    /// queued; when the command closes a modal dialog, it is delivered after
820    /// the dialog is gone. Views outside the dialog receive it, but its
821    /// `source` names a table that no longer exists and views inside the
822    /// dialog never see it.
823    fn valid(&mut self, cmd: Command, ctx: &mut Context) -> bool {
824        self.edit_valid(cmd, ctx) && self.group.valid(cmd, ctx)
825    }
826
827    /// Resize the header and the body (grow modes), and mark the bars for a
828    /// re-publish: the new size changes the vertical page step and the
829    /// horizontal range. Every framework resize path then calls
830    /// [`on_bounds_changed`](View::on_bounds_changed), which publishes at
831    /// once. The mark is a fallback for app code that calls `change_bounds`
832    /// directly: the publish then runs on the table's next event.
833    fn change_bounds(&mut self, bounds: Rect) {
834        let old = self.group.state().size;
835        self.group.change_bounds(bounds);
836        if self.group.state().size != old {
837            self.needs_publish = true;
838            self.resized = true;
839            // Keep the edited cell on screen under the editor.
840            self.place_editor(true);
841        }
842    }
843
844    /// Re-publish the bars for the new size, and hand the hook on to the
845    /// children the group re-bounded (the header and body publish nothing
846    /// themselves; this keeps the group's cascade intact for any child).
847    fn on_bounds_changed(&mut self, ctx: &mut Context) {
848        self.group.on_bounds_changed(ctx);
849        self.needs_publish = true;
850        self.resized = true;
851        self.ensure_published(ctx);
852    }
853
854    /// Single mode: the focused row's key as [`FieldValue::Text`] (`""` with
855    /// no rows). Multi mode: the marked keys as a [`FieldValue::List`] of
856    /// `Text`, in model order.
857    fn value(&self) -> Option<FieldValue> {
858        Some(match self.selection_mode() {
859            SelectionMode::Single => {
860                FieldValue::Text(self.focused_key().map(|k| k.0).unwrap_or_default())
861            }
862            SelectionMode::Multi => FieldValue::List(
863                self.selected_keys()
864                    .into_iter()
865                    .map(|k| FieldValue::Text(k.0))
866                    .collect(),
867            ),
868        })
869    }
870
871    /// Accepts the shapes [`value`](View::value) produces: single mode focuses
872    /// the row with the `Text` key (unknown keys are ignored), multi mode
873    /// replaces the marks with the `List` of `Text` keys. Other shapes are
874    /// ignored. Without a [`Context`] the scroll bar catches up on its next
875    /// sync; prefer [`set_value_ctx`](View::set_value_ctx).
876    fn set_value(&mut self, v: FieldValue) {
877        match (self.selection_mode(), v) {
878            (SelectionMode::Single, FieldValue::Text(k)) => {
879                let key = RowKey(k);
880                let idx = self.data.borrow().display_of(&key);
881                if let Some(i) = idx {
882                    self.drop_edit_unless(&key);
883                    self.place_focus(i);
884                }
885            }
886            (SelectionMode::Multi, FieldValue::List(items)) => {
887                self.set_selected_keys(items.into_iter().filter_map(|i| match i {
888                    FieldValue::Text(k) => Some(RowKey(k)),
889                    _ => None,
890                }));
891            }
892            _ => {}
893        }
894    }
895
896    /// Like [`set_value`](View::set_value), but a single-mode focus move also
897    /// updates the scroll bar.
898    fn set_value_ctx(&mut self, v: FieldValue, ctx: &mut Context) {
899        match (self.selection_mode(), v) {
900            (SelectionMode::Single, FieldValue::Text(k)) => {
901                self.set_focused_key(&RowKey(k), ctx);
902            }
903            (_, v) => self.set_value(v),
904        }
905    }
906
907    fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
908        Some(self)
909    }
910}
911
912#[cfg(test)]
913mod tests;