Guide API
Skip to main content

tvision_rs/widgets/table/
layout.rs

1//! Column specs and the pure layout/format/sort helpers behind the table's
2//! header and body. Nothing here touches a view; everything is unit-tested.
3//!
4//! The helpers are adapted from tvdocker's table (MIT, by supertorpe):
5//! widest-first column shrinking, ellipsis truncation, the header sort marker,
6//! and the stable sort.
7
8use std::fmt;
9use std::rc::Rc;
10
11use unicode_segmentation::UnicodeSegmentation;
12
13use super::model::TableModel;
14use crate::text;
15use crate::validate::Validator;
16
17/// Column alignment inside its cell.
18#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
19pub enum Align {
20    /// Text starts at the left edge of the cell (the default).
21    #[default]
22    Left,
23    /// Text ends at the right edge of the cell — the usual choice for numbers.
24    Right,
25}
26
27/// A sort direction.
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub enum SortDir {
30    /// Smallest first; the header shows `▲`.
31    Asc,
32    /// Largest first; the header shows `▼`.
33    Desc,
34}
35
36impl SortDir {
37    /// The other direction.
38    pub fn flip(self) -> SortDir {
39        match self {
40            SortDir::Asc => SortDir::Desc,
41            SortDir::Desc => SortDir::Asc,
42        }
43    }
44
45    /// The header marker glyph.
46    pub fn marker(self) -> char {
47        match self {
48            SortDir::Asc => '▲',
49            SortDir::Desc => '▼',
50        }
51    }
52}
53
54/// Which column separators a [`Table`](super::Table) draws between its
55/// columns. A separator is always one cell wide; this only chooses whether
56/// that cell holds a visible rule, so the layout never shifts. The rule glyph
57/// itself belongs to the theme (its [`frame_v`](crate::theme::Glyphs::frame_v));
58/// the draw that renders it passes it in, like the `ListViewer` divider does.
59#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
60pub enum Separators {
61    /// One blank cell between columns, with no visible rule (the default). Named
62    /// `Off` rather than `None` so a `use Separators::*` does not shadow
63    /// [`Option::None`].
64    #[default]
65    Off,
66    /// The rule in the header row only, so the resize handle is visible;
67    /// the rows keep blank separators. When the columns leave spare width,
68    /// the header also rules the cell after the last column, which is that
69    /// column's resize handle.
70    Header,
71    /// The rule in the header and between every row's cells. The header
72    /// rules the cell after the last column as in [`Separators::Header`];
73    /// the rows rule only the cells between columns and leave that one blank.
74    All,
75}
76
77impl Separators {
78    /// The character a header separator cell draws: `rule` where the mode
79    /// rules, blank where it does not.
80    pub(crate) fn header_char(self, rule: char) -> char {
81        match self {
82            Separators::Off => ' ',
83            Separators::Header | Separators::All => rule,
84        }
85    }
86
87    /// The character a row separator cell draws: `rule` only in
88    /// [`Separators::All`], blank otherwise.
89    pub(crate) fn row_char(self, rule: char) -> char {
90        match self {
91            Separators::All => rule,
92            Separators::Off | Separators::Header => ' ',
93        }
94    }
95}
96
97/// One column of a [`Table`](super::Table).
98#[derive(Clone, Debug, PartialEq, Eq)]
99pub struct ColumnSpec {
100    /// The header label.
101    pub label: String,
102    /// Preferred width in cells.
103    pub width: i32,
104    /// The narrowest the layout may shrink this column to (at least 1).
105    pub min_width: i32,
106    /// Alignment of the label and the cells.
107    pub align: Align,
108    /// A hidden column takes no space at all (no cell, no separator).
109    pub hidden: bool,
110    /// Stretch weight (0 = fixed, the default). When the visible columns are
111    /// narrower than the table, the spare cells go to the flex columns in
112    /// proportion to their weights.
113    pub flex: u16,
114    /// The user may change the width by dragging the separator right of the
115    /// label (default `true`).
116    pub resizable: bool,
117    /// The user may move the column by dragging its label (default `true`).
118    pub movable: bool,
119    /// The layout never shrinks this column below `width`: it overflows and
120    /// scrolls instead. A user resize sets it (and clears `flex`), so a
121    /// dragged width holds.
122    pub fixed: bool,
123    /// The user may edit the cells (default `false`): the cell cursor visits
124    /// the column and F2 or a double-click opens an editor on it.
125    pub editable: bool,
126    /// Builds a fresh [`Validator`] for every cell editor opened on this
127    /// column (none by default).
128    pub validator: Option<ValidatorFactory>,
129}
130
131/// A shareable factory of [`Validator`]s for a column's cell editors: each
132/// editor owns its validator, so the column keeps the recipe, not an
133/// instance. Two factories are equal only when they are the same one.
134#[derive(Clone)]
135pub struct ValidatorFactory(Rc<dyn Fn() -> Box<dyn Validator>>);
136
137impl ValidatorFactory {
138    /// Wrap `make`.
139    pub fn new(make: Box<dyn Fn() -> Box<dyn Validator>>) -> Self {
140        ValidatorFactory(Rc::from(make))
141    }
142
143    /// A new validator.
144    pub fn make(&self) -> Box<dyn Validator> {
145        (self.0)()
146    }
147}
148
149impl fmt::Debug for ValidatorFactory {
150    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
151        f.write_str("ValidatorFactory")
152    }
153}
154
155impl PartialEq for ValidatorFactory {
156    fn eq(&self, other: &Self) -> bool {
157        Rc::ptr_eq(&self.0, &other.0)
158    }
159}
160
161impl Eq for ValidatorFactory {}
162
163impl ColumnSpec {
164    /// A left-aligned, visible column of preferred `width`, shrinkable to 1.
165    pub fn new(label: impl Into<String>, width: i32) -> Self {
166        ColumnSpec {
167            label: label.into(),
168            width,
169            min_width: 1,
170            align: Align::Left,
171            hidden: false,
172            flex: 0,
173            resizable: true,
174            movable: true,
175            fixed: false,
176            editable: false,
177            validator: None,
178        }
179    }
180
181    /// Builder: the narrowest this column may be shrunk to.
182    pub fn min_width(mut self, min_width: i32) -> Self {
183        self.min_width = min_width;
184        self
185    }
186
187    /// Builder: right-align the label and the cells.
188    pub fn right(mut self) -> Self {
189        self.align = Align::Right;
190        self
191    }
192
193    /// Builder: set the alignment.
194    pub fn align(mut self, align: Align) -> Self {
195        self.align = align;
196        self
197    }
198
199    /// Builder: start hidden.
200    pub fn hidden(mut self, hidden: bool) -> Self {
201        self.hidden = hidden;
202        self
203    }
204
205    /// Builder: let this column stretch into spare width with `weight`
206    /// (0 = fixed). `width` is the width it starts from; a flex column is at
207    /// least `min_width` wide, so `ColumnSpec::new("Notes", 0).flex(1)` simply
208    /// fills the rest.
209    pub fn flex(mut self, weight: u16) -> Self {
210        self.flex = weight;
211        self
212    }
213
214    /// Builder: whether the user may drag the column's width (default
215    /// `true`).
216    pub fn resizable(mut self, resizable: bool) -> Self {
217        self.resizable = resizable;
218        self
219    }
220
221    /// Builder: whether the user may drag the column to another position
222    /// (default `true`).
223    pub fn movable(mut self, movable: bool) -> Self {
224        self.movable = movable;
225        self
226    }
227
228    /// Builder: keep the column at `width` instead of shrinking it to fit
229    /// (default `false`; see [`fixed`](Self::fixed)).
230    pub fn fixed(mut self, fixed: bool) -> Self {
231        self.fixed = fixed;
232        self
233    }
234
235    /// Builder: whether the user may edit the cells (default `false`; see
236    /// [`editable`](Self::editable)).
237    pub fn editable(mut self, editable: bool) -> Self {
238        self.editable = editable;
239        self
240    }
241
242    /// Builder: give every cell editor on this column a validator from
243    /// `make` (a fresh one per editor), as
244    /// [`InputLine::set_validator`](crate::widgets::InputLine::set_validator)
245    /// would. It filters the typing and checks the text on commit.
246    pub fn validator(mut self, make: Box<dyn Fn() -> Box<dyn Validator>>) -> Self {
247        self.validator = Some(ValidatorFactory::new(make));
248        self
249    }
250}
251
252/// The widest a column is ever laid out, in cells. Every cell is padded to its
253/// column width when drawn, so an unbounded width would allocate without
254/// bound; a user resize and [`Table::set_column_layout`](super::Table::set_column_layout)
255/// clamp to it as well.
256pub const MAX_COLUMN_WIDTH: i32 = 1024;
257
258/// Width of the multi-select check column: the `[ ]` box of
259/// [`CheckBoxes`](crate::widgets::CheckBoxes).
260pub const CHECK_WIDTH: i32 = 3;
261
262/// The fixed, non-shrinkable check column a multi-select table lays out in
263/// front of its own columns (blank label).
264pub fn check_column() -> ColumnSpec {
265    ColumnSpec::new("", CHECK_WIDTH).min_width(CHECK_WIDTH)
266}
267
268/// Prefix `rest` (an already joined line) with the check-column cell `check`
269/// of width `w0`, separated by `sep` exactly as the other columns are. A
270/// zero-width check column (no room at all) adds nothing.
271pub fn with_check_cell(w0: i32, check: &str, rest: String, sep: char) -> String {
272    if w0 <= 0 {
273        return rest;
274    }
275    let cell = pad_cell(check, w0, Align::Left);
276    if rest.is_empty() {
277        cell
278    } else {
279        format!("{cell}{sep}{rest}")
280    }
281}
282
283/// Distribute `avail` cells over `cols`: hidden columns get 0; the visible ones
284/// keep their preferred width while everything (plus one separator between
285/// neighbouring visible columns) fits, else the currently widest shrinkable
286/// column loses one cell per pass until it fits or every column sits at its
287/// `min_width` (a [`fixed`](ColumnSpec::fixed) one at its `width`). Shrinking
288/// comes first, scrolling second: a layout that still does not fit, even one
289/// whose separators alone fill `avail`, keeps every column at that floor and
290/// is wider than `avail`; the table scrolls it horizontally. Spare cells go
291/// to the [`flex`](ColumnSpec::flex) columns by weight (see [`stretch`]);
292/// without one they stay empty. With no visible column, or no cell at all
293/// (`avail` ≤ 0), every width is 0.
294pub fn layout_widths(cols: &[ColumnSpec], avail: i32) -> Vec<i32> {
295    let mut widths: Vec<i32> = cols.iter().map(preferred_width).collect();
296    // A visible column of width 0 renders nothing and gets no separator
297    // (as in `join_cells` / `column_at`), so it does not count here either.
298    let visible = widths.iter().filter(|&&w| w > 0).count() as i32;
299    if visible == 0 || avail <= 0 {
300        return vec![0; cols.len()];
301    }
302    // At or below 0 when the separators take every cell: the loop below
303    // then shrinks each column to its floor and the layout overflows.
304    let budget = avail - (visible - 1);
305    let over = sum_widths(&widths).saturating_sub(budget);
306    if over > 0 {
307        shrink(cols, &mut widths, over);
308    } else if over < 0 {
309        stretch(cols, &mut widths, -over);
310    }
311    widths
312}
313
314/// Take `over` cells off the shrinkable columns, widest first, one cell at a
315/// time, the rightmost of equally wide columns first, never below a column's
316/// [`shrink_floor`]; stop early when every column sits at its floor.
317///
318/// Computed by level instead of cell by cell: every column wider than the
319/// lowest level `level` whose cut fits in `over` drops to that level (or its
320/// floor), and the cells left over come off the rightmost columns standing at
321/// `level`. That is the state the one-cell-per-pass loop reaches, in
322/// O(n log width) instead of O(n · over).
323fn shrink(cols: &[ColumnSpec], widths: &mut [i32], over: i32) {
324    let floors: Vec<i32> = cols.iter().map(shrink_floor).collect();
325    let shrinkable = |i: usize| !cols[i].hidden;
326    // The cells taken by cutting every shrinkable column down to `level`
327    // (but not below its floor).
328    let cut = |widths: &[i32], level: i32| -> i64 {
329        (0..widths.len())
330            .filter(|&i| shrinkable(i))
331            .map(|i| i64::from((widths[i] - floors[i].max(level)).max(0)))
332            .sum()
333    };
334    let over = i64::from(over);
335    // Floors are at least 1, so cutting to level 1 already means every
336    // column at its floor. A budget at or below the floors' sum (the
337    // overflow case) needs no search.
338    if over >= cut(widths, 1) {
339        for i in (0..widths.len()).filter(|&i| shrinkable(i)) {
340            widths[i] = widths[i].min(floors[i]);
341        }
342        return;
343    }
344    // The lowest level whose cut fits in `over`: cut is non-increasing in
345    // the level, cut(1) > over, and cut(widest) = 0 ≤ over.
346    let (mut lo, mut hi) = (2, widths.iter().copied().max().unwrap_or(1).max(2));
347    while lo < hi {
348        let mid = lo + (hi - lo) / 2;
349        if cut(widths, mid) <= over {
350            hi = mid;
351        } else {
352            lo = mid + 1;
353        }
354    }
355    let level = lo;
356    let mut rest = over - cut(widths, level);
357    for i in (0..widths.len()).filter(|&i| shrinkable(i)) {
358        widths[i] = widths[i].min(floors[i].max(level));
359    }
360    // `rest` is below the number of columns at `level` that may still shrink
361    // (cut(level - 1) > over), so each loses at most one cell.
362    for i in (0..widths.len()).rev() {
363        if rest == 0 {
364            break;
365        }
366        if shrinkable(i) && widths[i] == level && floors[i] < level {
367            widths[i] -= 1;
368            rest -= 1;
369        }
370    }
371}
372
373/// The width a column starts the layout from: 0 when hidden; a flex column
374/// at least its `min_width` (and at least 1), so `ColumnSpec::new("X",
375/// 0).flex(1)` is the "fill the rest" column.
376fn preferred_width(c: &ColumnSpec) -> i32 {
377    let w = match () {
378        _ if c.hidden => 0,
379        _ if c.flex > 0 => c.width.max(c.min_width).max(1),
380        _ => c.width.max(0),
381    };
382    w.min(MAX_COLUMN_WIDTH)
383}
384
385/// The narrowest the layout shrinks a column to: its `min_width` (at least 1),
386/// or its `width` when it is [`fixed`](ColumnSpec::fixed).
387fn shrink_floor(c: &ColumnSpec) -> i32 {
388    let floor = c.min_width.max(1);
389    if c.fixed {
390        floor.max(c.width.min(MAX_COLUMN_WIDTH))
391    } else {
392        floor
393    }
394}
395
396/// The sum of `widths`, saturating instead of overflowing on absurd widths.
397fn sum_widths(widths: &[i32]) -> i32 {
398    widths
399        .iter()
400        .filter(|&&w| w > 0)
401        .fold(0i32, |acc, &w| acc.saturating_add(w))
402}
403
404/// Give `spare` cells to the visible, non-zero-width flex columns: each gets
405/// `spare * weight / total_weight` (rounded down), and the cells the rounding
406/// leaves over go one each to the leftmost flex columns. Without a flex column
407/// nothing changes.
408pub fn stretch(cols: &[ColumnSpec], widths: &mut [i32], spare: i32) {
409    let flex: Vec<usize> = (0..cols.len())
410        .filter(|&i| !cols[i].hidden && cols[i].flex > 0 && widths[i] > 0)
411        .collect();
412    let total: i64 = flex.iter().map(|&i| i64::from(cols[i].flex)).sum();
413    if total == 0 || spare <= 0 {
414        return;
415    }
416    let mut left = spare;
417    for &i in &flex {
418        let share = (i64::from(spare) * i64::from(cols[i].flex) / total) as i32;
419        widths[i] += share;
420        left -= share;
421    }
422    // The rounding remainder is below the number of flex columns.
423    for &i in flex.iter().take(left as usize) {
424        widths[i] += 1;
425    }
426}
427
428/// The width of a line of `widths` joined with one-cell separators (zero-width
429/// columns take no cell and no separator).
430pub fn line_width(widths: &[i32]) -> i32 {
431    let shown = widths.iter().filter(|&&w| w > 0).count() as i32;
432    sum_widths(widths).saturating_add((shown - 1).max(0))
433}
434
435/// The horizontal geometry of a table row for one view width: the leading
436/// `frozen` layout columns (the check column) stay put, the rest scroll.
437#[derive(Clone, Debug, PartialEq, Eq)]
438pub struct RowLayout {
439    /// The width of every layout column, frozen ones first.
440    pub widths: Vec<i32>,
441    /// How many leading layout columns are frozen.
442    pub frozen: usize,
443    /// Cells the frozen part takes, its trailing separator included.
444    pub frozen_width: i32,
445    /// The full width of the scrolling part.
446    pub content: i32,
447    /// The cells the scrolling part has on screen.
448    pub view: i32,
449}
450
451impl RowLayout {
452    /// Lay `cols` out over `avail` cells with the first `frozen` columns fixed.
453    pub fn new(cols: &[ColumnSpec], frozen: usize, avail: i32) -> Self {
454        let widths = layout_widths(cols, avail);
455        let frozen = frozen.min(widths.len());
456        let content = line_width(&widths[frozen..]);
457        let mut frozen_width = line_width(&widths[..frozen]);
458        if frozen_width > 0 && content > 0 {
459            frozen_width = frozen_width.saturating_add(1);
460        }
461        RowLayout {
462            view: (avail.max(0) - frozen_width).max(0),
463            widths,
464            frozen,
465            frozen_width,
466            content,
467        }
468    }
469
470    /// The largest horizontal offset: how far the scrolling part overflows.
471    /// 0 when the scrolling part has no cell on screen (the frozen check
472    /// column fills the view): no offset would bring a cell into view.
473    pub fn max_offset(&self) -> i32 {
474        if self.view <= 0 {
475            return 0;
476        }
477        (self.content - self.view).max(0)
478    }
479
480    /// `offset` clamped into `0..=max_offset()`.
481    pub fn clamp(&self, offset: i32) -> i32 {
482        offset.clamp(0, self.max_offset())
483    }
484
485    /// The on-screen text of a row: the `frozen` cell text (the check cell),
486    /// then the scrolling `rest` (a full-width line over
487    /// `widths[frozen..]`) cut to the view from `offset`. `sep` is the
488    /// character the separator cells hold (see [`Separators`]).
489    pub fn compose(&self, frozen: &str, rest: &str, offset: i32, sep: char) -> String {
490        let shown = slice_cols(rest, self.clamp(offset), self.view);
491        match self.frozen {
492            0 => shown,
493            _ => with_check_cell(self.widths[0], frozen, shown, sep),
494        }
495    }
496
497    /// The layout column under text-relative column `x` at `offset`, or
498    /// `None` (a separator, or no column there).
499    pub fn column_at(&self, x: i32, offset: i32) -> Option<usize> {
500        if x < 0 {
501            return None;
502        }
503        if x < self.frozen_width {
504            return column_at(&self.widths[..self.frozen], x);
505        }
506        let sx = x - self.frozen_width;
507        if sx >= self.view {
508            return None;
509        }
510        column_at(
511            &self.widths[self.frozen..],
512            sx.saturating_add(self.clamp(offset)),
513        )
514        .map(|c| c + self.frozen)
515    }
516
517    /// The visible scrolling columns as `(layout index, start, end)` in
518    /// content cells (`end` exclusive; the one-cell separator sits at `end`).
519    pub fn spans(&self) -> Vec<(usize, i32, i32)> {
520        let mut out = Vec::new();
521        let mut start = 0i32;
522        for (i, &w) in self.widths.iter().enumerate().skip(self.frozen) {
523            if w <= 0 {
524                continue;
525            }
526            let end = start.saturating_add(w);
527            out.push((i, start, end));
528            start = end.saturating_add(1);
529        }
530        out
531    }
532
533    /// The content cell under text-relative column `x` at `offset`, or `None`
534    /// outside the scrolling part's view.
535    pub fn content_x(&self, x: i32, offset: i32) -> Option<i32> {
536        let sx = x - self.frozen_width;
537        (0..self.view)
538            .contains(&sx)
539            .then(|| sx.saturating_add(self.clamp(offset)))
540    }
541
542    /// The text-relative column of content cell `cx` at `offset` (it may lie
543    /// outside the view).
544    pub fn text_x(&self, cx: i32, offset: i32) -> i32 {
545        self.frozen_width
546            .saturating_add(cx)
547            .saturating_sub(self.clamp(offset))
548    }
549
550    /// The scrolling layout column whose right-hand separator cell is under
551    /// text-relative column `x` at `offset` — the resize handle. The cell
552    /// right after the last column counts too, so the last column can grow;
553    /// when the last column ends on the view's last cell (it fills or
554    /// overflows the view), that cell is its handle instead.
555    pub fn separator_at(&self, x: i32, offset: i32) -> Option<usize> {
556        let cx = self.content_x(x, offset)?;
557        let spans = self.spans();
558        if let Some(&(i, _, _)) = spans.iter().find(|&&(_, _, end)| end == cx) {
559            return Some(i);
560        }
561        let &(last, _, end) = spans.last()?;
562        let on_last_cell = x - self.frozen_width == self.view - 1;
563        (on_last_cell && end == cx + 1).then_some(last)
564    }
565}
566
567/// The part of `s` from display column `skip` that fits in `width` display
568/// columns. A wide glyph cut by either edge turns into spaces for its visible
569/// half, so the result never starts mid-glyph.
570pub fn slice_cols(s: &str, skip: i32, width: i32) -> String {
571    let (skip, end) = (
572        skip.max(0) as usize,
573        skip.max(0).saturating_add(width.max(0)) as usize,
574    );
575    let mut out = String::new();
576    let mut col = 0;
577    for g in s.graphemes(true) {
578        if col >= end {
579            break;
580        }
581        let gw = text::width(g);
582        let next = col + gw;
583        if col >= skip && next <= end {
584            out.push_str(g);
585        } else if next > skip {
586            // Cut by an edge: pad the visible part.
587            out.push_str(&" ".repeat(next.min(end) - col.max(skip)));
588        }
589        col = next;
590    }
591    out
592}
593
594/// Fit `cell` into exactly `width` display columns: pad with spaces per
595/// `align`, or cut the tail and mark the cut with `…` (`width 1 → "…"`).
596/// Measured in display columns, so wide characters are never split.
597pub fn pad_cell(cell: &str, width: i32, align: Align) -> String {
598    let width = width.max(0) as usize;
599    if width == 0 {
600        return String::new();
601    }
602    let len = text::width(cell);
603    if len <= width {
604        let pad = " ".repeat(width - len);
605        return match align {
606            Align::Left => format!("{cell}{pad}"),
607            Align::Right => format!("{pad}{cell}"),
608        };
609    }
610    // Truncation cuts the tail regardless of alignment (the ellipsis marks the
611    // cut); a wide glyph that would straddle the cut is dropped and the gap
612    // padded, so the result is always exactly `width` columns.
613    let mut head = String::new();
614    let mut used = 0;
615    for g in cell.graphemes(true) {
616        let gw = text::width(g);
617        if used + gw > width - 1 {
618            break;
619        }
620        head.push_str(g);
621        used += gw;
622    }
623    format!("{head}…{}", " ".repeat(width - 1 - used))
624}
625
626/// Join the cells of the visible, non-zero-width columns with `sep`.
627fn join_cells<'a>(
628    widths: &[i32],
629    cells: impl Iterator<Item = (usize, String)> + 'a,
630    sep: char,
631) -> String {
632    let mut line = String::new();
633    for (i, cell) in cells {
634        if widths.get(i).copied().unwrap_or(0) <= 0 {
635            continue;
636        }
637        if !line.is_empty() {
638            line.push(sep);
639        }
640        line.push_str(&cell);
641    }
642    line
643}
644
645/// The rendered text of model row `row`: each visible column padded or
646/// truncated to its width, separated by `sep`.
647pub fn format_line(
648    model: &dyn TableModel,
649    row: usize,
650    widths: &[i32],
651    cols: &[ColumnSpec],
652    sep: char,
653) -> String {
654    join_cells(
655        widths,
656        cols.iter().enumerate().map(|(i, c)| {
657            let w = widths.get(i).copied().unwrap_or(0);
658            (i, pad_cell(&model.cell(row, i), w, c.align))
659        }),
660        sep,
661    )
662}
663
664/// The header text: the labels laid out like [`format_line`], the sorted
665/// column's label carrying `▲`/`▼`. A label too long for its column is cut so
666/// the marker stays visible.
667pub fn header_line(
668    cols: &[ColumnSpec],
669    widths: &[i32],
670    sort: Option<(usize, SortDir)>,
671    sep: char,
672) -> String {
673    join_cells(
674        widths,
675        cols.iter().enumerate().map(|(i, c)| {
676            let w = widths.get(i).copied().unwrap_or(0);
677            let cell = match sort {
678                Some((s, dir)) if s == i => {
679                    let m = dir.marker();
680                    let full = format!("{} {m}", c.label);
681                    if text::width(&full) as i32 <= w {
682                        pad_cell(&full, w, c.align)
683                    } else if w >= 2 {
684                        format!("{} {m}", pad_cell(&c.label, w - 2, Align::Left))
685                    } else {
686                        m.to_string()
687                    }
688                }
689                _ => pad_cell(&c.label, w, c.align),
690            };
691            (i, cell)
692        }),
693        sep,
694    )
695}
696
697/// The column whose cell spans text-relative column `x`, or `None` (a
698/// separator, past the last column, or before the first).
699pub fn column_at(widths: &[i32], x: i32) -> Option<usize> {
700    let mut start = 0;
701    for (i, &w) in widths.iter().enumerate() {
702        if w <= 0 {
703            continue;
704        }
705        if x >= start && x < start.saturating_add(w) {
706            return Some(i);
707        }
708        start = start.saturating_add(w).saturating_add(1);
709    }
710    None
711}
712
713/// The display order of `model` sorted by column `col`: model row indices,
714/// stable for ties (equal keys keep model order in both directions). Numbers
715/// come before text in both directions.
716pub fn sort_order(model: &dyn TableModel, col: usize, dir: SortDir) -> Vec<usize> {
717    let keys: Vec<_> = (0..model.row_count())
718        .map(|r| model.sort_key(r, col))
719        .collect();
720    let mut order: Vec<usize> = (0..keys.len()).collect();
721    order.sort_by(|&a, &b| {
722        let ord = keys[a].compare(&keys[b]);
723        // Descending reverses within a kind only: numbers stay before text.
724        match dir {
725            SortDir::Desc if keys[a].same_kind(&keys[b]) => ord.reverse(),
726            _ => ord,
727        }
728    });
729    order
730}
731
732#[cfg(test)]
733mod tests {
734    use super::*;
735    use crate::widgets::table::model::{RowKey, SortKey, VecModel};
736    use std::borrow::Cow;
737
738    /// The default theme's `frame_v` — the glyph the draws pass to the
739    /// [`Separators`] helpers (these tests are view-free, so the literal
740    /// stands in for `ctx.glyphs().frame_v`).
741    const RULE: char = '│';
742
743    fn col(label: &str, width: i32) -> ColumnSpec {
744        ColumnSpec::new(label, width)
745    }
746
747    fn model(rows: &[&[&str]]) -> VecModel {
748        VecModel::new(
749            rows.iter()
750                .map(|r| r.iter().map(|s| s.to_string()).collect())
751                .collect(),
752        )
753    }
754
755    #[test]
756    fn layout_widths_shrink_widest_until_it_fits() {
757        // avail 30 − 1 separator = 29; wants 60 → shave the widest per pass.
758        let w = layout_widths(&[col("A", 40), col("B", 20)], 30);
759        assert_eq!(w, vec![15, 14]);
760        assert_eq!(w.iter().sum::<i32>() + 1, 30, "total + separator == avail");
761        // Total already fits → untouched.
762        assert_eq!(layout_widths(&[col("A", 5), col("B", 5)], 30), vec![5, 5]);
763    }
764
765    #[test]
766    fn layout_widths_respects_min_width() {
767        // avail 12 − 1 = 11; A may not go below 8, so B absorbs the rest.
768        let w = layout_widths(&[col("A", 10).min_width(8), col("B", 10)], 12);
769        assert_eq!(w, vec![8, 3]);
770        // Nothing left to shave: stays over budget (the view clips).
771        let w = layout_widths(&[col("A", 10).min_width(10), col("B", 3).min_width(3)], 8);
772        assert_eq!(w, vec![10, 3]);
773    }
774
775    #[test]
776    fn layout_widths_nonpositive_avail_yields_zeros() {
777        assert_eq!(layout_widths(&[col("A", 40)], 0), vec![0]);
778        assert_eq!(layout_widths(&[col("A", 4), col("B", 4)], -3), vec![0, 0]);
779    }
780
781    #[test]
782    fn layout_widths_without_room_for_the_separators_keeps_the_floors() {
783        // avail 1, two visible columns: the separator alone eats the budget.
784        // The columns stay at their floors and overflow (the table scrolls).
785        assert_eq!(layout_widths(&[col("A", 4), col("B", 4)], 1), vec![1, 1]);
786        // Multi mode, four columns, view 5 wide → avail 4, five layout
787        // columns, budget 4 − 4 = 0: the check column keeps its 3.
788        let cols = [
789            check_column(),
790            col("ID", 4),
791            col("NAME", 10),
792            col("STATE", 8),
793            col("CPU", 5),
794        ];
795        assert_eq!(layout_widths(&cols, 4), vec![3, 1, 1, 1, 1]);
796        assert_eq!(layout_widths(&cols, 1), vec![3, 1, 1, 1, 1]);
797        // min_width and fixed floors hold too; hidden columns stay 0.
798        let cols = [
799            col("A", 6).min_width(2),
800            col("H", 5).hidden(true),
801            col("F", 4).fixed(true),
802        ];
803        assert_eq!(layout_widths(&cols, 1), vec![2, 0, 4]);
804        let l = RowLayout::new(&cols, 0, 1);
805        assert_eq!((l.content, l.view, l.max_offset()), (7, 1, 6));
806    }
807
808    #[test]
809    fn layout_widths_with_no_visible_column_yields_zeros() {
810        let cols = [col("A", 4).hidden(true), col("B", 0)];
811        assert_eq!(layout_widths(&cols, 1), vec![0, 0]);
812        assert_eq!(layout_widths(&cols, 10), vec![0, 0]);
813    }
814
815    #[test]
816    fn hidden_columns_take_no_width_and_no_separator() {
817        let cols = [col("A", 10), col("B", 12).hidden(true), col("C", 8)];
818        // 10 + 8 + one separator = 19 fits exactly.
819        assert_eq!(layout_widths(&cols, 19), vec![10, 0, 8]);
820        let m = model(&[&["a", "b", "c"]]);
821        let line = format_line(&m, 0, &[10, 0, 8], &cols, ' ');
822        assert_eq!(line, "a          c       ");
823        assert_eq!(text::width(&line), 19);
824        assert!(layout_widths(&[col("A", 3).hidden(true)], 10) == vec![0]);
825    }
826
827    #[test]
828    fn pad_cell_uses_ellipsis_truncation() {
829        assert_eq!(pad_cell("abc", 0, Align::Left), "");
830        assert_eq!(pad_cell("abc", 1, Align::Left), "…");
831        assert_eq!(pad_cell("abc", 2, Align::Left), "a…");
832        assert_eq!(pad_cell("abc", 3, Align::Left), "abc", "exact fit");
833        assert_eq!(pad_cell("abc", 5, Align::Left), "abc  ");
834        assert_eq!(pad_cell("abc", 5, Align::Right), "  abc");
835        assert_eq!(
836            pad_cell("abcdef", 4, Align::Right),
837            "abc…",
838            "tail cut keeps ellipsis at the cut"
839        );
840        assert_eq!(pad_cell("ééé", 2, Align::Left), "é…");
841    }
842
843    #[test]
844    fn pad_cell_measures_display_columns() {
845        // Each CJK glyph is two columns wide; never split one.
846        assert_eq!(pad_cell("日本語", 6, Align::Left), "日本語");
847        assert_eq!(pad_cell("日本語テキスト", 5, Align::Left), "日本…");
848        assert_eq!(pad_cell("日本語テキスト", 4, Align::Left), "日… ");
849        assert_eq!(text::width(&pad_cell("日本語テキスト", 4, Align::Left)), 4);
850    }
851
852    #[test]
853    fn format_line_pads_and_truncates_to_the_cell() {
854        let cols = [col("C1", 5), col("C2", 8), col("C3", 6)];
855        let m = model(&[&["c1", "very-long-name-here", "running"]]);
856        assert_eq!(
857            format_line(&m, 0, &[4, 7, 5], &cols, ' '),
858            "c1   very-l… runn…"
859        );
860        let cols = [col("N", 3).right()];
861        assert_eq!(format_line(&model(&[&["7"]]), 0, &[3], &cols, ' '), "  7");
862    }
863
864    #[test]
865    fn header_line_marks_sort_direction() {
866        let cols = [col("ID", 10), col("NAME", 12), col("STATE", 8)];
867        let widths = [10, 12, 8];
868        assert!(header_line(&cols, &widths, Some((1, SortDir::Asc)), ' ').contains("NAME ▲"));
869        assert!(header_line(&cols, &widths, Some((1, SortDir::Desc)), ' ').contains("NAME ▼"));
870        assert!(!header_line(&cols, &widths, None, ' ').contains('▲'));
871    }
872
873    #[test]
874    fn header_line_keeps_the_marker_when_the_label_is_cut() {
875        let cols = [col("STATUS", 5)];
876        assert_eq!(
877            header_line(&cols, &[5], Some((0, SortDir::Asc)), ' '),
878            "ST… ▲"
879        );
880        assert_eq!(header_line(&cols, &[1], Some((0, SortDir::Desc)), ' '), "▼");
881        assert_eq!(header_line(&cols, &[5], None, ' '), "STAT…");
882    }
883
884    #[test]
885    fn column_at_maps_x_to_columns_and_skips_separators() {
886        let widths = [3, 0, 4];
887        assert_eq!(column_at(&widths, 0), Some(0));
888        assert_eq!(column_at(&widths, 2), Some(0));
889        assert_eq!(column_at(&widths, 3), None, "separator");
890        assert_eq!(column_at(&widths, 4), Some(2), "hidden column skipped");
891        assert_eq!(column_at(&widths, 7), Some(2));
892        assert_eq!(column_at(&widths, 8), None, "past the end");
893        assert_eq!(column_at(&widths, -1), None);
894    }
895
896    #[test]
897    fn sort_order_orders_strings_and_is_stable_for_ties() {
898        let m = model(&[&["1", "b"], &["2", "a"], &["3", "b"]]);
899        assert_eq!(sort_order(&m, 1, SortDir::Asc), [1, 0, 2]);
900        assert_eq!(
901            sort_order(&m, 1, SortDir::Desc),
902            [0, 2, 1],
903            "ties keep model order in both directions"
904        );
905    }
906
907    #[test]
908    fn sort_order_compares_numbers_numerically() {
909        let m = model(&[&["9.9"], &["10.2"], &["1.5"]]);
910        assert_eq!(
911            sort_order(&m, 0, SortDir::Asc),
912            [2, 0, 1],
913            "numeric: 1.5 < 9.9 < 10.2 — string order would say 1.5 < 10.2 < 9.9"
914        );
915        assert_eq!(sort_order(&m, 0, SortDir::Desc), [1, 0, 2]);
916    }
917
918    #[test]
919    fn numbers_sort_before_text_in_both_directions() {
920        let m = model(&[&["n/a"], &["10"], &["9"], &["abc"]]);
921        assert_eq!(sort_order(&m, 0, SortDir::Asc), [2, 1, 3, 0]);
922        assert_eq!(
923            sort_order(&m, 0, SortDir::Desc),
924            [1, 2, 0, 3],
925            "descending reverses within each kind, numbers still first"
926        );
927    }
928
929    #[test]
930    fn check_column_is_fixed_on_a_narrow_table() {
931        // avail 12: check 3 + separators 2 leaves 7 for A and B (wanted 20).
932        let cols = [check_column(), col("A", 10), col("B", 10)];
933        let w = layout_widths(&cols, 12);
934        assert_eq!(w, vec![3, 4, 3], "the check column never shrinks");
935        let m = model(&[&["alpha", "beta"]]);
936        let line = with_check_cell(
937            w[0],
938            "[X]",
939            format_line(&m, 0, &w[1..], &cols[1..], ' '),
940            ' ',
941        );
942        assert_eq!(line, "[X] alp… be…");
943        assert_eq!(text::width(&line), 12, "fills avail exactly");
944        assert_eq!(with_check_cell(0, "[X]", "rest".into(), ' '), "rest");
945        assert_eq!(with_check_cell(3, "[ ]", String::new(), ' '), "[ ]");
946    }
947
948    #[test]
949    fn flex_columns_take_the_spare_width_by_weight() {
950        // avail 30 − 2 separators = 28; wanted 15 → 13 spare, weights 2:1.
951        let cols = [col("A", 5).flex(2), col("B", 5), col("C", 5).flex(1)];
952        let w = layout_widths(&cols, 30);
953        // 13·2/3 = 8, 13·1/3 = 4, remainder 1 → the leftmost flex column.
954        assert_eq!(w, vec![5 + 8 + 1, 5, 5 + 4]);
955        assert_eq!(line_width(&w), 30, "fills avail exactly");
956    }
957
958    #[test]
959    fn flex_remainder_goes_one_cell_each_to_the_leftmost() {
960        // avail 10 − 2 = 8; wanted 3 → 5 spare over three equal weights.
961        let cols = [
962            col("A", 1).flex(1),
963            col("B", 1).flex(1),
964            col("C", 1).flex(1),
965        ];
966        assert_eq!(layout_widths(&cols, 10), vec![3, 3, 2]);
967    }
968
969    #[test]
970    fn without_flex_the_spare_stays_empty_and_hidden_flex_gets_none() {
971        assert_eq!(layout_widths(&[col("A", 5), col("B", 5)], 30), vec![5, 5]);
972        let cols = [col("A", 5).flex(1).hidden(true), col("B", 5)];
973        assert_eq!(layout_widths(&cols, 30), vec![0, 5]);
974        let cols = [col("A", 5).flex(1), col("B", 5)];
975        assert_eq!(
976            layout_widths(&cols, 8),
977            vec![4, 3],
978            "no spare: flex columns shrink like the others"
979        );
980    }
981
982    #[test]
983    fn a_zero_width_flex_column_fills_the_rest() {
984        // avail 20 − 1 separator = 19; A keeps 5, X (width 0) takes 14.
985        let cols = [col("A", 5), col("X", 0).flex(1)];
986        assert_eq!(layout_widths(&cols, 20), vec![5, 14]);
987        // No spare: it still shows one cell and its separator counts.
988        assert_eq!(layout_widths(&cols, 7), vec![5, 1]);
989    }
990
991    #[test]
992    fn huge_widths_are_capped_and_sums_saturate() {
993        let big = i32::MAX / 2;
994        let cols = [col("A", big).min_width(big), col("B", big).min_width(big)];
995        let w = layout_widths(&cols, 10);
996        // Every cell is padded to its width on draw: the layout caps it.
997        let max = MAX_COLUMN_WIDTH;
998        assert_eq!(w, vec![max, max], "nothing may shrink below the cap");
999        let flex = [col("F", big).min_width(big).flex(1)];
1000        assert_eq!(layout_widths(&flex, 10), vec![max]);
1001        let l = RowLayout::new(&cols, 0, 10);
1002        assert_eq!((l.content, l.view), (2 * max + 1, 10));
1003        assert_eq!(l.column_at(3, l.max_offset()), Some(1));
1004        // The width helpers themselves still saturate.
1005        assert_eq!(line_width(&[big, big]), i32::MAX);
1006        assert_eq!(column_at(&[big, big], i32::MAX - 1), Some(1));
1007        assert_eq!(slice_cols("abc", i32::MAX - 1, 10), "");
1008    }
1009
1010    #[test]
1011    fn row_layout_overflows_only_past_min_width() {
1012        let cols = [col("A", 10).min_width(8), col("B", 10).min_width(8)];
1013        // Shrinkable to fit: no overflow.
1014        let l = RowLayout::new(&cols, 0, 17);
1015        assert_eq!((l.content, l.view, l.max_offset()), (17, 17, 0));
1016        // 8 + 1 + 8 = 17 cells of content in 12: overflow by 5.
1017        let l = RowLayout::new(&cols, 0, 12);
1018        assert_eq!((l.content, l.view, l.max_offset()), (17, 12, 5));
1019        assert_eq!(l.clamp(-3), 0);
1020        assert_eq!(l.clamp(3), 3);
1021        assert_eq!(l.clamp(99), 5, "the offset clamps to the overflow");
1022    }
1023
1024    #[test]
1025    fn row_layout_keeps_the_frozen_column_out_of_the_scroll() {
1026        let cols = [
1027            check_column(),
1028            col("A", 6).min_width(6),
1029            col("B", 6).min_width(6),
1030        ];
1031        // 3 + 1 frozen; 13 content cells in 16 − 4 = 12.
1032        let l = RowLayout::new(&cols, 1, 16);
1033        assert_eq!((l.frozen_width, l.content, l.view), (4, 13, 12));
1034        assert_eq!(l.max_offset(), 1);
1035        let rest = "aaaaaa bbbbbb";
1036        assert_eq!(l.compose("[X]", rest, 0, ' '), "[X] aaaaaa bbbbb");
1037        assert_eq!(l.compose("[X]", rest, 1, ' '), "[X] aaaaa bbbbbb");
1038        assert_eq!(
1039            l.compose("[X]", rest, 9, ' '),
1040            "[X] aaaaa bbbbbb",
1041            "clamped"
1042        );
1043        // With a visible rule the check separator is the rule too.
1044        assert_eq!(l.compose("[X]", rest, 0, '│'), "[X]│aaaaaa bbbbb");
1045        // Hit test: the frozen cell, then the scrolled columns.
1046        assert_eq!(l.column_at(1, 1), Some(0));
1047        assert_eq!(l.column_at(3, 1), None, "frozen separator");
1048        assert_eq!(l.column_at(4, 0), Some(1));
1049        assert_eq!(l.column_at(9, 0), Some(1));
1050        assert_eq!(l.column_at(9, 1), None, "scrolled: now the separator");
1051        assert_eq!(l.column_at(10, 1), Some(2));
1052        assert_eq!(l.column_at(16, 1), None, "past the view");
1053    }
1054
1055    #[test]
1056    fn slice_cols_cuts_by_display_columns() {
1057        assert_eq!(slice_cols("abcdef", 2, 3), "cde");
1058        assert_eq!(slice_cols("abc", 1, 9), "bc");
1059        assert_eq!(slice_cols("abc", 5, 2), "");
1060        // A wide glyph cut by the left or the right edge leaves a space.
1061        assert_eq!(slice_cols("日本語", 1, 4), " 本 ");
1062        assert_eq!(slice_cols("日本語", 2, 4), "本語");
1063    }
1064
1065    #[test]
1066    fn zero_width_visible_columns_get_no_separator() {
1067        // 5 + 5 + one separator = 11: the zero-width B must not eat a cell.
1068        let cols = [col("A", 5), col("B", 0), col("C", 5)];
1069        assert_eq!(layout_widths(&cols, 11), vec![5, 0, 5]);
1070        let m = model(&[&["a", "b", "c"]]);
1071        assert_eq!(text::width(&format_line(&m, 0, &[5, 0, 5], &cols, ' ')), 11);
1072    }
1073
1074    #[test]
1075    fn separators_choose_the_join_glyph_without_shifting_the_layout() {
1076        let cols = [col("ID", 4), col("NAME", 8), col("STATE", 6)];
1077        let widths = [4, 8, 6];
1078        let m = model(&[&["a1", "web", "running"]]);
1079
1080        // The default draws one blank cell between columns.
1081        assert_eq!(
1082            header_line(&cols, &widths, None, Separators::Off.header_char(RULE)),
1083            "ID   NAME     STATE "
1084        );
1085        assert_eq!(
1086            format_line(&m, 0, &widths, &cols, Separators::Off.row_char(RULE)),
1087            "a1   web      runni…"
1088        );
1089
1090        // Header: a `│` rule in the label row only; the rows keep spaces.
1091        assert_eq!(
1092            header_line(&cols, &widths, None, Separators::Header.header_char(RULE)),
1093            "ID  │NAME    │STATE "
1094        );
1095        assert_eq!(
1096            format_line(&m, 0, &widths, &cols, Separators::Header.row_char(RULE)),
1097            "a1   web      runni…",
1098            "rows keep the blank separator"
1099        );
1100
1101        // All: the rule in the header and between every row's cells.
1102        assert_eq!(
1103            header_line(&cols, &widths, None, Separators::All.header_char(RULE)),
1104            "ID  │NAME    │STATE "
1105        );
1106        assert_eq!(
1107            format_line(&m, 0, &widths, &cols, Separators::All.row_char(RULE)),
1108            "a1  │web     │runni…"
1109        );
1110
1111        // A rule is one cell wide, so it never changes the line's width.
1112        for sep in [Separators::Off, Separators::Header, Separators::All] {
1113            let head = header_line(&cols, &widths, None, sep.header_char(RULE));
1114            let row = format_line(&m, 0, &widths, &cols, sep.row_char(RULE));
1115            assert_eq!(text::width(&head) as i32, line_width(&widths));
1116            assert_eq!(text::width(&row) as i32, line_width(&widths));
1117        }
1118    }
1119
1120    #[test]
1121    fn separator_rules_take_the_glyph_from_the_theme() {
1122        // The rule is not a literal of this module: it is whatever
1123        // `ctx.glyphs().frame_v` holds, so another theme can rule with
1124        // another glyph (the ListViewer divider reads it the same way).
1125        const DOUBLE: char = '║';
1126        assert_eq!(Separators::Header.header_char(DOUBLE), DOUBLE);
1127        assert_eq!(Separators::All.header_char(DOUBLE), DOUBLE);
1128        assert_eq!(Separators::All.row_char(DOUBLE), DOUBLE);
1129        assert_eq!(Separators::Off.header_char(DOUBLE), ' ');
1130        assert_eq!(Separators::Header.row_char(DOUBLE), ' ', "rows stay blank");
1131    }
1132
1133    #[test]
1134    fn the_separator_rule_lands_on_the_resize_handle_cell() {
1135        // The rule is drawn on the very cell `separator_at` reports, so a
1136        // header drag with a rule on still resizes the same column.
1137        let cols = [col("A", 4), col("B", 4)];
1138        let l = RowLayout::new(&cols, 0, 9);
1139        assert_eq!(l.widths, vec![4, 4]);
1140        let head = header_line(&cols, &l.widths, None, Separators::Header.header_char(RULE));
1141        assert_eq!(head.chars().nth(4), Some(RULE));
1142        assert_eq!(l.separator_at(4, 0), Some(0));
1143        let row = format_line(
1144            &model(&[&["a", "b"]]),
1145            0,
1146            &l.widths,
1147            &cols,
1148            Separators::All.row_char(RULE),
1149        );
1150        assert_eq!(row.chars().nth(4), Some(RULE));
1151    }
1152
1153    /// A model whose display text is not its sort key (the tvdocker
1154    /// `sort_keys` case, here via [`TableModel::sort_key`]).
1155    struct Percent(Vec<f64>);
1156
1157    impl TableModel for Percent {
1158        fn row_count(&self) -> usize {
1159            self.0.len()
1160        }
1161        fn cell(&self, row: usize, _col: usize) -> Cow<'_, str> {
1162            Cow::Owned(format!("{}%", self.0[row]))
1163        }
1164        fn row_key(&self, row: usize) -> RowKey {
1165            RowKey(row.to_string())
1166        }
1167        fn sort_key(&self, row: usize, _col: usize) -> SortKey {
1168            SortKey::Num(self.0[row])
1169        }
1170    }
1171
1172    #[test]
1173    fn sort_order_uses_the_model_sort_key() {
1174        let m = Percent(vec![9.9, 10.2, 1.5]);
1175        assert_eq!(sort_order(&m, 0, SortDir::Asc), [2, 0, 1]);
1176    }
1177
1178    #[test]
1179    fn nan_sort_keys_tie_and_stay_stable() {
1180        let m = Percent(vec![f64::NAN, f64::NAN]);
1181        assert_eq!(sort_order(&m, 0, SortDir::Asc), [0, 1]);
1182    }
1183
1184    /// The layout as it was before the level shrink: one cell off the widest
1185    /// shrinkable column (the rightmost of a tie) per pass. Kept verbatim as
1186    /// the reference [`shrink`] must reproduce.
1187    fn layout_widths_reference(cols: &[ColumnSpec], avail: i32) -> Vec<i32> {
1188        let mut widths: Vec<i32> = cols.iter().map(preferred_width).collect();
1189        let visible = widths.iter().filter(|&&w| w > 0).count() as i32;
1190        if visible == 0 || avail <= 0 {
1191            return vec![0; cols.len()];
1192        }
1193        let budget = avail - (visible - 1);
1194        let mut over = sum_widths(&widths).saturating_sub(budget);
1195        while over > 0 {
1196            let widest = widths
1197                .iter()
1198                .enumerate()
1199                .filter(|(i, w)| !cols[*i].hidden && **w > shrink_floor(&cols[*i]))
1200                .max_by_key(|(_, w)| **w)
1201                .map(|(i, _)| i);
1202            let Some(i) = widest else { break };
1203            widths[i] -= 1;
1204            over -= 1;
1205        }
1206        if over < 0 {
1207            stretch(cols, &mut widths, -over);
1208        }
1209        widths
1210    }
1211
1212    #[test]
1213    fn level_shrink_matches_the_one_cell_loop() {
1214        let templates = [
1215            check_column(),
1216            col("a", 5),
1217            col("b", 9).min_width(3),
1218            col("c", 4).fixed(true),
1219            col("d", 0).flex(1),
1220            col("e", 6).flex(2).min_width(2),
1221            col("h", 7).hidden(true),
1222            col("z", 0),
1223            col("w", 2).min_width(5),
1224            col("t", 9),
1225        ];
1226        let n = templates.len();
1227        let mut checked = 0u32;
1228        // Every ordered pick of 0..=4 templates (repeats allowed).
1229        for len in 0..=4u32 {
1230            for code in 0..n.pow(len) {
1231                let mut c = code;
1232                let cols: Vec<ColumnSpec> = (0..len)
1233                    .map(|_| {
1234                        let t = templates[c % n].clone();
1235                        c /= n;
1236                        t
1237                    })
1238                    .collect();
1239                for avail in -3..=60 {
1240                    assert_eq!(
1241                        layout_widths(&cols, avail),
1242                        layout_widths_reference(&cols, avail),
1243                        "avail {avail}, columns {:?}",
1244                        cols.iter().map(|c| &c.label).collect::<Vec<_>>()
1245                    );
1246                    checked += 1;
1247                }
1248            }
1249        }
1250        assert_eq!(checked, 11_111 * 64);
1251        // Wide columns: several levels, ties and partial rounds.
1252        let wide = [
1253            col("p", 40),
1254            col("q", 40).min_width(30),
1255            col("r", 25),
1256            col("s", 40),
1257            col("u", 13).fixed(true),
1258            check_column(),
1259        ];
1260        for avail in -3..=200 {
1261            assert_eq!(
1262                layout_widths(&wide, avail),
1263                layout_widths_reference(&wide, avail),
1264                "avail {avail}"
1265            );
1266        }
1267    }
1268}