Skip to main content

cosmic_applet_avestruz/views/components/
table_grid.rs

1// SPDX-License-Identifier: MIT
2
3//! A table of a note: cells in rows and columns, each column as wide as
4//! what is widest in it, and all of them together no wider than the room
5//! there is.
6//!
7//! A table that fits is as wide as what it holds, and no wider. One that
8//! doesn't is as wide as the room: the columns that would take less than
9//! an even share of it keep their width, and the others share what is
10//! left evenly and wrap what they hold. Every cell of a row is as tall
11//! as the tallest of them, so that rows stay rows.
12//!
13//! Under each row but the last is a line, the one under the first row
14//! the plainest: that row says what the columns are.
15//!
16//! The cells are elements like any other, and are told of everything a
17//! cell could want to know: a link in one can be clicked. The table
18//! itself takes no click, so one on it is one on what is under it.
19
20use cosmic::iced::core::Renderer as _;
21use cosmic::iced::core::layout::{Limits, Node};
22use cosmic::iced::core::mouse;
23use cosmic::iced::core::overlay;
24use cosmic::iced::core::renderer::{self, Quad};
25use cosmic::iced::core::widget::{Operation, Tree, tree};
26use cosmic::iced::core::{Alignment, Clipboard, Color, Element, Event, Layout, Length, Rectangle, Shell, Size, Vector, Widget};
27
28/// The room around what a cell holds: beside it, and above and under it.
29pub const TABLE_CELL_PADDING_X: f32 = 10.0;
30pub const TABLE_CELL_PADDING_Y: f32 = 5.0;
31
32/// How thick the line under a row is.
33pub const TABLE_LINE: f32 = 1.0;
34
35/// How narrow a column may get, whatever else wants the room.
36const COLUMN_MIN_WIDTH: f32 = 24.0;
37
38/// A table of cells: see the module.
39pub struct TableGrid<'a, Message> {
40    /// The cells, row by row.
41    cells: Vec<cosmic::Element<'a, Message>>,
42    /// Where in its column each column's cells stand: as many as there
43    /// are columns.
44    columns: Vec<Alignment>,
45    /// The colour of the line under the first row, and of the others.
46    head_line: Color,
47    line: Color,
48}
49
50impl<'a, Message> TableGrid<'a, Message> {
51    /// A table of `cells`, row by row, with a column for each of
52    /// `columns`. Cells past the last whole row are left out.
53    pub fn new(columns: Vec<Alignment>, mut cells: Vec<cosmic::Element<'a, Message>>, head_line: Color, line: Color) -> Self {
54        let whole = cells.len() - cells.len() % columns.len().max(1);
55        cells.truncate(if columns.is_empty() { 0 } else { whole });
56        Self { cells, columns, head_line, line }
57    }
58}
59
60/// How tall each row came out, the room around its cells included: what
61/// the lines are drawn by.
62#[derive(Default)]
63struct Rows(Vec<f32>);
64
65/// How wide each column is, of columns that would be `natural` wide if
66/// they had the room, in `room`: as wide as that if they fit, and
67/// otherwise the narrow ones as they are and the rest sharing what is
68/// left.
69pub(super) fn column_widths(natural: &[f32], room: f32) -> Vec<f32> {
70    if natural.iter().sum::<f32>() <= room {
71        return natural.to_vec();
72    }
73    // The narrowest first: each takes what it wants if that is no more
74    // than an even share of what is left, and the share if it is.
75    let mut order: Vec<usize> = (0..natural.len()).collect();
76    order.sort_by(|a, b| natural.get(*a).zip(natural.get(*b)).map_or(std::cmp::Ordering::Equal, |(a, b)| a.total_cmp(b)));
77    let mut widths = vec![0.0; natural.len()];
78    let mut left = room;
79    for (taken, column) in order.iter().enumerate() {
80        let share = left / (natural.len() - taken) as f32;
81        let width = natural.get(*column).copied().unwrap_or_default().min(share).max(COLUMN_MIN_WIDTH);
82        if let Some(slot) = widths.get_mut(*column) {
83            *slot = width;
84        }
85        left = (left - width).max(0.0);
86    }
87    widths
88}
89
90impl<Message> Widget<Message, cosmic::Theme, cosmic::Renderer> for TableGrid<'_, Message> {
91    fn size(&self) -> Size<Length> {
92        Size::new(Length::Shrink, Length::Shrink)
93    }
94
95    fn tag(&self) -> tree::Tag {
96        tree::Tag::of::<Rows>()
97    }
98
99    fn state(&self) -> tree::State {
100        tree::State::new(Rows::default())
101    }
102
103    fn children(&self) -> Vec<Tree> {
104        self.cells.iter().map(|cell| Tree::new(cell.as_widget())).collect()
105    }
106
107    fn diff(&mut self, tree: &mut Tree) {
108        tree.diff_children(&mut self.cells);
109    }
110
111    fn layout(&mut self, tree: &mut Tree, renderer: &cosmic::Renderer, limits: &Limits) -> Node {
112        let columns = self.columns.len();
113        if columns == 0 {
114            return Node::new(Size::ZERO);
115        }
116        let around = 2.0 * TABLE_CELL_PADDING_X;
117        let unbounded = Limits::new(Size::ZERO, Size::INFINITE);
118
119        // How wide each column would be with all the room it wants.
120        let mut natural = vec![0.0_f32; columns];
121        for (at, (cell, state)) in self.cells.iter_mut().zip(&mut tree.children).enumerate() {
122            let width = cell.as_widget_mut().layout(state, renderer, &unbounded).size().width;
123            if let Some(widest) = natural.get_mut(at % columns) {
124                *widest = widest.max(width);
125            }
126        }
127        let room = limits.max().width - around * columns as f32;
128        let widths = if room.is_finite() { column_widths(&natural, room.max(0.0)) } else { natural };
129
130        // Each cell in the width its column has, and each row as tall as
131        // its tallest.
132        let mut nodes = Vec::with_capacity(self.cells.len());
133        let mut heights: Vec<f32> = Vec::new();
134        for (at, (cell, state)) in self.cells.iter_mut().zip(&mut tree.children).enumerate() {
135            let width = widths.get(at % columns).copied().unwrap_or_default();
136            let node = cell.as_widget_mut().layout(state, renderer, &Limits::new(Size::ZERO, Size::new(width, f32::INFINITY)));
137            if at % columns == 0 {
138                heights.push(0.0);
139            }
140            if let Some(tallest) = heights.last_mut() {
141                *tallest = tallest.max(node.size().height);
142            }
143            nodes.push(node);
144        }
145
146        // Each where it stands.
147        let (mut x, mut y) = (0.0, 0.0);
148        for (at, node) in nodes.iter_mut().enumerate() {
149            let (row, column) = (at / columns, at % columns);
150            if column == 0 {
151                x = 0.0;
152                if let Some(above) = row.checked_sub(1).and_then(|above| heights.get(above)) {
153                    y += above + 2.0 * TABLE_CELL_PADDING_Y + TABLE_LINE;
154                }
155            }
156            let width = widths.get(column).copied().unwrap_or_default();
157            let height = heights.get(row).copied().unwrap_or_default();
158            let align = self.columns.get(column).copied().unwrap_or(Alignment::Start);
159            node.move_to_mut((x + TABLE_CELL_PADDING_X, y + TABLE_CELL_PADDING_Y));
160            node.align_mut(align, Alignment::Start, Size::new(width, height));
161            x += width + around;
162        }
163        let wide = widths.iter().sum::<f32>() + around * columns as f32;
164        let tall = heights.last().map_or(0.0, |last| y + last + 2.0 * TABLE_CELL_PADDING_Y);
165        tree.state.downcast_mut::<Rows>().0 = heights.iter().map(|height| height + 2.0 * TABLE_CELL_PADDING_Y).collect();
166        Node::with_children(Size::new(wide, tall), nodes)
167    }
168
169    fn update(
170        &mut self,
171        tree: &mut Tree,
172        event: &Event,
173        layout: Layout<'_>,
174        cursor: mouse::Cursor,
175        renderer: &cosmic::Renderer,
176        clipboard: &mut dyn Clipboard,
177        shell: &mut Shell<'_, Message>,
178        viewport: &Rectangle,
179    ) {
180        for ((cell, state), layout) in self.cells.iter_mut().zip(&mut tree.children).zip(layout.children()) {
181            cell.as_widget_mut().update(state, event, layout, cursor, renderer, clipboard, shell, viewport);
182        }
183    }
184
185    fn draw(
186        &self,
187        tree: &Tree,
188        renderer: &mut cosmic::Renderer,
189        theme: &cosmic::Theme,
190        style: &renderer::Style,
191        layout: Layout<'_>,
192        cursor: mouse::Cursor,
193        viewport: &Rectangle,
194    ) {
195        for ((cell, state), layout) in self.cells.iter().zip(&tree.children).zip(layout.children()) {
196            cell.as_widget().draw(state, renderer, theme, style, layout, cursor, viewport);
197        }
198        // A line under each row but the last.
199        let bounds = layout.bounds();
200        let rows = &tree.state.downcast_ref::<Rows>().0;
201        let mut y = bounds.y;
202        for (row, height) in rows.iter().enumerate().take(rows.len().saturating_sub(1)) {
203            y += height;
204            let line = Rectangle { x: bounds.x, y, width: bounds.width, height: TABLE_LINE };
205            renderer.fill_quad(
206                Quad { bounds: line, snap: true, ..Quad::default() },
207                if row == 0 { self.head_line } else { self.line },
208            );
209            y += TABLE_LINE;
210        }
211    }
212
213    fn mouse_interaction(
214        &self,
215        tree: &Tree,
216        layout: Layout<'_>,
217        cursor: mouse::Cursor,
218        viewport: &Rectangle,
219        renderer: &cosmic::Renderer,
220    ) -> mouse::Interaction {
221        self.cells
222            .iter()
223            .zip(&tree.children)
224            .zip(layout.children())
225            .map(|((cell, state), layout)| cell.as_widget().mouse_interaction(state, layout, cursor, viewport, renderer))
226            .max()
227            .unwrap_or_default()
228    }
229
230    fn operate(&mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &cosmic::Renderer, operation: &mut dyn Operation) {
231        for ((cell, state), layout) in self.cells.iter_mut().zip(&mut tree.children).zip(layout.children()) {
232            cell.as_widget_mut().operate(state, layout, renderer, operation);
233        }
234    }
235
236    fn overlay<'b>(
237        &'b mut self,
238        tree: &'b mut Tree,
239        layout: Layout<'b>,
240        renderer: &cosmic::Renderer,
241        viewport: &Rectangle,
242        translation: Vector,
243    ) -> Option<overlay::Element<'b, Message, cosmic::Theme, cosmic::Renderer>> {
244        overlay::from_children(&mut self.cells, tree, layout, renderer, viewport, translation)
245    }
246}
247
248impl<'a, Message: 'a> From<TableGrid<'a, Message>> for Element<'a, Message, cosmic::Theme, cosmic::Renderer> {
249    fn from(table: TableGrid<'a, Message>) -> Self {
250        Self::new(table)
251    }
252}
253
254#[cfg(test)]
255mod tests {
256    use super::{COLUMN_MIN_WIDTH, TABLE_CELL_PADDING_X, TableGrid, column_widths};
257    use cosmic::iced::core::layout::Limits;
258    use cosmic::iced::core::widget::Tree;
259    use cosmic::iced::core::{Alignment, Color, Size};
260    use cosmic::iced::widget::text::Wrapping;
261
262    /// How large a table of `cells`, two to a row, lays out in room
263    /// `room` wide, and where its cells are.
264    fn laid_out(cells: &[&str], room: f32) -> (Size, Vec<cosmic::iced::core::Rectangle>) {
265        let renderer = crate::views::components::testing::renderer();
266        let cells = cells
267            .iter()
268            .map(|said| cosmic::widget::text(said.to_string()).size(13).wrapping(Wrapping::WordOrGlyph).into())
269            .collect::<Vec<cosmic::Element<'_, ()>>>();
270        let mut table: cosmic::Element<'_, ()> =
271            TableGrid::new(vec![Alignment::Start, Alignment::End], cells, Color::WHITE, Color::WHITE).into();
272        let mut tree = Tree::new(table.as_widget());
273        let node = table.as_widget_mut().layout(&mut tree, &renderer, &Limits::new(Size::ZERO, Size::new(room, f32::INFINITY)));
274        (node.size(), node.children().iter().map(|cell| cell.bounds()).collect())
275    }
276
277    #[test]
278    fn a_table_that_fits_is_as_wide_as_what_it_holds() {
279        let (size, cells) = laid_out(&["Key", "Since", "j", "0.1"], 600.0);
280        assert!(size.width < 200.0, "{size:?}");
281        // Rows are rows: the cells of one start as high as each other,
282        let [key, since, j, version] = cells.as_slice() else { panic!("four cells: {cells:?}") };
283        assert_eq!((key.y, j.y), (since.y, version.y));
284        assert!(j.y > key.y + key.height);
285        // and columns are columns: the first starts where the first does,
286        // and the second, set to its far side, ends where the second does.
287        assert_eq!(key.x, TABLE_CELL_PADDING_X);
288        assert_eq!(j.x, key.x);
289        assert!((since.x + since.width - (version.x + version.width)).abs() < 0.01, "{since:?} {version:?}");
290    }
291
292    #[test]
293    fn a_table_that_does_not_fit_is_as_wide_as_the_room_and_wraps_what_it_holds() {
294        let long = "words upon words upon words, ".repeat(12);
295        let (narrow, _) = laid_out(&["What", "N", &long, "1"], 300.0);
296        let (wide, _) = laid_out(&["What", "N", &long, "1"], 600.0);
297        assert!((narrow.width - 300.0).abs() < 0.01 && (wide.width - 600.0).abs() < 0.01, "{narrow:?} {wide:?}");
298        assert!(narrow.height > wide.height, "the narrower, the more lines: {narrow:?} {wide:?}");
299    }
300
301    #[test]
302    fn columns_that_fit_are_as_wide_as_what_they_hold() {
303        assert_eq!(column_widths(&[40.0, 120.0, 60.0], 400.0), [40.0, 120.0, 60.0]);
304    }
305
306    #[test]
307    fn columns_that_do_not_fit_share_the_room_the_narrow_ones_first() {
308        // The narrow one keeps its width, and the two that want more
309        // than a share of what is left get as much each.
310        assert_eq!(column_widths(&[900.0, 40.0, 500.0], 300.0), [130.0, 40.0, 130.0]);
311        // All the room is used, and none of it twice.
312        assert_eq!(column_widths(&[900.0, 40.0, 500.0], 300.0).iter().sum::<f32>(), 300.0);
313        // With no room at all, a column is still something.
314        assert_eq!(column_widths(&[900.0, 500.0], 10.0), [COLUMN_MIN_WIDTH, COLUMN_MIN_WIDTH]);
315    }
316}