Skip to main content

devpage_design/display/
run.rs

1//! A run's children in the index: each child a space of its own — its
2//! chunks in its own coordinates under an R-tree of its own — placed along
3//! the run by the prefix sums of the sizes before it. The run is one entry in
4//! the space it sits in; a query inside it finds the first child that
5//! reaches the rectangle by a search of the sums, widened by the furthest any
6//! child paints past its box, and walks on until a child starts past it. A
7//! child that changes size moves no other child's entry: their places are
8//! the sums.
9
10use std::collections::{BTreeMap, HashMap};
11
12use kurbo::{Rect as KRect, Vec2};
13
14use crate::prefix_sums::{Item, Summary, Sums};
15use crate::tree::OrderKey;
16
17use super::*;
18
19/// A run, by its slot.
20pub type RunId = u32;
21
22/// Where a chunk's coordinates are: the design's own, or a run's child's,
23/// whose origin is the child's box's top-left.
24#[derive(Clone, Debug, PartialEq, Eq, Hash)]
25pub enum Space {
26    /// The design's own coordinates: those of every chunk not inside a run's
27    /// child.
28    Root,
29    /// The coordinates of the child at this key of this run, from its box's
30    /// top-left.
31    Item(RunId, OrderKey),
32}
33
34/// A run's children placed along it, and what they paint.
35pub struct Run {
36    /// The space its own node is in.
37    pub space: Space,
38    /// Its node's unrounded top-left and its rounded one, in its space.
39    pub raw: Vec2,
40    /// Its node's rounded top-left, in its space.
41    pub at: Vec2,
42    /// Where its space's origin was in the design's coordinates when it was
43    /// last placed: its children are placed in single precision there, as
44    /// taffy places them, so they round where a whole tree's do.
45    pub origin: Vec2,
46    /// Whether its children go along x; else along y.
47    pub row: bool,
48    /// A frame with no layout: each child at a place of its own, found by
49    /// an R-tree of their boxes rather than by the sums.
50    pub free: bool,
51    /// In a free run, what each child reaches, by bounds: what finds the children
52    /// that touch a rectangle.
53    pub(super) boxes: rstar::RTree<Boxed>,
54    /// In a free run, the left, top, right and bottom edges of what its children
55    /// reach, as counted sets, from its node's unrounded top-left.
56    pub(super) free_reach: [Counted; 4],
57    /// In a free run, the left, top, right and bottom edges of what its children
58    /// cover, as counted sets, from its node's unrounded top-left.
59    pub(super) free_cover: [Counted; 4],
60    /// Where its first child starts along the run, from its node's unrounded
61    /// top-left: the padding and any `justify` offset.
62    pub start: f64,
63    /// Where its children's line starts across, from the same: the padding.
64    pub across: f64,
65    /// How far apart its children are: its gap, and any room
66    /// `"space-between"` spreads between them — one number for the run, so
67    /// a change of it moves no child's entry.
68    pub gap: f64,
69    /// The breadth of its children's line.
70    pub line: f64,
71    /// What cuts it in its space: its clipping frames' boxes.
72    pub cut: Option<KRect>,
73    /// Its children in order, each as the sums see it: the sums place them.
74    pub(super) items: Sums<OrderKey, Placed>,
75    /// Each child's own space's index, by the child's key.
76    pub(super) spaces: HashMap<OrderKey, SpaceIndex>,
77    /// The furthest any child reaches past its box along the run, and each
78    /// child's reach and cover across, from the line's start: counted sets.
79    pub(super) overhang: Counted,
80    /// Where each child's reach starts and ends across, from the line's start.
81    pub(super) reach_across: (Counted, Counted),
82    /// Where each child's cover starts and ends across, from the line's start.
83    pub(super) cover_across: (Counted, Counted),
84    /// Its entry in its space's index, and what it adds to its space's cover.
85    pub(super) entry: Option<KRect>,
86    /// What it adds to its space's cover: what its children cover, cut to its
87    /// clipping frames.
88    pub(super) cover: Option<KRect>,
89}
90
91/// One space's index: its chunks and runs by their bounds in its own
92/// coordinates, and the extent of what its chunks cover.
93#[derive(Default)]
94pub struct SpaceIndex {
95    /// Its chunks and runs, by their bounds in its own coordinates.
96    pub(super) index: rstar::RTree<Entry>,
97    /// The extent of what its chunks cover.
98    pub(super) covers: Extent,
99}
100
101/// A child of a run as the run's sums see it: its size along the run, where
102/// it sits across, and what it reaches and covers along the run from its
103/// unrounded start.
104#[derive(Clone, Debug, PartialEq)]
105pub struct Placed {
106    /// Its size along the run.
107    pub size: f64,
108    /// In a free run, its unrounded top-left from the run's node's.
109    pub at: Option<Vec2>,
110    /// In a free run, what it reaches and covers in the run's space.
111    pub(super) boxed: Option<KRect>,
112    /// In a free run, what it covers, from the run's node's unrounded top-left.
113    pub(super) cover_box: Option<KRect>,
114    /// Its unrounded place across, from the line's start.
115    pub across: f64,
116    /// Its rounded top-left less its unrounded one: fixed while what the
117    /// run places it at keeps its fraction of a pixel.
118    pub delta: Vec2,
119    /// Where what it reaches starts and ends along the run, from its unrounded
120    /// start; `None` when its space holds nothing.
121    pub(super) reach: Option<(f64, f64)>,
122    /// Where what it covers starts and ends along the run, from its unrounded
123    /// start; `None` when it covers nothing.
124    pub(super) covered: Option<(f64, f64)>,
125    /// What it put in the run's counted sets, to take out again.
126    pub(super) counted: Counts,
127}
128
129/// A child's entries in its run's counted sets.
130#[derive(Clone, Debug, PartialEq, Default)]
131pub struct Counts {
132    /// How far it reaches past its box along the run, in the run's `overhang`.
133    overhang: Option<f64>,
134    /// Where its reach starts and ends across, in the run's `reach_across`.
135    reach: Option<(f64, f64)>,
136    /// Where its cover starts and ends across, in the run's `cover_across`.
137    cover: Option<(f64, f64)>,
138}
139
140impl Placed {
141    /// A free run's child, at `at` from the run's node's top-left.
142    pub fn at(at: Vec2, delta: Vec2) -> Placed {
143        Placed {
144            at: Some(at),
145            ..Placed::new(0.0, 0.0, delta)
146        }
147    }
148
149    /// A child of a run in the flow: `size` along it, `across` from the line's
150    /// start, its rounded top-left `delta` from its unrounded one.
151    pub fn new(size: f64, across: f64, delta: Vec2) -> Placed {
152        Placed {
153            at: None,
154            boxed: None,
155            cover_box: None,
156            size,
157            across,
158            delta,
159            reach: None,
160            covered: None,
161            counted: Counts::default(),
162        }
163    }
164}
165
166/// A stretch of a run's children: how many, and the sum of their sizes —
167/// how far they advance less the gaps, which are the run's.
168#[derive(Clone, Debug, Default)]
169pub struct Span {
170    /// How many children.
171    pub n: usize,
172    /// The sum of their sizes along the run, gaps left out.
173    pub length: f64,
174}
175
176impl Summary for Span {
177    fn then(&self, next: &Self) -> Self {
178        Span {
179            n: self.n + next.n,
180            length: self.length + next.length,
181        }
182    }
183}
184
185impl Item for Placed {
186    type Sum = Span;
187    fn summary(&self) -> Span {
188        Span {
189            n: 1,
190            length: self.size,
191        }
192    }
193}
194
195/// A free run's child's entry in the run's R-tree: what it reaches.
196#[derive(Clone, Debug, PartialEq)]
197pub(super) struct Boxed {
198    /// The child's key in the run.
199    pub(super) key: OrderKey,
200    /// What it reaches, from the run's node's unrounded top-left.
201    pub(super) bounds: KRect,
202}
203
204impl rstar::RTreeObject for Boxed {
205    type Envelope = rstar::AABB<[f64; 2]>;
206    fn envelope(&self) -> Self::Envelope {
207        rstar::AABB::from_corners(
208            [self.bounds.x0, self.bounds.y0],
209            [self.bounds.x1, self.bounds.y1],
210        )
211    }
212}
213
214/// A multiset of numbers that knows its least and greatest in log time.
215#[derive(Default)]
216pub struct Counted(BTreeMap<i64, usize>);
217
218impl Counted {
219    /// Counts `v` once more, to the millionth.
220    pub(super) fn add(&mut self, v: f64) {
221        *self.0.entry(key(v)).or_default() += 1;
222    }
223    /// Counts `v` once less; a `v` not in the set is ignored.
224    pub(super) fn remove(&mut self, v: f64) {
225        let k = key(v);
226        if let Some(n) = self.0.get_mut(&k) {
227            *n -= 1;
228            if *n == 0 {
229                self.0.remove(&k);
230            }
231        }
232    }
233    /// The least number in the set; `None` when it is empty.
234    pub(super) fn least(&self) -> Option<f64> {
235        self.0.keys().next().map(|k| *k as f64 / 1e6)
236    }
237    /// The greatest number in the set; `None` when it is empty.
238    pub(super) fn greatest(&self) -> Option<f64> {
239        self.0.keys().next_back().map(|k| *k as f64 / 1e6)
240    }
241}
242
243/// A rectangle's span along a run and across it.
244fn spans(row: bool, r: KRect) -> ((f64, f64), (f64, f64)) {
245    if row {
246        ((r.x0, r.x1), (r.y0, r.y1))
247    } else {
248        ((r.y0, r.y1), (r.x0, r.x1))
249    }
250}
251
252/// The rectangle spanning `along` the run and `across` it: [`spans`] undone.
253fn rect(row: bool, along: (f64, f64), across: (f64, f64)) -> KRect {
254    if row {
255        KRect::new(along.0, across.0, along.1, across.1)
256    } else {
257        KRect::new(across.0, along.0, across.1, along.1)
258    }
259}
260
261impl Run {
262    /// An empty run in `space`, along y, its node at the space's origin.
263    pub fn new(space: Space) -> Run {
264        Run {
265            space,
266            raw: Vec2::ZERO,
267            at: Vec2::ZERO,
268            origin: Vec2::ZERO,
269            row: false,
270            free: false,
271            boxes: rstar::RTree::new(),
272            free_reach: Default::default(),
273            free_cover: Default::default(),
274            start: 0.0,
275            across: 0.0,
276            gap: 0.0,
277            line: 0.0,
278            cut: None,
279            items: Sums::new(),
280            spaces: HashMap::new(),
281            overhang: Counted::default(),
282            reach_across: Default::default(),
283            cover_across: Default::default(),
284            entry: None,
285            cover: None,
286        }
287    }
288
289    /// How many children it has.
290    pub fn len(&self) -> usize {
291        self.items.len()
292    }
293
294    /// Whether it has no children.
295    pub fn is_empty(&self) -> bool {
296        self.items.is_empty()
297    }
298
299    /// Where a free run places a child at `at` from its node: its unrounded
300    /// top-left and its rounded one, measured from the run's node, as taffy
301    /// rounds a box placed in its parent.
302    pub fn place_at(&self, at: Vec2) -> (Vec2, Vec2) {
303        let o = self.origin;
304        let (rx, ry) = ((o.x + self.raw.x) as f32, (o.y + self.raw.y) as f32);
305        let raw = (rx + at.x as f32, ry + at.y as f32);
306        let snap32 = |v: f32| (v + 0.5).floor();
307        let rounded = (
308            (o.x + self.at.x) as f32 + snap32(raw.0) - snap32(rx),
309            (o.y + self.at.y) as f32 + snap32(raw.1) - snap32(ry),
310        );
311        (
312            Vec2::new(raw.0 as f64 - o.x, raw.1 as f64 - o.y),
313            Vec2::new(rounded.0 as f64 - o.x, rounded.1 as f64 - o.y),
314        )
315    }
316
317    /// Where the run places a child `before` along it and `across` from its
318    /// line's start: its unrounded top-left in the run's space, and its rounded
319    /// one — each edge where taffy's rounding pass puts it, measured from the
320    /// run's node, a box in the flow.
321    pub fn place(&self, before: f64, across: f64) -> (Vec2, Vec2) {
322        // In single precision, as taffy places a box and its rounding pass
323        // rounds it: the child's place within the run, then the run's.
324        let along = (self.start + before) as f32;
325        let across = (self.across + across) as f32;
326        let (dx, dy) = if self.row {
327            (along, across)
328        } else {
329            (across, along)
330        };
331        let o = self.origin;
332        let (rx, ry) = ((o.x + self.raw.x) as f32, (o.y + self.raw.y) as f32);
333        let raw = (rx + dx, ry + dy);
334        let snap32 = |v: f32| (v + 0.5).floor();
335        let at = (
336            (o.x + self.at.x) as f32 + snap32(raw.0) - snap32(rx),
337            (o.y + self.at.y) as f32 + snap32(raw.1) - snap32(ry),
338        );
339        (
340            Vec2::new(raw.0 as f64 - o.x, raw.1 as f64 - o.y),
341            Vec2::new(at.0 as f64 - o.x, at.1 as f64 - o.y),
342        )
343    }
344
345    /// The child at `key`: how far along the run the children before it
346    /// advance, and how it is placed.
347    pub fn child(&self, key: &OrderKey) -> Option<(f64, &Placed)> {
348        let placed = self.items.get(key)?;
349        Some((self.prefix(key), placed))
350    }
351
352    /// How far along the run the children before `key` advance, gaps and
353    /// all.
354    pub fn prefix(&self, key: &OrderKey) -> f64 {
355        let s = self.items.before(key);
356        s.length + s.n as f64 * self.gap
357    }
358
359    /// The keys of the children after `key`, in order.
360    pub fn keys_after(&self, key: &OrderKey) -> Vec<OrderKey> {
361        self.items
362            .from(key)
363            .filter(|(k, _)| *k != key)
364            .map(|(k, _)| k.clone())
365            .collect()
366    }
367
368    /// Its entry's bounds in its space's index.
369    pub fn entry(&self) -> Option<KRect> {
370        self.entry
371    }
372
373    /// Where the child at `key` is: its rounded top-left in the run's space.
374    pub fn child_at(&self, key: &OrderKey) -> Option<Vec2> {
375        if self.free {
376            let p = self.items.get(key)?;
377            return Some(self.place_at(p.at.unwrap_or(Vec2::ZERO)).1);
378        }
379        let (before, p) = self.child(key)?;
380        Some(self.place(before, p.across).1)
381    }
382
383    /// The children in order, each with how far the ones before it advance.
384    pub fn children(&self) -> impl Iterator<Item = (&OrderKey, f64, &Placed)> {
385        let mut before = 0.0;
386        let gap = self.gap;
387        self.items.iter().map(move |(k, p)| {
388            let b = before;
389            before += p.size + gap;
390            (k, b, p)
391        })
392    }
393
394    /// The children that can touch `r`, in the run's space, in order: from
395    /// the first whose box ends past `r`'s start, less the furthest any child
396    /// reaches past its box, to the last that starts before its end, plus
397    /// that.
398    pub(super) fn touching(&self, r: KRect) -> Vec<(&OrderKey, Vec2)> {
399        self.touching_rounded(r)
400            .into_iter()
401            .map(|(k, at, _)| (k, at))
402            .collect()
403    }
404
405    /// [`Run::touching`], each child with whether it still rounds as its
406    /// space was made: whether its rounded place less its unrounded one is
407    /// what it was when its boxes and chunks were made. A child the sums
408    /// moved by a fraction of a pixel doesn't, and is rounded anew before it
409    /// is read.
410    pub(super) fn touching_rounded(&self, r: KRect) -> Vec<(&OrderKey, Vec2, bool)> {
411        if self.free {
412            let env = rstar::AABB::from_corners([r.x0, r.y0], [r.x1, r.y1]);
413            let mut found: Vec<&Boxed> = self.boxes.locate_in_envelope_intersecting(&env).collect();
414            found.sort_by(|a, b| a.key.cmp(&b.key));
415            return found
416                .into_iter()
417                .filter_map(|b| {
418                    let (k, p) = (&b.key, self.items.get(&b.key)?);
419                    let (raw, rounded) = self.place_at(p.at.unwrap_or(Vec2::ZERO));
420                    let fresh = ((rounded - raw) - p.delta).hypot() < 1e-3;
421                    Some((k, rounded, fresh))
422                })
423                .collect();
424        }
425        let ((a0, a1), _) = spans(self.row, r);
426        let base = if self.row { self.raw.x } else { self.raw.y } + self.start;
427        let over = self.overhang.greatest().unwrap_or(0.0).max(0.0);
428        let (from, to) = (a0 - base - over, a1 - base + over);
429        let gap = self.gap;
430        let Some((first, _, before)) = self
431            .items
432            .seek(|s| s.length + s.n.saturating_sub(1) as f64 * gap >= from)
433        else {
434            return Vec::new();
435        };
436        let mut out = Vec::new();
437        let mut at = before.length + before.n as f64 * gap;
438        for (k, p) in self.items.from(first) {
439            if at > to {
440                break;
441            }
442            let (raw, rounded) = self.place(at, p.across);
443            let fresh = ((rounded - raw) - p.delta).hypot() < 1e-3;
444            out.push((k, rounded, fresh));
445            at += p.size + gap;
446        }
447        out
448    }
449
450    /// What the run's children reach and cover in its space, from its sums
451    /// and counted sets; `None` where nothing. Along the run, the least is
452    /// found walking in from the first child and the greatest from the
453    /// last, each only while a child could still reach past the best found
454    /// — no further than the furthest any child reaches past its box.
455    pub(super) fn extents(&self) -> (Option<KRect>, Option<KRect>) {
456        if self.free {
457            let make = |c: &[Counted; 4]| {
458                let (Some(x0), Some(y0), Some(x1), Some(y1)) =
459                    (c[0].least(), c[1].least(), c[2].greatest(), c[3].greatest())
460                else {
461                    return None;
462                };
463                Some(KRect::new(x0, y0, x1, y1) + self.raw)
464            };
465            let cover = make(&self.free_cover).and_then(|r| super::chunk::cut_to(r, self.cut));
466            return (make(&self.free_reach), cover);
467        }
468        let base = if self.row { self.raw.x } else { self.raw.y } + self.start;
469        let across = if self.row { self.raw.y } else { self.raw.x } + self.across;
470        let over = self.overhang.greatest().unwrap_or(0.0).max(0.0);
471        let along = |of: fn(&Placed) -> Option<(f64, f64)>| -> Option<(f64, f64)> {
472            let gap = self.gap;
473            let mut lo = f64::INFINITY;
474            let mut at = 0.0;
475            for (_, p) in self.items.iter() {
476                if at - over > lo {
477                    break;
478                }
479                if let Some((l, _)) = of(p) {
480                    lo = lo.min(at + l);
481                }
482                at += p.size + gap;
483            }
484            let total = self.items.total();
485            let mut hi = f64::NEG_INFINITY;
486            let mut end = total.length + total.n.saturating_sub(1) as f64 * gap;
487            for (_, p) in self.items.rev() {
488                let start = end - p.size;
489                if end + over < hi {
490                    break;
491                }
492                if let Some((_, h)) = of(p) {
493                    hi = hi.max(start + h);
494                }
495                end = start - gap;
496            }
497            (lo <= hi).then_some((lo, hi))
498        };
499        let make = |along: Option<(f64, f64)>, lo: &Counted, hi: &Counted| {
500            let along = along?;
501            let (Some(c0), Some(c1)) = (lo.least(), hi.greatest()) else {
502                return None;
503            };
504            Some(rect(
505                self.row,
506                (base + along.0, base + along.1),
507                (across + c0, across + c1),
508            ))
509        };
510        let reach = make(
511            along(|p| p.reach),
512            &self.reach_across.0,
513            &self.reach_across.1,
514        );
515        let cover = make(
516            along(|p| p.covered),
517            &self.cover_across.0,
518            &self.cover_across.1,
519        )
520        .and_then(|r| super::chunk::cut_to(r, self.cut));
521        (reach, cover)
522    }
523
524    /// Puts what a child is, from its space's index and covers, in the sums
525    /// and the counted sets.
526    pub(super) fn set(&mut self, key: OrderKey, mut placed: Placed) {
527        self.unset(&key);
528        if self.free {
529            let local = self.spaces.entry(key.clone()).or_default();
530            let env = local.index.root().envelope();
531            let reach = (env.lower()[0] <= env.upper()[0]).then(|| {
532                KRect::new(
533                    env.lower()[0],
534                    env.lower()[1],
535                    env.upper()[0],
536                    env.upper()[1],
537                )
538            });
539            let covered = local.covers.rect();
540            // In the run's own coordinates, from its node's unrounded
541            // top-left: the child's rounded place less that.
542            let at = placed.at.unwrap_or(Vec2::ZERO) + placed.delta;
543            placed.boxed = reach.map(|r| r + at);
544            placed.cover_box = covered.map(|r| r + at);
545            if let Some(b) = placed.boxed {
546                self.boxes.insert(Boxed {
547                    key: key.clone(),
548                    bounds: b,
549                });
550                for (c, v) in self.free_reach.iter_mut().zip([b.x0, b.y0, b.x1, b.y1]) {
551                    c.add(v);
552                }
553            }
554            if let Some(b) = placed.cover_box {
555                for (c, v) in self.free_cover.iter_mut().zip([b.x0, b.y0, b.x1, b.y1]) {
556                    c.add(v);
557                }
558            }
559            self.items.insert(key, placed);
560            return;
561        }
562        let local = self.spaces.entry(key.clone()).or_default();
563        let reach = local.index.root().envelope();
564        let reach = (reach.lower()[0] <= reach.upper()[0]).then(|| {
565            KRect::new(
566                reach.lower()[0],
567                reach.lower()[1],
568                reach.upper()[0],
569                reach.upper()[1],
570            )
571        });
572        let covered = local.covers.rect();
573        let d = if self.row {
574            (placed.delta.x, placed.delta.y)
575        } else {
576            (placed.delta.y, placed.delta.x)
577        };
578        let along = |r: KRect| {
579            let ((a0, a1), _) = spans(self.row, r);
580            (a0 + d.0, a1 + d.0)
581        };
582        let across = |r: KRect| {
583            let (_, (c0, c1)) = spans(self.row, r);
584            (placed.across + d.1 + c0, placed.across + d.1 + c1)
585        };
586        placed.reach = reach.map(along);
587        placed.covered = covered.map(along);
588        placed.counted = Counts::default();
589        if let Some(r) = reach {
590            let (lo, hi) = along(r);
591            let o = (-lo).max(hi - placed.size).max(0.0);
592            self.overhang.add(o);
593            let c = across(r);
594            self.reach_across.0.add(c.0);
595            self.reach_across.1.add(c.1);
596            placed.counted.overhang = Some(o);
597            placed.counted.reach = Some(c);
598        }
599        if let Some(r) = covered {
600            let c = across(r);
601            self.cover_across.0.add(c.0);
602            self.cover_across.1.add(c.1);
603            placed.counted.cover = Some(c);
604        }
605        self.items.insert(key, placed);
606    }
607
608    /// Takes a child out of the sums and the counted sets, keeping its
609    /// space; returns how it was placed.
610    pub(super) fn unset(&mut self, key: &OrderKey) -> Option<Placed> {
611        let p = self.items.remove(key)?;
612        if let Some(b) = p.boxed {
613            self.boxes.remove(&Boxed {
614                key: key.clone(),
615                bounds: b,
616            });
617            for (c, v) in self.free_reach.iter_mut().zip([b.x0, b.y0, b.x1, b.y1]) {
618                c.remove(v);
619            }
620        }
621        if let Some(b) = p.cover_box {
622            for (c, v) in self.free_cover.iter_mut().zip([b.x0, b.y0, b.x1, b.y1]) {
623                c.remove(v);
624            }
625        }
626        if let Some(o) = p.counted.overhang {
627            self.overhang.remove(o);
628        }
629        if let Some((c0, c1)) = p.counted.reach {
630            self.reach_across.0.remove(c0);
631            self.reach_across.1.remove(c1);
632        }
633        if let Some((c0, c1)) = p.counted.cover {
634            self.cover_across.0.remove(c0);
635            self.cover_across.1.remove(c1);
636        }
637        Some(p)
638    }
639}