Skip to main content

blit_widget/layout/
grid.rs

1use blit::{Axis, Context, Fit, LayoutCx, Scalar, Scratch};
2
3blit::builder! {
4    /// fixed column row major grid
5    #[derive(Clone, Copy, Debug, PartialEq)]
6    pub struct Layout<T: Scalar> {
7        new(columns: u32),
8        column_gap: T = T::ZERO,
9        row_gap: T = T::ZERO,
10    }
11}
12
13impl<T: Scalar> Layout<T> {
14    pub fn gap(mut self, gap: T) -> Self {
15        self.column_gap = gap;
16        self.row_gap = gap;
17        self
18    }
19}
20
21blit::builder! {
22    /// spans and contributions to track sizing for a grid child
23    /// final cells can be larger than the supplied width and height
24    #[derive(Clone, Copy, Debug, PartialEq)]
25    pub struct Item<T: Scalar> {
26        new(),
27        #[into]
28        width: Option<T> = None,
29        #[into]
30        height: Option<T> = None,
31        row_span: u32 = 1,
32        column_span: u32 = 1,
33    }
34}
35
36pub fn new<T: Scalar>(columns: u32) -> Layout<T> {
37    Layout::new(columns)
38}
39
40pub fn item<T: Scalar>() -> Item<T> {
41    Item::new()
42}
43
44impl<C: Context<Scalar = T>, T: Scalar> blit::Layout<C> for Layout<T> {
45    type Item = Item<T>;
46
47    fn fit(&self, cx: &mut LayoutCx<'_, C, Self::Item>, axis: Axis) -> Fit<T> {
48        let columns = self.columns as usize;
49        let column_gap = self.column_gap.max(T::ZERO);
50        let row_gap = self.row_gap.max(T::ZERO);
51        if axis == Axis::Horizontal {
52            let mut count = 0usize;
53            let mut required_min = 0.0f32;
54            let mut required_natural = 0.0f32;
55            for child in cx.children() {
56                let item = cx.item(child);
57                let child_w = item
58                    .width
59                    .map_or_else(|| cx.fit(child, Axis::Horizontal), |w| Fit::exact(w.max(T::ZERO)));
60                let span = item.column_span as usize;
61                let span_gaps = column_gap.repeat(span.saturating_sub(1));
62                let scale = columns as f32 / span as f32;
63                required_min = required_min.max((child_w.min - span_gaps).max(T::ZERO).to_f32() * scale);
64                required_natural = required_natural.max((child_w.natural - span_gaps).max(T::ZERO).to_f32() * scale);
65                count += 1;
66            }
67            if count == 0 {
68                return Fit::ZERO;
69            }
70            let snap = |required: f32| {
71                let mut width = T::from_f32(required);
72                // round up to preserve intrinsic widths when snapping to integer cells
73                if width.to_f32() < required {
74                    width = width.endpoint(T::from_f32(1.0));
75                }
76                width + column_gap.repeat(columns.saturating_sub(1))
77            };
78            return Fit::new(snap(required_min), snap(required_natural));
79        }
80
81        let (count, spanning, row_count, _) = self.grid_cells(cx, false);
82        if row_count == 0 {
83            return Fit::ZERO;
84        }
85        let height = if spanning {
86            let (min_track, natural_track) = self.row_track(cx, row_gap);
87            Fit::new(
88                T::from_f32(min_track * row_count as f32),
89                T::from_f32(natural_track * row_count as f32),
90            )
91        } else {
92            let mut children = cx.children();
93            let mut height = Fit::ZERO;
94            let mut index = 0;
95            while index < count {
96                let group = columns.min(count - index);
97                let mut row_height = Fit::ZERO;
98                for child in children.by_ref().take(group) {
99                    row_height = row_height.max(self.child_height(cx, child));
100                }
101                height += row_height;
102                index += group;
103            }
104            height
105        };
106        height + Fit::exact(row_gap.repeat(row_count.saturating_sub(1)))
107    }
108
109    fn distribute(&self, cx: &mut LayoutCx<'_, C, Self::Item>, axis: Axis, extent: T) {
110        let columns = self.columns as usize;
111        let column_gap = self.column_gap.max(T::ZERO);
112        let row_gap = self.row_gap.max(T::ZERO);
113        let (count, spanning, row_count, positions) = self.grid_cells(cx, true);
114        if row_count == 0 {
115            return;
116        }
117        if axis == Axis::Horizontal {
118            let horizontal_gaps = column_gap.repeat(columns.saturating_sub(1));
119            let content_width = (extent - horizontal_gaps).max(T::ZERO).to_f32();
120            let column_edge = |column: usize| T::from_f32(column as f32 * content_width / columns as f32);
121            for (index, child) in cx.children().enumerate() {
122                let column = if spanning { positions[index].1 } else { index % columns };
123                let span = cx.item(child).column_span as usize;
124                let assigned =
125                    column_edge(column + span) - column_edge(column) + column_gap.repeat(span.saturating_sub(1));
126                cx.set_extent(child, assigned);
127                cx.set_offset(child, column_edge(column) + column_gap.repeat(column));
128            }
129            return;
130        }
131
132        if spanning {
133            let row_track = self.row_track(cx, row_gap).1;
134            for (index, child) in cx.children().enumerate() {
135                let row = positions[index].0;
136                let span = cx.item(child).row_span as usize;
137                let assigned = T::from_f32((row + span) as f32 * row_track) - T::from_f32(row as f32 * row_track)
138                    + row_gap.repeat(span.saturating_sub(1));
139                cx.set_extent(child, assigned);
140                cx.set_offset(child, T::from_f32(row as f32 * row_track) + row_gap.repeat(row));
141            }
142        } else {
143            let mut children = cx.children();
144            let mut index = 0;
145            let mut y = T::ZERO;
146            while index < count {
147                let group = columns.min(count - index);
148                let mut row_height = T::ZERO;
149                for child in children.take(group) {
150                    row_height = row_height.max(self.child_height(cx, child).natural);
151                }
152                for child in children.by_ref().take(group) {
153                    cx.set_extent(child, row_height);
154                    cx.set_offset(child, y);
155                }
156                y += row_height + row_gap;
157                index += group;
158            }
159        }
160    }
161}
162
163impl<T: Scalar> Layout<T> {
164    #[inline]
165    fn child_height<C: Context<Scalar = T>>(&self, cx: &LayoutCx<'_, C, Item<T>>, child: blit::NodeId) -> Fit<T> {
166        cx.item(child)
167            .height
168            .map_or_else(|| cx.fit(child, Axis::Vertical), |h| Fit::exact(h.max(T::ZERO)))
169    }
170
171    fn row_track<C: Context<Scalar = T>>(&self, cx: &LayoutCx<'_, C, Item<T>>, row_gap: T) -> (f32, f32) {
172        let mut min_track = 0.0f32;
173        let mut natural_track = 0.0f32;
174        for child in cx.children() {
175            let child_h = self.child_height(cx, child);
176            let span = cx.item(child).row_span as usize;
177            let span_gaps = row_gap.repeat(span.saturating_sub(1));
178            min_track = min_track.max((child_h.min - span_gaps).max(T::ZERO).to_f32() / span as f32);
179            natural_track = natural_track.max((child_h.natural - span_gaps).max(T::ZERO).to_f32() / span as f32);
180        }
181        (min_track, natural_track)
182    }
183
184    fn grid_cells<'a, C: Context<Scalar = T>>(
185        &self,
186        cx: &LayoutCx<'a, C, Item<T>>,
187        need_positions: bool,
188    ) -> (usize, bool, usize, Scratch<'a, (usize, usize)>) {
189        assert!(self.columns != 0, "grid must have at least one column");
190        let columns = self.columns as usize;
191        let mut count = 0usize;
192        let mut spanning = false;
193        for child in cx.children() {
194            let item = cx.item(child);
195            assert!(
196                item.row_span != 0 && item.column_span != 0,
197                "grid spans must be nonzero"
198            );
199            assert!(
200                item.column_span <= self.columns,
201                "grid column span exceeds its column count"
202            );
203            spanning |= item.row_span != 1 || item.column_span != 1;
204            count += 1;
205        }
206        let mut positions = cx.scratch().alloc(if spanning && need_positions { count } else { 0 });
207        let row_count = if spanning {
208            let mut column_rows = cx.scratch().alloc(columns);
209            column_rows.resize(columns, 0usize);
210            let mut cursor = (0usize, 0usize);
211            let mut rows = 0usize;
212            for child in cx.children() {
213                let item = cx.item(child);
214                let span = item.column_span as usize;
215                let (cursor_row, cursor_column) = cursor;
216                let (row, column) = if span <= columns - cursor_column
217                    && column_rows[cursor_column..cursor_column + span]
218                        .iter()
219                        .all(|row| *row <= cursor_row)
220                {
221                    cursor
222                } else {
223                    (0..=columns - span)
224                        .map(|column| {
225                            let row = column_rows[column..column + span]
226                                .iter()
227                                .copied()
228                                .fold(cursor_row + usize::from(column < cursor_column), usize::max);
229                            (row, column)
230                        })
231                        .min()
232                        .unwrap()
233                };
234                column_rows[column..column + span]
235                    .fill(row.checked_add(item.row_span as usize).expect("too many grid rows"));
236                cursor = if column + span == columns {
237                    (row + 1, 0)
238                } else {
239                    (row, column + span)
240                };
241                if need_positions {
242                    positions.push((row, column));
243                }
244                rows = rows.max(row + item.row_span as usize);
245            }
246            rows
247        } else {
248            count.div_ceil(columns)
249        };
250        (count, spanning, row_count, positions)
251    }
252}