Guide API
Skip to main content

tvision_rs/widgets/table/
columns.rs

1//! Header interaction: resize a column by dragging the separator right of its
2//! label, move it by dragging the label, show or hide columns from a popup,
3//! and read or restore the whole column layout.
4//!
5//! The table, not the header child, handles every header press: the drags
6//! track the mouse with the table as the tracked view (so the release reaches
7//! [`Table::handle_event`] and its notifications go out with the table's id),
8//! and a press-release without a drag sorts, which needs the row body.
9
10use std::sync::Mutex;
11
12use super::body::{TEXT_X, row_layout};
13use super::layout::MAX_COLUMN_WIDTH;
14use super::{Table, TableData};
15use crate::capture::TrackMask;
16use crate::command::Command;
17use crate::event::{Event, MouseEvent};
18use crate::menu::{Menu, popup_menu};
19use crate::view::{Context, Point, View};
20use crate::widgets::cluster::check_box;
21
22/// The persistent state of one column, as [`Table::column_layout`] reports it
23/// and [`Table::set_column_layout`] restores it.
24#[derive(Clone, Debug, PartialEq, Eq)]
25pub struct ColumnState {
26    /// The column's index in the model (and in the `columns` the table was
27    /// built with).
28    pub column: usize,
29    /// Its display position, 0 = leftmost.
30    pub order: usize,
31    /// Its [`width`](super::ColumnSpec::width).
32    pub width: i32,
33    /// Its [`flex`](super::ColumnSpec::flex) weight (a user resize sets 0).
34    pub flex: u16,
35    /// Whether the layout keeps it at `width` (a user resize sets it; see
36    /// [`ColumnSpec::fixed`](super::ColumnSpec::fixed)).
37    pub fixed: bool,
38    /// Whether it is hidden.
39    pub hidden: bool,
40}
41
42/// A header press being tracked.
43pub(super) enum HeaderDrag {
44    /// Dragging the separator right of model column `col`, which was `start`
45    /// cells wide on screen when pressed at header x `press_x`.
46    Resize {
47        col: usize,
48        press_x: i32,
49        start: i32,
50        changed: bool,
51    },
52    /// Pressed on the label of model column `col`; `moving` once the pointer
53    /// left the label's cell (a movable column only). A release without a
54    /// move sorts.
55    Move { col: usize, moving: bool },
56}
57
58/// The prefix of the per-column toggle commands.
59const TOGGLE_PREFIX: &str = "tv.table_toggle_column.";
60
61/// The command a column popup item posts for model column `col` (see
62/// [`Table::toggle_column_command`]). Each name is built once and kept for
63/// the life of the process, since a [`Command`] holds a `&'static str`.
64fn toggle_command(col: usize) -> Command {
65    static NAMES: Mutex<Vec<&'static str>> = Mutex::new(Vec::new());
66    let mut names = NAMES.lock().unwrap_or_else(|e| e.into_inner());
67    while names.len() <= col {
68        let name = format!("{TOGGLE_PREFIX}{}", names.len());
69        names.push(Box::leak(name.into_boxed_str()));
70    }
71    Command::custom(names[col])
72}
73
74/// The model column a toggle command names.
75fn toggle_index(command: Command) -> Option<usize> {
76    command.name().strip_prefix(TOGGLE_PREFIX)?.parse().ok()
77}
78
79impl TableData {
80    /// How many columns are not hidden.
81    fn visible_count(&self) -> usize {
82        self.columns.iter().filter(|c| !c.hidden).count()
83    }
84}
85
86impl Table {
87    /// The command that shows or hides model column `col` when it reaches
88    /// the focused table — what the column popup's items post. Bind it to a
89    /// key or a menu item to toggle a column directly; like the popup, it
90    /// never hides the last visible column, and it broadcasts
91    /// [`Command::TABLE_COLUMNS_CHANGED`].
92    pub fn toggle_column_command(col: usize) -> Command {
93        toggle_command(col)
94    }
95
96    /// Every column's state, in model order: the display position, width,
97    /// flex weight, `fixed` flag and hidden flag. Store it and hand it to
98    /// [`set_column_layout`](Self::set_column_layout) to restore what the
99    /// user arranged.
100    pub fn column_layout(&self) -> Vec<ColumnState> {
101        let d = self.data.borrow();
102        d.columns
103            .iter()
104            .enumerate()
105            .map(|(column, c)| ColumnState {
106                column,
107                order: d.display_pos(column).unwrap_or(column),
108                width: c.width,
109                flex: c.flex,
110                fixed: c.fixed,
111                hidden: c.hidden,
112            })
113            .collect()
114    }
115
116    /// Restore a [`column_layout`](Self::column_layout). Entries for unknown
117    /// columns are ignored; the columns `layout` does not name keep their
118    /// state and follow the named ones in their current order. Widths are
119    /// clamped to the column's `min_width` (at least 1) and to
120    /// [`MAX_COLUMN_WIDTH`].
121    /// Does not broadcast; the bars catch up on the table's next event.
122    pub fn set_column_layout(&mut self, layout: &[ColumnState]) {
123        let mut d = self.data.borrow_mut();
124        let n = d.columns.len();
125        let mut named: Vec<&ColumnState> = layout.iter().filter(|s| s.column < n).collect();
126        named.sort_by_key(|s| s.order);
127        let mut order: Vec<usize> = Vec::with_capacity(n);
128        for s in &named {
129            if !order.contains(&s.column) {
130                order.push(s.column);
131            }
132            let c = &mut d.columns[s.column];
133            c.width = s.width.clamp(width_floor(c), MAX_COLUMN_WIDTH);
134            c.flex = s.flex;
135            c.fixed = s.fixed;
136            c.hidden = s.hidden;
137        }
138        let rest: Vec<usize> = d
139            .col_order
140            .iter()
141            .copied()
142            .filter(|c| !order.contains(c))
143            .collect();
144        order.extend(rest);
145        d.col_order = order;
146        drop(d);
147        self.needs_publish = true;
148    }
149
150    /// The column popup, the column drags and the toggle commands. Returns
151    /// whether `ev` was used.
152    pub(super) fn header_event(&mut self, ev: &Event, ctx: &mut Context) -> bool {
153        match *ev {
154            Event::MouseDown(me) if me.position.y == 0 && self.drag.is_none() => {
155                self.header_press(me, ctx);
156                true
157            }
158            Event::MouseMove(me) if self.drag.is_some() => {
159                self.header_drag(me.position.x, ctx);
160                true
161            }
162            // Only a tracked release ends a drag: an untracked up reaching
163            // the table through normal routing is left alone.
164            Event::MouseUp(me) if self.drag.is_some() => {
165                self.header_release(me.position, ctx);
166                true
167            }
168            Event::Command(c) if c == Command::TABLE_COLUMNS => {
169                self.open_column_popup(Point::new(TEXT_X, 0), ctx);
170                true
171            }
172            Event::Command(c) => match toggle_index(c) {
173                Some(col) if col < self.data.borrow().columns.len() => {
174                    self.user_toggle(col, ctx);
175                    true
176                }
177                _ => false,
178            },
179            _ => false,
180        }
181    }
182
183    /// A press on the header row: right button → the column popup; left
184    /// button on a resize handle → start resizing, on a label → start a
185    /// move-or-sort.
186    fn header_press(&mut self, me: MouseEvent, ctx: &mut Context) {
187        if me.buttons.right {
188            self.open_column_popup(me.position, ctx);
189            return;
190        }
191        if !me.buttons.left {
192            return;
193        }
194        let x = me.position.x;
195        let drag = {
196            let d = self.data.borrow();
197            let l = row_layout(&d, self.group.state().size.x);
198            let tx = x - TEXT_X;
199            if let Some(lc) = l.separator_at(tx, d.h_offset)
200                && let Some(col) = d.model_col(lc)
201            {
202                d.columns[col].resizable.then_some(HeaderDrag::Resize {
203                    col,
204                    press_x: x,
205                    start: l.widths[lc],
206                    changed: false,
207                })
208            } else {
209                // Layout columns before `frozen` are the check column: its
210                // blank header cell does nothing.
211                l.column_at(tx, d.h_offset)
212                    .filter(|&lc| lc >= l.frozen)
213                    .and_then(|lc| d.model_col(lc))
214                    .map(|col| HeaderDrag::Move { col, moving: false })
215            }
216        };
217        let Some(drag) = drag else { return };
218        match self.group.state().id() {
219            Some(id) => {
220                ctx.start_mouse_track(
221                    id,
222                    self.abs_origin,
223                    TrackMask {
224                        mouse_move: true,
225                        ..Default::default()
226                    },
227                );
228                self.drag = Some(drag);
229            }
230            // Not inserted, so nothing can track the drag: a label press
231            // sorts at once.
232            None => {
233                if let HeaderDrag::Move { col, .. } = drag {
234                    let sort = self.click_sort(col);
235                    self.user_sort(sort, ctx);
236                }
237            }
238        }
239    }
240
241    /// The pointer moved to header x `x` while a press is held.
242    fn header_drag(&mut self, x: i32, ctx: &mut Context) {
243        match self.drag {
244            Some(HeaderDrag::Resize {
245                col,
246                press_x,
247                start,
248                ref mut changed,
249            }) => {
250                let mut d = self.data.borrow_mut();
251                let c = &mut d.columns[col];
252                let width = start
253                    .saturating_add(x - press_x)
254                    .clamp(width_floor(c), MAX_COLUMN_WIDTH);
255                if !*changed && width == start {
256                    return;
257                }
258                // A dragged width is a fixed width.
259                *changed = true;
260                c.width = width;
261                c.flex = 0;
262                c.fixed = true;
263                drop(d);
264                self.publish_h(ctx);
265            }
266            Some(HeaderDrag::Move {
267                col,
268                ref mut moving,
269            }) => {
270                let mut d = self.data.borrow_mut();
271                if !*moving {
272                    let off_label = d.columns[col].movable
273                        && label_span(&d, self.group.state().size.x, col)
274                            .is_none_or(|(s, e)| x < s || x >= e);
275                    if !off_label {
276                        return;
277                    }
278                    *moving = true;
279                }
280                let size_x = self.group.state().size.x;
281                d.drop_x = drop_gap(&d, size_x, x).and_then(|(_, gx)| gx);
282            }
283            None => {}
284        }
285    }
286
287    /// The press ends at table-local `at`: commit a resize or a move, or
288    /// sort on a click (released on the pressed label; a drag off it
289    /// cancels).
290    fn header_release(&mut self, at: Point, ctx: &mut Context) {
291        let x = at.x;
292        let Some(drag) = self.drag.take() else { return };
293        self.data.borrow_mut().drop_x = None;
294        match drag {
295            HeaderDrag::Resize { changed, .. } => {
296                if changed {
297                    self.columns_changed();
298                }
299            }
300            HeaderDrag::Move { col, moving: false } => {
301                let on_label = at.y == 0
302                    && label_span(&self.data.borrow(), self.group.state().size.x, col)
303                        .is_some_and(|(s, e)| (s..e).contains(&x));
304                if on_label {
305                    let sort = self.click_sort(col);
306                    self.user_sort(sort, ctx);
307                }
308            }
309            HeaderDrag::Move { col, moving: true } => {
310                let size_x = self.group.state().size.x;
311                let moved = {
312                    let mut d = self.data.borrow_mut();
313                    match drop_gap(&d, size_x, x) {
314                        Some((gap, _)) => move_column(&mut d, size_x, col, gap),
315                        None => false,
316                    }
317                };
318                if moved {
319                    self.publish_h(ctx);
320                    self.columns_changed();
321                }
322            }
323        }
324    }
325
326    /// Open the column popup at table-local `at`: one item per column in
327    /// display order, `[X]` when shown, posting its toggle command.
328    fn open_column_popup(&mut self, at: Point, ctx: &mut Context) {
329        let menu = {
330            let d = self.data.borrow();
331            d.col_order
332                .iter()
333                .fold(Menu::builder(), |b, &c| {
334                    let spec = &d.columns[c];
335                    // The menu reads `~` as a hotkey marker and has no
336                    // escape for it: drop it so no stray hotkey appears.
337                    let name: String = spec.label.chars().filter(|&c| c != '~').collect();
338                    let label = format!("{} {name}", check_box(!spec.hidden));
339                    b.command(label, toggle_command(c))
340                })
341                .build()
342        };
343        // Before the first draw the screen size is unknown; the owner's size
344        // is the best bound there is.
345        let screen = if self.screen.x > 0 && self.screen.y > 0 {
346            self.screen
347        } else {
348            ctx.owner_size()
349        };
350        popup_menu(self.abs_origin + at, menu, screen, ctx);
351    }
352
353    /// Show or hide model column `col` for the user; the last visible column
354    /// stays.
355    fn user_toggle(&mut self, col: usize, ctx: &mut Context) {
356        {
357            let mut d = self.data.borrow_mut();
358            let hide = !d.columns[col].hidden;
359            if hide && d.visible_count() <= 1 {
360                return;
361            }
362            d.columns[col].hidden = hide;
363        }
364        self.publish_h(ctx);
365        self.columns_changed();
366    }
367
368    /// Queue [`Command::TABLE_COLUMNS_CHANGED`] for the drain.
369    fn columns_changed(&mut self) {
370        self.data
371            .borrow_mut()
372            .pending
373            .push(Command::TABLE_COLUMNS_CHANGED);
374    }
375}
376
377/// The narrowest a user resize or a restored layout may make column `c`: its
378/// `min_width`, at least 1 and at most [`MAX_COLUMN_WIDTH`].
379fn width_floor(c: &super::ColumnSpec) -> i32 {
380    c.min_width.clamp(1, MAX_COLUMN_WIDTH)
381}
382
383/// The header x range `[start, end)` model column `col`'s label covers on
384/// screen (it may reach outside the view), `None` when it takes no cells.
385fn label_span(d: &TableData, size_x: i32, col: usize) -> Option<(i32, i32)> {
386    let l = row_layout(d, size_x);
387    let lc = d.display_pos(col)? + l.frozen;
388    let (_, s, e) = l.spans().into_iter().find(|&(i, _, _)| i == lc)?;
389    let x = |cx| TEXT_X + l.text_x(cx, d.h_offset);
390    Some((x(s), x(e)))
391}
392
393/// The gap a column dropped at header x `x` lands in: its index among the
394/// visible scrolling columns (0 = before the first, `n` = after the last),
395/// and the header x of the indicator when that gap is on screen. The gap is
396/// the one before the first column whose middle lies right of `x`.
397fn drop_gap(d: &TableData, size_x: i32, x: i32) -> Option<(usize, Option<i32>)> {
398    let l = row_layout(d, size_x);
399    let spans = l.spans();
400    let last = spans.last()?.2;
401    // The pointer in content cells (unclamped: it may be off either edge).
402    let cx = (x - TEXT_X - l.frozen_width).saturating_add(l.clamp(d.h_offset));
403    let gap = spans
404        .iter()
405        .position(|&(_, s, e)| cx < s + (e - s) / 2)
406        .unwrap_or(spans.len());
407    // The separator cell before the gap's column, or the cell after the last.
408    let mark = spans.get(gap).map_or(last, |&(_, s, _)| s - 1);
409    let gx = TEXT_X + l.text_x(mark, d.h_offset);
410    // On screen: from the cell before the scrolling part to its last cell.
411    let lo = TEXT_X + l.frozen_width - 1;
412    let hi = (TEXT_X + l.frozen_width + l.view).min(size_x - 1);
413    Some((gap, (lo..=hi).contains(&gx).then_some(gx.max(0))))
414}
415
416/// Move model column `col` into visible gap `gap` (see [`drop_gap`]);
417/// returns whether the order changed. Hidden columns keep their places
418/// relative to their neighbours.
419fn move_column(d: &mut TableData, size_x: i32, col: usize, gap: usize) -> bool {
420    let l = row_layout(d, size_x);
421    let visible: Vec<usize> = l
422        .spans()
423        .into_iter()
424        .filter_map(|(lc, _, _)| d.model_col(lc))
425        .collect();
426    let before = visible.get(gap).copied();
427    let after = gap.checked_sub(1).and_then(|g| visible.get(g)).copied();
428    if before == Some(col) || after == Some(col) {
429        return false;
430    }
431    let Some(from) = d.display_pos(col) else {
432        return false;
433    };
434    d.col_order.remove(from);
435    let to = match (before, after) {
436        (Some(b), _) => d.display_pos(b),
437        (None, Some(a)) => d.display_pos(a).map(|p| p + 1),
438        (None, None) => None,
439    };
440    match to {
441        Some(to) => d.col_order.insert(to, col),
442        None => {
443            d.col_order.insert(from, col);
444            return false;
445        }
446    }
447    true
448}