Skip to main content

egui_pop_fit/
regions.rs

1//! Slot regions: named places around and over a surface (an image, a
2//! canvas), where cards sit.
3//!
4//! A [`Region`] has an [`Anchor`] (a corner, an edge, the centre, or the
5//! whole surface as an overlay), a [`Side`] (over the surface, or around
6//! it in the margin up to the bounds), a gap and a priority. A [`Card`] is
7//! one element of the slot engine, placed in one region. The regions are
8//! solved in priority order: each takes the room at its anchor that the
9//! regions before it left, packs its cards there with [`layout`](crate::layout),
10//! and its cards' block becomes an obstacle for the regions after it.
11//!
12//! When the room runs out, a region folds its lowest-priority card (the
13//! last in its order on a tie) and packs the others again, until the rest
14//! fit; then each folded card, the highest priority first, comes back if
15//! it fits beside them. A card is never placed over another one, nor cut.
16
17use crate::element::{Axis, Element, Orientation, Size2, SizePolicy};
18use crate::layout::{Container, Layout, PointRect, Reason, Status, layout};
19use crate::size::{Size, TWELFTHS_PER_UNIT};
20use core::fmt;
21use core::fmt::Write as _;
22
23/// Where a region sits on its surface. Start and end follow the
24/// direction: start is left in a left-to-right interface, right in a
25/// right-to-left one ([`Surface::right_to_left`]).
26#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
27#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
28#[non_exhaustive]
29pub enum Anchor {
30    /// The top start corner.
31    TopStart,
32    /// The top edge, centred.
33    Top,
34    /// The top end corner.
35    TopEnd,
36    /// The start edge, centred vertically.
37    Start,
38    /// The centre, between the regions around it.
39    Center,
40    /// The end edge, centred vertically.
41    End,
42    /// The bottom start corner.
43    BottomStart,
44    /// The bottom edge, centred.
45    Bottom,
46    /// The bottom end corner.
47    BottomEnd,
48    /// The whole surface, over the other regions: it neither avoids them
49    /// nor makes them move. Its cards are centred.
50    Overlay,
51}
52
53impl Anchor {
54    /// Every anchor, corners and edges in reading order, then the centre
55    /// and the overlay.
56    pub const ALL: [Anchor; 10] = [
57        Anchor::TopStart,
58        Anchor::Top,
59        Anchor::TopEnd,
60        Anchor::Start,
61        Anchor::Center,
62        Anchor::End,
63        Anchor::BottomStart,
64        Anchor::Bottom,
65        Anchor::BottomEnd,
66        Anchor::Overlay,
67    ];
68
69    /// Its name in kebab case (`top-start`).
70    pub fn name(self) -> &'static str {
71        match self {
72            Anchor::TopStart => "top-start",
73            Anchor::Top => "top",
74            Anchor::TopEnd => "top-end",
75            Anchor::Start => "start",
76            Anchor::Center => "center",
77            Anchor::End => "end",
78            Anchor::BottomStart => "bottom-start",
79            Anchor::Bottom => "bottom",
80            Anchor::BottomEnd => "bottom-end",
81            Anchor::Overlay => "overlay",
82        }
83    }
84
85    /// The way its cards flow by default: down the start and end edges,
86    /// across everywhere else.
87    pub fn default_flow(self) -> Axis {
88        match self {
89            Anchor::Start | Anchor::End => Axis::Height,
90            _ => Axis::Width,
91        }
92    }
93
94    /// Its logical place on each axis: start, middle or end.
95    fn places(self) -> (Place, Place) {
96        use Place::{End, Mid, Start};
97        match self {
98            Anchor::TopStart => (Start, Start),
99            Anchor::Top => (Mid, Start),
100            Anchor::TopEnd => (End, Start),
101            Anchor::Start => (Start, Mid),
102            Anchor::Center | Anchor::Overlay => (Mid, Mid),
103            Anchor::End => (End, Mid),
104            Anchor::BottomStart => (Start, End),
105            Anchor::Bottom => (Mid, End),
106            Anchor::BottomEnd => (End, End),
107        }
108    }
109}
110
111impl fmt::Display for Anchor {
112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113        f.write_str(self.name())
114    }
115}
116
117/// Whether a region lies over the surface or around it.
118#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
119#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
120#[non_exhaustive]
121pub enum Side {
122    /// On the surface, inside its edges.
123    #[default]
124    Over,
125    /// Outside the surface, in the margin between its edges and the
126    /// bounds ([`Surface::within`]), against the surface. The centre and
127    /// the overlay have no outside: they stay over.
128    Around,
129}
130
131impl fmt::Display for Side {
132    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133        f.write_str(match self {
134            Side::Over => "over",
135            Side::Around => "around",
136        })
137    }
138}
139
140/// A named place for cards on a surface.
141#[derive(Clone, Debug, PartialEq)]
142#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
143#[non_exhaustive]
144pub struct Region {
145    /// The caller's key, which cards name ([`Card::region`]).
146    pub key: u64,
147    /// Where it sits.
148    pub anchor: Anchor,
149    /// Over the surface or around it.
150    pub side: Side,
151    /// In points: from the surface's edges to the cards, between cards,
152    /// and between this region's cards and another region's.
153    pub gap: f32,
154    /// Regions with a higher priority take their room first.
155    pub priority: i32,
156    /// The way its cards flow: across in rows (`Width`) or down in
157    /// columns (`Height`), wrapping to a new row or column when one is
158    /// full.
159    pub flow: Axis,
160    /// In points, how far the region reaches into the surface across its
161    /// flow (a row band's height, a column band's width); `None` reaches
162    /// as far as the room allows.
163    pub depth: Option<f32>,
164}
165
166impl Region {
167    /// A region over the surface at `anchor`, with no gap, priority 0, its
168    /// anchor's default flow and no depth limit.
169    pub fn new(key: u64, anchor: Anchor) -> Region {
170        Region {
171            key,
172            anchor,
173            side: Side::Over,
174            gap: 0.0,
175            priority: 0,
176            flow: anchor.default_flow(),
177            depth: None,
178        }
179    }
180
181    /// The same region around the surface instead of over it.
182    pub fn around(mut self) -> Region {
183        self.side = Side::Around;
184        self
185    }
186
187    /// The same region with a gap of `gap` points.
188    pub fn with_gap(mut self, gap: f32) -> Region {
189        self.gap = gap;
190        self
191    }
192
193    /// The same region with a priority.
194    pub fn with_priority(mut self, priority: i32) -> Region {
195        self.priority = priority;
196        self
197    }
198
199    /// The same region flowing its cards along `flow`.
200    pub fn with_flow(mut self, flow: Axis) -> Region {
201        self.flow = flow;
202        self
203    }
204
205    /// The same region reaching at most `depth` points across its flow.
206    pub fn with_depth(mut self, depth: f32) -> Region {
207        self.depth = Some(depth);
208        self
209    }
210}
211
212/// A card: one element of the slot engine, placed in a region.
213#[derive(Clone, Debug, PartialEq)]
214#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
215#[non_exhaustive]
216pub struct Card {
217    /// The region's key.
218    pub region: u64,
219    /// The element: its key (unique across the cards), forms,
220    /// orientations, and its pin, counted from the region's anchor corner.
221    pub element: Element,
222    /// When room runs out, cards with a lower priority fold first.
223    pub priority: i32,
224    /// A size in points, `[width, height]`, instead of the element's
225    /// forms: the card takes the smallest slot holding it and the gap,
226    /// and its rectangle is this size, against the anchor in its slot.
227    pub size: Option<[f32; 2]>,
228}
229
230impl Card {
231    /// A card for `element` in the region keyed `region`, priority 0.
232    pub fn new(region: u64, element: Element) -> Card {
233        Card {
234            region,
235            element,
236            priority: 0,
237            size: None,
238        }
239    }
240
241    /// A card of one fixed slot size.
242    pub fn fixed(key: u64, region: u64, size: Size2) -> Card {
243        Card::new(region, Element::new(key, SizePolicy::fixed(size)))
244    }
245
246    /// A card `width` by `height` points.
247    pub fn sized(key: u64, region: u64, width: f32, height: f32) -> Card {
248        let one = Size2::new(Size::ONE, Size::ONE);
249        let mut card = Card::fixed(key, region, one);
250        card.size = Some([width, height]);
251        card
252    }
253
254    /// The same card with a priority.
255    pub fn with_priority(mut self, priority: i32) -> Card {
256        self.priority = priority;
257        self
258    }
259
260    /// The card's key (its element's).
261    pub fn key(&self) -> u64 {
262        self.element.key
263    }
264}
265
266/// The surface the regions sit on and around, in points.
267#[derive(Clone, Copy, Debug, PartialEq)]
268#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
269#[non_exhaustive]
270pub struct Surface {
271    /// The surface (an image, a canvas).
272    pub rect: PointRect,
273    /// What the regions around it may use: the surface and its margin.
274    pub bounds: PointRect,
275    /// The slot engine's base unit, in points.
276    pub unit: f32,
277    /// Whether start is on the right.
278    pub rtl: bool,
279}
280
281impl Surface {
282    /// A surface with no margin around it, left to right.
283    pub fn new(rect: PointRect, unit: f32) -> Surface {
284        Surface {
285            rect,
286            bounds: rect,
287            unit,
288            rtl: false,
289        }
290    }
291
292    /// The same surface within `bounds`, the room for the regions around
293    /// it.
294    pub fn within(mut self, bounds: PointRect) -> Surface {
295        self.bounds = bounds;
296        self
297    }
298
299    /// The same surface, start on the right when `rtl`.
300    pub fn right_to_left(mut self, rtl: bool) -> Surface {
301        self.rtl = rtl;
302        self
303    }
304}
305
306/// What became of a card.
307#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
308#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
309#[non_exhaustive]
310pub enum CardStatus {
311    /// Placed: it has a rectangle.
312    Placed,
313    /// Not placed: the host folds it (a menu, a "more" chip) or shows it
314    /// elsewhere. `NoRoom` when cards with a higher priority took the
315    /// room; `TooNarrow` or `TooShort` when even the region's whole room
316    /// cannot hold it.
317    Folded(Reason),
318    /// Its region is not declared.
319    NoRegion,
320}
321
322impl CardStatus {
323    /// Whether the card has a rectangle.
324    pub fn is_placed(&self) -> bool {
325        matches!(self, CardStatus::Placed)
326    }
327}
328
329impl fmt::Display for CardStatus {
330    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
331        match self {
332            CardStatus::Placed => f.write_str("placed"),
333            CardStatus::Folded(r) => write!(f, "folded({r})"),
334            CardStatus::NoRegion => f.write_str("no-region"),
335        }
336    }
337}
338
339/// Where a card went.
340#[derive(Clone, Copy, Debug, PartialEq)]
341#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
342#[non_exhaustive]
343pub struct CardPlacement {
344    /// The card's key.
345    pub key: u64,
346    /// Its region's key.
347    pub region: u64,
348    /// Its index in the input.
349    pub logical: usize,
350    /// Its rectangle, when placed: the slot less half the gap on each
351    /// side, or its size against the anchor ([`Card::size`]).
352    pub rect: Option<PointRect>,
353    /// Its whole slot, gap included, when placed.
354    pub slot: Option<PointRect>,
355    /// The form chosen.
356    pub form: usize,
357    /// The orientation chosen.
358    pub orientation: Orientation,
359    /// Placed or folded.
360    pub status: CardStatus,
361}
362
363/// Where a region went.
364#[derive(Clone, Debug, PartialEq)]
365#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
366#[non_exhaustive]
367pub struct RegionPlacement {
368    /// The region's key.
369    pub key: u64,
370    /// Its anchor.
371    pub anchor: Anchor,
372    /// Its side.
373    pub side: Side,
374    /// The room it had: its place less the gap, the depth, and the blocks
375    /// of the regions before it. `None` when none was left.
376    pub area: Option<PointRect>,
377    /// The extent of its placed cards, `None` when none is placed.
378    pub block: Option<PointRect>,
379    /// The slot engine's last layout of its cards, in the engine's frame
380    /// (transposed for a region flowing down), kept for hysteresis.
381    pub layout: Layout,
382}
383
384/// The cards laid out in their regions.
385#[derive(Clone, Debug, PartialEq)]
386#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
387#[non_exhaustive]
388pub struct RegionLayout {
389    /// One per region, in the order given.
390    pub regions: Vec<RegionPlacement>,
391    /// One per card, in the order given.
392    pub cards: Vec<CardPlacement>,
393}
394
395impl RegionLayout {
396    /// The placement of the card keyed `key`.
397    pub fn card(&self, key: u64) -> Option<&CardPlacement> {
398        self.cards.iter().find(|c| c.key == key)
399    }
400
401    /// The placement of the region keyed `key`.
402    pub fn region(&self, key: u64) -> Option<&RegionPlacement> {
403        self.regions.iter().find(|r| r.key == key)
404    }
405
406    /// The rectangles of the cards placed in the region keyed `region`,
407    /// with their keys, in the cards' order.
408    pub fn rects(&self, region: u64) -> Vec<(u64, PointRect)> {
409        self.cards
410            .iter()
411            .filter(|c| c.region == region)
412            .filter_map(|c| c.rect.map(|r| (c.key, r)))
413            .collect()
414    }
415
416    /// The keys of the cards not placed, in the cards' order.
417    pub fn folded(&self) -> Vec<u64> {
418        self.cards
419            .iter()
420            .filter(|c| !c.status.is_placed())
421            .map(|c| c.key)
422            .collect()
423    }
424
425    /// One line per region (its anchor, side, room and block), each
426    /// followed by its cards (their rectangle, or why they are not
427    /// placed), then the cards with no region.
428    pub fn dump(&self) -> String {
429        let mut out = String::new();
430        for r in &self.regions {
431            let _ = write!(out, "region {} {} {}", r.key, r.anchor, r.side);
432            match r.area {
433                Some(a) => {
434                    let _ = write!(out, " area {}", show(a));
435                }
436                None => out.push_str(" no-area"),
437            }
438            if let Some(b) = r.block {
439                let _ = write!(out, " block {}", show(b));
440            }
441            out.push('\n');
442            for c in self.cards.iter().filter(|c| c.region == r.key) {
443                card_line(&mut out, c);
444            }
445        }
446        for c in &self.cards {
447            if c.status == CardStatus::NoRegion {
448                card_line(&mut out, c);
449            }
450        }
451        out
452    }
453}
454
455fn card_line(out: &mut String, c: &CardPlacement) {
456    let _ = write!(out, "  card {}", c.key);
457    match (c.status, c.rect) {
458        (CardStatus::Placed, Some(r)) => {
459            let _ = write!(out, " at {}", show(r));
460        }
461        (s, _) => {
462            let _ = write!(out, " {s}");
463        }
464    }
465    out.push('\n');
466}
467
468/// `x,y wxh`, each to a tenth of a point, without trailing zeros.
469fn show(r: PointRect) -> String {
470    fn n(v: f32) -> String {
471        let t = (v * 10.0).round() / 10.0;
472        if t == t.trunc() {
473            format!("{}", t as i64)
474        } else {
475            format!("{t:.1}")
476        }
477    }
478    format!("{},{} {}x{}", n(r.x), n(r.y), n(r.w), n(r.h))
479}
480
481/// A place on one axis, logical (start, end) or physical (low, high).
482#[derive(Clone, Copy, Debug, PartialEq, Eq)]
483enum Place {
484    Start,
485    Mid,
486    End,
487}
488
489/// One axis of a rectangle: its low edge and length.
490#[derive(Clone, Copy, Debug)]
491struct Span {
492    lo: f32,
493    len: f32,
494}
495
496impl Span {
497    fn hi(self) -> f32 {
498        self.lo + self.len
499    }
500
501    /// From `lo` to `hi`, empty when reversed.
502    fn between(lo: f32, hi: f32) -> Span {
503        Span {
504            lo,
505            len: (hi - lo).max(0.0),
506        }
507    }
508
509    /// The point of the span at `place`.
510    fn at(self, place: Place) -> f32 {
511        match place {
512            Place::Start => self.lo,
513            Place::Mid => self.lo + self.len / 2.0,
514            Place::End => self.hi(),
515        }
516    }
517
518    /// Where a block `len` long starts in the span, at `place`, centred
519    /// on `centre` when in the middle, kept inside when it fits.
520    fn put(self, len: f32, place: Place, centre: f32) -> f32 {
521        match place {
522            Place::Start => self.lo,
523            Place::End => self.hi() - len,
524            Place::Mid => {
525                let lo = centre - len / 2.0;
526                if len >= self.len {
527                    self.lo + (self.len - len) / 2.0
528                } else {
529                    lo.clamp(self.lo, self.hi() - len)
530                }
531            }
532        }
533    }
534
535    /// At most `len` long, kept against `place` (around `centre` when in
536    /// the middle).
537    fn limit(self, len: f32, place: Place, centre: f32) -> Span {
538        if len >= self.len {
539            return self;
540        }
541        Span {
542            lo: self.put(len, place, centre),
543            len: len.max(0.0),
544        }
545    }
546}
547
548fn rect(x: Span, y: Span) -> PointRect {
549    PointRect {
550        x: x.lo,
551        y: y.lo,
552        w: x.len,
553        h: y.len,
554    }
555}
556
557fn spans(r: PointRect) -> (Span, Span) {
558    (
559        Span {
560            lo: r.x,
561            len: r.w.max(0.0),
562        },
563        Span {
564            lo: r.y,
565            len: r.h.max(0.0),
566        },
567    )
568}
569
570/// `r` grown by `d` on each side (shrunk when negative, to nothing at
571/// most).
572fn inflate(r: PointRect, d: f32) -> PointRect {
573    let w = (r.w + 2.0 * d).max(0.0);
574    let h = (r.h + 2.0 * d).max(0.0);
575    PointRect {
576        x: r.x + (r.w - w) / 2.0,
577        y: r.y + (r.h - h) / 2.0,
578        w,
579        h,
580    }
581}
582
583fn overlaps(a: PointRect, b: PointRect) -> bool {
584    a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h
585}
586
587/// The largest of the four cuts of `area` that leaves out `o` and keeps
588/// the point `p`; `None` when `o` covers or touches `p`.
589fn cut(area: PointRect, o: PointRect, p: (f32, f32)) -> Option<PointRect> {
590    if !overlaps(area, o) {
591        return Some(area);
592    }
593    let (x, y) = spans(area);
594    let mut best: Option<PointRect> = None;
595    let mut keep = |c: PointRect| {
596        if best.is_none_or(|b| c.w * c.h > b.w * b.h) {
597            best = Some(c);
598        }
599    };
600    if o.x >= p.0 {
601        keep(rect(Span::between(x.lo, o.x.min(x.hi())), y));
602    }
603    if o.x + o.w <= p.0 {
604        keep(rect(Span::between((o.x + o.w).max(x.lo), x.hi()), y));
605    }
606    if o.y >= p.1 {
607        keep(rect(x, Span::between(y.lo, o.y.min(y.hi()))));
608    }
609    if o.y + o.h <= p.1 {
610        keep(rect(x, Span::between((o.y + o.h).max(y.lo), y.hi())));
611    }
612    // A cut to nothing (an obstacle touching the point) leaves no room.
613    best.filter(|b| b.w > 0.0 && b.h > 0.0)
614}
615
616/// A region's room before the obstacles: its area, its physical place
617/// on each axis (where its block goes) and its anchor point.
618fn zone(surface: &Surface, region: &Region) -> (PointRect, (Place, Place), (f32, f32)) {
619    let (h, v) = region.anchor.places();
620    let flip = |p: Place| match p {
621        Place::Start => Place::End,
622        Place::End => Place::Start,
623        Place::Mid => Place::Mid,
624    };
625    let h = if surface.rtl { flip(h) } else { h };
626    let gap = region.gap.max(0.0);
627    let (sx, sy) = spans(surface.rect);
628    let (bx, by) = spans(surface.bounds);
629    let around =
630        region.side == Side::Around && !matches!(region.anchor, Anchor::Center | Anchor::Overlay);
631    if around {
632        // Per axis: before the surface, along it, or after it; a block
633        // before or after the surface lies against it.
634        let axis = |s: Span, b: Span, place: Place| match place {
635            Place::Start => (Span::between(b.lo, s.lo - gap), Place::End),
636            Place::Mid => (s, Place::Mid),
637            Place::End => (Span::between(s.hi() + gap, b.hi()), Place::Start),
638        };
639        let (x, ph) = axis(sx, bx, h);
640        let (y, pv) = axis(sy, by, v);
641        (rect(x, y), (ph, pv), (x.at(ph), y.at(pv)))
642    } else {
643        let area = inflate(surface.rect, -gap);
644        let (x, y) = spans(area);
645        (area, (h, v), (x.at(h), y.at(v)))
646    }
647}
648
649/// The slot holding `points` and the gap: an allowed size at least as
650/// large, a quarter of a unit at least.
651fn slot_size(points: f32, unit: f32) -> Size {
652    let t = if unit > 0.0 && points.is_finite() {
653        // `as` saturates and maps NaN to 0.
654        (points.max(0.0) * TWELFTHS_PER_UNIT as f32 / unit).ceil() as u32
655    } else {
656        0
657    };
658    let t = if t <= TWELFTHS_PER_UNIT {
659        [3, 4, 6, 8, 9, 12]
660            .into_iter()
661            .find(|&f| f >= t)
662            .unwrap_or(TWELFTHS_PER_UNIT)
663    } else {
664        t.div_ceil(TWELFTHS_PER_UNIT)
665            .saturating_mul(TWELFTHS_PER_UNIT)
666    };
667    Size::from_twelfths(t).unwrap_or(Size::ONE)
668}
669
670fn turned(o: Orientation) -> Orientation {
671    match o {
672        Orientation::Horizontal => Orientation::Vertical,
673        Orientation::Vertical => Orientation::Horizontal,
674    }
675}
676
677/// The element the engine lays out for `card` in a region with `gap`,
678/// turned when the region flows down (the engine fills rows).
679fn element_of(card: &Card, unit: f32, gap: f32, down: bool) -> Element {
680    let mut e = match card.size {
681        Some([w, h]) => {
682            let size = Size2::new(slot_size(w + gap, unit), slot_size(h + gap, unit));
683            let mut e = Element::new(card.element.key, SizePolicy::fixed(size));
684            e.pin = card.element.pin;
685            e
686        }
687        None => card.element.clone(),
688    };
689    if down {
690        if e.orientations.is_empty() {
691            e.orientations = vec![Orientation::Horizontal];
692        }
693        e.orientations = e.orientations.iter().map(|&o| turned(o)).collect();
694        e.pinned_orientation = e.pinned_orientation.map(turned);
695        if let Some(pin) = e.pin.as_mut() {
696            core::mem::swap(&mut pin.col, &mut pin.row);
697        }
698    }
699    e
700}
701
702/// Lays `cards` out in `regions` on and around `surface`.
703///
704/// Pass the previous result for the same regions as `previous` to keep
705/// each region's choices (column count, forms, orientations) while its
706/// room stays within half a unit of a threshold. The result has one
707/// placement per region and per card, in input order. This function
708/// never panics.
709///
710/// Regions go by priority, highest first (the first given on a tie):
711/// each takes the room at its anchor less the blocks of the regions
712/// before it (and the gap), cutting the side that keeps the most room. Its
713/// cards fill from its anchor outwards: in a corner the first card is in
714/// the corner, along a centred edge they go in reading order. Of two
715/// regions at one anchor, the second gets no room once the first placed a
716/// card: its cards fold.
717pub fn layout_regions(
718    surface: &Surface,
719    regions: &[Region],
720    cards: &[Card],
721    previous: Option<&RegionLayout>,
722) -> RegionLayout {
723    let unit = surface.unit;
724    let mut placements: Vec<CardPlacement> = cards
725        .iter()
726        .enumerate()
727        .map(|(i, c)| CardPlacement {
728            key: c.key(),
729            region: c.region,
730            logical: i,
731            rect: None,
732            slot: None,
733            form: 0,
734            orientation: Orientation::Horizontal,
735            status: CardStatus::NoRegion,
736        })
737        .collect();
738    let mut order: Vec<usize> = (0..regions.len()).collect();
739    order.sort_by_key(|&i| (core::cmp::Reverse(regions[i].priority), i));
740    let mut done: Vec<Option<RegionPlacement>> = vec![None; regions.len()];
741    let mut obstacles: Vec<PointRect> = Vec::new();
742    for i in order {
743        let region = &regions[i];
744        // A key declared twice: the first region has the cards.
745        let owner = regions.iter().position(|r| r.key == region.key) == Some(i);
746        let members: Vec<usize> = if owner {
747            (0..cards.len())
748                .filter(|&c| cards[c].region == region.key)
749                .collect()
750        } else {
751            Vec::new()
752        };
753        let gap = if region.gap.is_finite() {
754            region.gap.max(0.0)
755        } else {
756            0.0
757        };
758        let (mut area, (ph, pv), p) = zone(surface, region);
759        let overlay = region.anchor == Anchor::Overlay;
760        let mut room = true;
761        if !overlay {
762            for &o in &obstacles {
763                match cut(area, inflate(o, gap), p) {
764                    Some(a) => area = a,
765                    None => {
766                        room = false;
767                        break;
768                    }
769                }
770            }
771        }
772        let down = region.flow == Axis::Height;
773        if let Some(depth) = region.depth {
774            let (x, y) = spans(area);
775            area = if down {
776                rect(x.limit(depth, ph, p.0), y)
777            } else {
778                rect(x, y.limit(depth, pv, p.1))
779            };
780        }
781        // The engine's box: the room and half a gap around it, so the
782        // outer cards' edges, inset by half a gap, meet the room's.
783        let engine_box = inflate(area, gap / 2.0);
784        let (ew, eh) = if room {
785            (engine_box.w, engine_box.h)
786        } else {
787            (0.0, 0.0)
788        };
789        let (cw, ch) = if down { (eh, ew) } else { (ew, eh) };
790        let container = Container::new(cw, unit).with_height(ch);
791        let prev = previous
792            .and_then(|l| l.region(region.key))
793            .map(|r| &r.layout);
794        let elements: Vec<Element> = members
795            .iter()
796            .map(|&c| element_of(&cards[c], unit, gap, down))
797            .collect();
798        // Fold until the rest fit: first what even the whole room cannot
799        // hold, then the lowest priority.
800        let mut active: Vec<usize> = (0..members.len()).collect();
801        let mut folded: Vec<(usize, Reason)> = Vec::new();
802        if !room {
803            // The regions before it took its anchor.
804            folded = active.drain(..).map(|a| (a, Reason::NoRoom)).collect();
805        }
806        let result = loop {
807            let input: Vec<Element> = active.iter().map(|&a| elements[a].clone()).collect();
808            let l = layout(&container, &input, prev);
809            let mut hopeless = Vec::new();
810            let mut crowded = false;
811            for (at, pl) in l.placements.iter().enumerate() {
812                match pl.status {
813                    Status::Overflow(Reason::NoRoom) => crowded = true,
814                    Status::Overflow(r) => hopeless.push((active[at], r)),
815                    _ => {}
816                }
817            }
818            if !hopeless.is_empty() {
819                active.retain(|a| !hopeless.iter().any(|(h, _)| h == a));
820                folded.extend(hopeless);
821                continue;
822            }
823            if !crowded {
824                break l;
825            }
826            // The lowest priority, the last in order on a tie.
827            let Some(at) = (0..active.len())
828                .min_by_key(|&k| (cards[members[active[k]]].priority, core::cmp::Reverse(k)))
829            else {
830                break l;
831            };
832            folded.push((active.remove(at), Reason::NoRoom));
833        };
834        // Then each card folded for room, the highest priority first, comes
835        // back if it fits beside the others: a smaller card of a lower
836        // priority may fit where a larger one did not.
837        let mut result = result;
838        let mut retry: Vec<usize> = if room {
839            folded
840                .iter()
841                .filter(|(_, r)| *r == Reason::NoRoom)
842                .map(|&(m, _)| m)
843                .collect()
844        } else {
845            Vec::new()
846        };
847        retry.sort_by_key(|&m| (core::cmp::Reverse(cards[members[m]].priority), m));
848        for m in retry {
849            let mut trial = active.clone();
850            trial.push(m);
851            trial.sort_unstable();
852            let input: Vec<Element> = trial.iter().map(|&a| elements[a].clone()).collect();
853            let l = layout(&container, &input, prev);
854            if l.placements.iter().all(|p| p.status.is_placed()) {
855                active = trial;
856                result = l;
857                folded.retain(|&(f, _)| f != m);
858            }
859        }
860        // Back to the surface's frame: turned back, then the block put
861        // against its anchor.
862        let mut slots: Vec<(usize, PointRect, usize, Orientation)> = Vec::new();
863        for (at, pl) in result.placements.iter().enumerate() {
864            let Some(r) = pl.points else { continue };
865            let (r, o) = if down {
866                (
867                    PointRect {
868                        x: r.y,
869                        y: r.x,
870                        w: r.h,
871                        h: r.w,
872                    },
873                    turned(pl.orientation),
874                )
875            } else {
876                (r, pl.orientation)
877            };
878            slots.push((active[at], r, pl.form, o));
879        }
880        let bw = slots.iter().map(|s| s.1.x + s.1.w).fold(0.0, f32::max);
881        let bh = slots.iter().map(|s| s.1.y + s.1.h).fold(0.0, f32::max);
882        let (ex, ey) = spans(engine_box);
883        let ox = ex.put(bw, ph, p.0);
884        let oy = ey.put(bh, pv, p.1);
885        let mut block: Option<PointRect> = None;
886        for &(m, r, form, orientation) in &slots {
887            let x = match ph {
888                Place::End => bw - r.x - r.w,
889                Place::Mid if surface.rtl => bw - r.x - r.w,
890                _ => r.x,
891            };
892            let y = match pv {
893                Place::End => bh - r.y - r.h,
894                _ => r.y,
895            };
896            let slot = PointRect {
897                x: ox + x,
898                y: oy + y,
899                w: r.w,
900                h: r.h,
901            };
902            let inner = inflate(slot, -gap / 2.0);
903            let card = &cards[members[m]];
904            let shown = match card.size {
905                Some([w, h]) => {
906                    let (sx, sy) = spans(inner);
907                    let w = w.clamp(0.0, sx.len);
908                    let h = h.clamp(0.0, sy.len);
909                    rect(
910                        Span {
911                            lo: sx.put(w, ph, sx.at(Place::Mid)),
912                            len: w,
913                        },
914                        Span {
915                            lo: sy.put(h, pv, sy.at(Place::Mid)),
916                            len: h,
917                        },
918                    )
919                }
920                None => inner,
921            };
922            block = Some(match block {
923                None => inner,
924                Some(b) => {
925                    let x0 = b.x.min(inner.x);
926                    let y0 = b.y.min(inner.y);
927                    let x1 = (b.x + b.w).max(inner.x + inner.w);
928                    let y1 = (b.y + b.h).max(inner.y + inner.h);
929                    PointRect {
930                        x: x0,
931                        y: y0,
932                        w: x1 - x0,
933                        h: y1 - y0,
934                    }
935                }
936            });
937            let pl = &mut placements[members[m]];
938            pl.rect = Some(shown);
939            pl.slot = Some(slot);
940            pl.form = form;
941            pl.orientation = orientation;
942            pl.status = CardStatus::Placed;
943        }
944        for (m, reason) in folded {
945            let reason = match (down, reason) {
946                (true, Reason::TooNarrow) => Reason::TooShort,
947                (true, Reason::TooShort) => Reason::TooNarrow,
948                (_, r) => r,
949            };
950            let pl = &mut placements[members[m]];
951            pl.status = CardStatus::Folded(reason);
952        }
953        if let (Some(b), false) = (block, overlay) {
954            obstacles.push(b);
955        }
956        done[i] = Some(RegionPlacement {
957            key: region.key,
958            anchor: region.anchor,
959            side: region.side,
960            area: room.then_some(area),
961            block,
962            layout: result,
963        });
964    }
965    RegionLayout {
966        regions: done.into_iter().flatten().collect(),
967        cards: placements,
968    }
969}