summaryrefslogtreecommitdiff
path: root/src/layout/grid.rs
blob: 52e07d0df747dbe2e87d60422c362f46fc9fdb85 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
use super::*;

/// A node that arranges its children in a grid.
#[derive(Debug, Clone, PartialEq, Hash)]
pub struct GridNode {
    /// The `main` and `cross` directions of this grid.
    ///
    /// The rows go along the `main` direction and the columns along the `cross`
    /// direction.
    pub dirs: Gen<Dir>,
    /// Defines sizing for content rows and columns.
    pub tracks: Gen<Vec<TrackSizing>>,
    /// Defines sizing of gutter rows and columns between content.
    pub gutter: Gen<Vec<TrackSizing>>,
    /// The nodes to be arranged in a grid.
    pub children: Vec<AnyNode>,
}

/// Defines how to size a grid cell along an axis.
#[derive(Debug, Copy, Clone, PartialEq, Hash)]
pub enum TrackSizing {
    /// Fit the cell to its contents.
    Auto,
    /// A length stated in absolute values and fractions of the parent's size.
    Linear(Linear),
    /// A length that is the fraction of the remaining free space in the parent.
    Fractional(Fractional),
}

impl Layout for GridNode {
    fn layout(&self, ctx: &mut LayoutContext, regions: &Regions) -> Vec<Frame> {
        // Prepare grid layout by unifying content and gutter tracks.
        let mut layouter = GridLayouter::new(self, regions.clone());

        // Determine all column sizes.
        layouter.measure_columns(ctx);

        // Layout the grid row-by-row.
        layouter.layout(ctx)
    }
}

impl From<GridNode> for AnyNode {
    fn from(grid: GridNode) -> Self {
        Self::new(grid)
    }
}

/// Performs grid layout.
struct GridLayouter<'a> {
    /// The axis of the cross direction.
    cross: SpecAxis,
    /// The axis of the main direction.
    main: SpecAxis,
    /// The column tracks including gutter tracks.
    cols: Vec<TrackSizing>,
    /// The row tracks including gutter tracks.
    rows: Vec<TrackSizing>,
    /// The children of the grid.
    children: &'a [AnyNode],
    /// The region to layout into.
    regions: Regions,
    /// Resolved column sizes.
    rcols: Vec<Length>,
    /// The full main size of the current region.
    full: Length,
    /// The used-up size of the current region. The cross size is determined
    /// once after columns are resolved and not touched again.
    used: Gen<Length>,
    /// The sum of fractional ratios in the current region.
    fr: Fractional,
    /// Rows in the current region.
    lrows: Vec<Row>,
    /// Frames for finished regions.
    finished: Vec<Frame>,
}

/// Produced by initial row layout, auto and linear rows are already finished,
/// fractional rows not yet.
enum Row {
    /// Finished row frame of auto or linear row.
    Frame(Frame),
    /// Ratio of a fractional row and y index of the track.
    Fr(Fractional, usize),
}

impl<'a> GridLayouter<'a> {
    /// Prepare grid layout by unifying content and gutter tracks.
    fn new(grid: &'a GridNode, mut regions: Regions) -> Self {
        let mut cols = vec![];
        let mut rows = vec![];

        // Number of content columns: Always at least one.
        let c = grid.tracks.cross.len().max(1);

        // Number of content rows: At least as many as given, but also at least
        // as many as needed to place each item.
        let r = {
            let len = grid.children.len();
            let given = grid.tracks.main.len();
            let needed = len / c + (len % c).clamp(0, 1);
            given.max(needed)
        };

        let auto = TrackSizing::Auto;
        let zero = TrackSizing::Linear(Linear::zero());
        let get_or = |tracks: &[_], idx, default| {
            tracks.get(idx).or(tracks.last()).copied().unwrap_or(default)
        };

        // Collect content and gutter columns.
        for x in 0 .. c {
            cols.push(get_or(&grid.tracks.cross, x, auto));
            cols.push(get_or(&grid.gutter.cross, x, zero));
        }

        // Collect content and gutter rows.
        for y in 0 .. r {
            rows.push(get_or(&grid.tracks.main, y, auto));
            rows.push(get_or(&grid.gutter.main, y, zero));
        }

        // Remove superfluous gutter tracks.
        cols.pop();
        rows.pop();

        let cross = grid.dirs.cross.axis();
        let main = grid.dirs.main.axis();
        let full = regions.current.get(main);
        let rcols = vec![Length::zero(); cols.len()];

        // We use the regions only for auto row measurement.
        regions.expand = Gen::new(true, false).to_spec(main);

        Self {
            cross,
            main,
            cols,
            rows,
            children: &grid.children,
            regions,
            rcols,
            lrows: vec![],
            full,
            used: Gen::zero(),
            fr: Fractional::zero(),
            finished: vec![],
        }
    }

    /// Determine all column sizes.
    fn measure_columns(&mut self, ctx: &mut LayoutContext) {
        // Sum of sizes of resolved linear tracks.
        let mut linear = Length::zero();

        // Sum of fractions of all fractional tracks.
        let mut fr = Fractional::zero();

        // Generic version of current and base size.
        let current = self.regions.current.to_gen(self.main);
        let base = self.regions.base.to_gen(self.main);

        // Resolve the size of all linear columns and compute the sum of all
        // fractional tracks.
        for (&col, rcol) in self.cols.iter().zip(&mut self.rcols) {
            match col {
                TrackSizing::Auto => {}
                TrackSizing::Linear(v) => {
                    let resolved = v.resolve(base.cross);
                    *rcol = resolved;
                    linear += resolved;
                }
                TrackSizing::Fractional(v) => fr += v,
            }
        }

        // Size that is not used by fixed-size columns.
        let available = current.cross - linear;
        if available >= Length::zero() {
            // Determine size of auto columns.
            let (auto, count) = self.measure_auto_columns(ctx, available);

            // If there is remaining space, distribute it to fractional columns,
            // otherwise shrink auto columns.
            let remaining = available - auto;
            if remaining >= Length::zero() {
                self.grow_fractional_columns(remaining, fr);
            } else {
                self.shrink_auto_columns(available, count);
            }
        }

        self.used.cross = self.rcols.iter().sum();
    }

    /// Measure the size that is available to auto columns.
    fn measure_auto_columns(
        &mut self,
        ctx: &mut LayoutContext,
        available: Length,
    ) -> (Length, usize) {
        let mut auto = Length::zero();
        let mut count = 0;

        // Determine size of auto columns by laying out all cells in those
        // columns, measuring them and finding the largest one.
        for (x, &col) in self.cols.iter().enumerate() {
            if col != TrackSizing::Auto {
                continue;
            }

            let mut resolved = Length::zero();
            for node in (0 .. self.rows.len()).filter_map(|y| self.cell(x, y)) {
                let size = Gen::new(available, Length::inf()).to_size(self.main);
                let regions = Regions::one(size, Spec::splat(false));
                let frame = node.layout(ctx, &regions).remove(0);
                resolved.set_max(frame.size.get(self.cross));
            }

            self.rcols[x] = resolved;
            auto += resolved;
            count += 1;
        }

        (auto, count)
    }

    /// Distribute remaining space to fractional columns.
    fn grow_fractional_columns(&mut self, remaining: Length, fr: Fractional) {
        for (&col, rcol) in self.cols.iter().zip(&mut self.rcols) {
            if let TrackSizing::Fractional(v) = col {
                let ratio = v / fr;
                if ratio.is_finite() {
                    *rcol = ratio * remaining;
                }
            }
        }
    }

    /// Redistribute space to auto columns so that each gets a fair share.
    fn shrink_auto_columns(&mut self, available: Length, count: usize) {
        // The fair share each auto column may have.
        let fair = available / count as f64;

        // The number of overlarge auto columns and the space that will be
        // equally redistributed to them.
        let mut overlarge: usize = 0;
        let mut redistribute = available;

        // Find out the number of and space used by overlarge auto columns.
        for (&col, rcol) in self.cols.iter().zip(&mut self.rcols) {
            if col == TrackSizing::Auto {
                if *rcol > fair {
                    overlarge += 1;
                } else {
                    redistribute -= *rcol;
                }
            }
        }

        // Redistribute the space equally.
        let share = redistribute / overlarge as f64;
        for (&col, rcol) in self.cols.iter().zip(&mut self.rcols) {
            if col == TrackSizing::Auto && *rcol > fair {
                *rcol = share;
            }
        }
    }

    /// Layout the grid row-by-row.
    fn layout(mut self, ctx: &mut LayoutContext) -> Vec<Frame> {
        for y in 0 .. self.rows.len() {
            match self.rows[y] {
                TrackSizing::Auto => {
                    self.layout_auto_row(ctx, y);
                }
                TrackSizing::Linear(v) => {
                    let base = self.regions.base.get(self.main);
                    let resolved = v.resolve(base);
                    let frame = self.layout_single_row(ctx, resolved, y);
                    self.push_row(ctx, frame);
                }
                TrackSizing::Fractional(v) => {
                    self.fr += v;
                    self.lrows.push(Row::Fr(v, y));
                }
            }
        }

        self.finish_region(ctx);
        self.finished
    }

    /// Layout a row with automatic size along the main axis. Such a row may
    /// break across multiple regions.
    fn layout_auto_row(&mut self, ctx: &mut LayoutContext, y: usize) {
        let mut first = Length::zero();
        let mut rest: Vec<Length> = vec![];

        // Determine the size for each region of the row.
        for (x, &rcol) in self.rcols.iter().enumerate() {
            if let Some(node) = self.cell(x, y) {
                let cross = self.cross;
                self.regions.mutate(|size| *size.get_mut(cross) = rcol);

                let mut sizes = node
                    .layout(ctx, &self.regions)
                    .into_iter()
                    .map(|frame| frame.size.get(self.main));

                if let Some(size) = sizes.next() {
                    first.set_max(size);
                }

                for (resolved, size) in rest.iter_mut().zip(&mut sizes) {
                    resolved.set_max(size);
                }

                rest.extend(sizes);
            }
        }

        // Layout the row.
        if rest.is_empty() {
            let frame = self.layout_single_row(ctx, first, y);
            self.push_row(ctx, frame);
        } else {
            let frames = self.layout_multi_row(ctx, first, &rest, y);
            for frame in frames {
                self.push_row(ctx, frame);
            }
        }
    }

    /// Layout a row with a fixed size along the main axis.
    fn layout_single_row(
        &self,
        ctx: &mut LayoutContext,
        length: Length,
        y: usize,
    ) -> Frame {
        let size = self.to_size(length);
        let mut output = Frame::new(size, size.height);
        let mut pos = Gen::zero();

        for (x, &rcol) in self.rcols.iter().enumerate() {
            if let Some(node) = self.cell(x, y) {
                let size = Gen::new(rcol, length).to_size(self.main);
                let regions = Regions::one(size, Spec::splat(true));
                let frame = node.layout(ctx, &regions).remove(0);
                output.push_frame(pos.to_point(self.main), frame);
            }

            pos.cross += rcol;
        }

        output
    }

    /// Layout a row spanning multiple regions.
    fn layout_multi_row(
        &self,
        ctx: &mut LayoutContext,
        first: Length,
        rest: &[Length],
        y: usize,
    ) -> Vec<Frame> {
        // Prepare frames.
        let mut outputs: Vec<_> = std::iter::once(first)
            .chain(rest.iter().copied())
            .map(|v| self.to_size(v))
            .map(|size| Frame::new(size, size.height))
            .collect();

        // Prepare regions.
        let mut regions = Regions::one(self.to_size(first), Spec::splat(true));
        regions.backlog = rest.iter().rev().map(|&v| self.to_size(v)).collect();

        // Layout the row.
        let mut pos = Gen::zero();
        for (x, &rcol) in self.rcols.iter().enumerate() {
            if let Some(node) = self.cell(x, y) {
                regions.mutate(|size| *size.get_mut(self.cross) = rcol);

                // Push the layouted frames into the individual output frames.
                let frames = node.layout(ctx, &regions);
                for (output, frame) in outputs.iter_mut().zip(frames) {
                    output.push_frame(pos.to_point(self.main), frame);
                }
            }

            pos.cross += rcol;
        }

        outputs
    }

    /// Push a row frame into the current or next fitting region, finishing
    /// regions (including layouting fractional rows) if necessary.
    fn push_row(&mut self, ctx: &mut LayoutContext, frame: Frame) {
        let length = frame.size.get(self.main);

        // Skip to fitting region.
        while !self.regions.current.get(self.main).fits(length)
            && !self.regions.in_full_last()
        {
            self.finish_region(ctx);
        }

        *self.regions.current.get_mut(self.main) -= length;
        self.used.main += length;
        self.lrows.push(Row::Frame(frame));
    }

    /// Finish rows for one region.
    fn finish_region(&mut self, ctx: &mut LayoutContext) {
        // Determine the size of the region.
        let length = if self.fr.is_zero() { self.used.main } else { self.full };
        let size = self.to_size(length);

        // The frame for the region.
        let mut output = Frame::new(size, size.height);
        let mut pos = Gen::zero();

        // Determine the remaining size for fractional rows.
        let remaining = self.full - self.used.main;

        // Place finished rows and layout fractional rows.
        for row in std::mem::take(&mut self.lrows) {
            let frame = match row {
                Row::Frame(frame) => frame,
                Row::Fr(v, y) => {
                    let ratio = v / self.fr;
                    if remaining > Length::zero() && ratio.is_finite() {
                        let resolved = ratio * remaining;
                        self.layout_single_row(ctx, resolved, y)
                    } else {
                        continue;
                    }
                }
            };

            let main = frame.size.get(self.main);
            output.push_frame(pos.to_point(self.main), frame);
            pos.main += main;
        }

        self.regions.next();
        self.full = self.regions.current.get(self.main);
        self.used.main = Length::zero();
        self.fr = Fractional::zero();
        self.finished.push(output);
    }

    /// Get the node in the cell in column `x` and row `y`.
    ///
    /// Returns `None` if it's a gutter cell.
    fn cell(&self, x: usize, y: usize) -> Option<&'a AnyNode> {
        assert!(x < self.cols.len());
        assert!(y < self.rows.len());

        // Even columns and rows are children, odd ones are gutter.
        if x % 2 == 0 && y % 2 == 0 {
            let c = 1 + self.cols.len() / 2;
            self.children.get((y / 2) * c + x / 2)
        } else {
            None
        }
    }

    /// Return a size where the cross axis spans the whole grid and the main
    /// axis the given length.
    fn to_size(&self, main_size: Length) -> Size {
        Gen::new(self.used.cross, main_size).to_size(self.main)
    }
}