Skip to main content

egui_pop_fit/
layout.rs

1//! The engine: choosing forms and orientations, dense packing, growth.
2
3use crate::element::{Axis, Element, Grow, Orientation, SizePolicy};
4use crate::group::{Group, GroupPlacement, Node, tree};
5use crate::size::{HALF_UNIT, TWELFTHS_PER_UNIT, floor_step, is_allowed, next_step, prev_step};
6use core::fmt;
7
8/// The largest grid extent, in twelfths: ten thousand units.
9const MAX_TWELFTHS: u32 = 10_000 * TWELFTHS_PER_UNIT;
10
11/// The box to lay elements out in, in points.
12#[derive(Clone, Copy, Debug, PartialEq)]
13#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
14pub struct Container {
15    /// The width in points.
16    pub width: f32,
17    /// The height in points, or `None` for a container that grows down.
18    pub height: Option<f32>,
19    /// The base unit in points: one row, scaled by density.
20    pub unit: f32,
21}
22
23impl Container {
24    /// A container of `width` points that grows down, with a unit of `unit`
25    /// points.
26    pub const fn new(width: f32, unit: f32) -> Container {
27        Container {
28            width,
29            height: None,
30            unit,
31        }
32    }
33
34    /// The same container bounded to `height` points.
35    pub const fn with_height(mut self, height: f32) -> Container {
36        self.height = Some(height);
37        self
38    }
39
40    fn twelfths(&self, points: f32) -> u32 {
41        if !(self.unit.is_finite() && self.unit > 0.0) {
42            return 0;
43        }
44        let t = points * TWELFTHS_PER_UNIT as f32 / self.unit;
45        // `as` saturates and maps NaN to 0: a bad box gives an empty grid.
46        (t.floor() as u32).min(MAX_TWELFTHS)
47    }
48}
49
50/// A rectangle on the grid, in twelfths of the unit.
51#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
52#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
53pub struct GridRect {
54    /// Left edge.
55    pub x: u32,
56    /// Top edge.
57    pub y: u32,
58    /// Width.
59    pub w: u32,
60    /// Height.
61    pub h: u32,
62}
63
64impl GridRect {
65    /// The right edge.
66    pub fn right(&self) -> u32 {
67        self.x + self.w
68    }
69
70    /// The bottom edge.
71    pub fn bottom(&self) -> u32 {
72        self.y + self.h
73    }
74
75    /// Whether two rectangles share any area.
76    pub fn overlaps(&self, other: &GridRect) -> bool {
77        self.x < other.right()
78            && other.x < self.right()
79            && self.y < other.bottom()
80            && other.y < self.bottom()
81    }
82}
83
84/// A rectangle in points, relative to the container's top left.
85#[derive(Clone, Copy, Debug, PartialEq)]
86#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
87pub struct PointRect {
88    /// Left edge.
89    pub x: f32,
90    /// Top edge.
91    pub y: f32,
92    /// Width.
93    pub w: f32,
94    /// Height.
95    pub h: f32,
96}
97
98/// Why an element is not placed, or not where it was pinned.
99#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
100#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
101pub enum Reason {
102    /// The element declares no form.
103    NoForms,
104    /// Even its smallest form is wider than the container.
105    TooNarrow,
106    /// Even its smallest form is taller than the bounded container.
107    TooShort,
108    /// It fits the container's shape, but the bounded container is full.
109    NoRoom,
110    /// Its pin puts it outside the container.
111    PinOutOfBounds,
112    /// Its pin overlaps an element pinned before it.
113    PinOverlap,
114}
115
116impl fmt::Display for Reason {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        f.write_str(match self {
119            Reason::NoForms => "no-forms",
120            Reason::TooNarrow => "too-narrow",
121            Reason::TooShort => "too-short",
122            Reason::NoRoom => "no-room",
123            Reason::PinOutOfBounds => "pin-out-of-bounds",
124            Reason::PinOverlap => "pin-overlap",
125        })
126    }
127}
128
129/// The outcome for one element.
130#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
131#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
132pub enum Status {
133    /// Placed, at its pin if it has one.
134    Placed,
135    /// Placed by the flow because its pin could not be honoured.
136    Unpinned(Reason),
137    /// Not placed: the caller folds it or shows it elsewhere.
138    Overflow(Reason),
139}
140
141impl Status {
142    /// Whether the element has a rectangle.
143    pub fn is_placed(&self) -> bool {
144        !matches!(self, Status::Overflow(_))
145    }
146}
147
148/// The result for one element.
149#[derive(Clone, Copy, Debug, PartialEq)]
150#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
151pub struct Placement {
152    /// The element's key.
153    pub key: u64,
154    /// Its index in the input: the logical order (Tab, accessibility, device
155    /// banks).
156    pub logical: usize,
157    /// Its rank in reading order (top to bottom, then left to right), or
158    /// `None` when not placed.
159    pub visual: Option<usize>,
160    /// The chosen form's index. For an overflow, the last form tried.
161    pub form: usize,
162    /// The chosen orientation.
163    pub orientation: Orientation,
164    /// The slot, in twelfths, when placed.
165    pub rect: Option<GridRect>,
166    /// The slot, in points, when placed.
167    pub points: Option<PointRect>,
168    /// Placed or overflow, with a reason.
169    pub status: Status,
170    /// The index, in the layout's groups, of the innermost group holding
171    /// it (its header included).
172    pub group: Option<usize>,
173    /// The row, in twelfths, its pin counts from: the top of its band
174    /// (its group's members, below the header, or its run of loose
175    /// elements). Subtract it from a position to store it as a pin.
176    pub band_top: u32,
177}
178
179/// A laid-out container.
180#[derive(Clone, Debug, PartialEq)]
181#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
182pub struct Layout {
183    /// The grid's width in twelfths (its column count).
184    pub columns: u32,
185    /// The height used, in twelfths.
186    pub rows: u32,
187    /// The unit, in points, the layout was made with.
188    pub unit: f32,
189    /// One placement per element, in logical order.
190    pub placements: Vec<Placement>,
191    /// One per group, in the order given.
192    pub groups: Vec<GroupPlacement>,
193}
194
195impl Layout {
196    /// The placement of the element with this key.
197    pub fn get(&self, key: u64) -> Option<&Placement> {
198        self.placements.iter().find(|p| p.key == key)
199    }
200
201    /// The placed elements in visual order.
202    pub fn visual_order(&self) -> Vec<&Placement> {
203        let mut placed: Vec<&Placement> = self
204            .placements
205            .iter()
206            .filter(|p| p.visual.is_some())
207            .collect();
208        placed.sort_by_key(|p| p.visual);
209        placed
210    }
211
212    /// The placement of the group with this key.
213    pub fn group(&self, key: u64) -> Option<&GroupPlacement> {
214        self.groups.iter().find(|g| g.key == key)
215    }
216
217    /// The height used, in points.
218    pub fn height_points(&self) -> f32 {
219        self.rows as f32 * self.unit / TWELFTHS_PER_UNIT as f32
220    }
221}
222
223/// A form and orientation, with the slot size it gets.
224#[derive(Clone, Copy)]
225struct Choice {
226    form: usize,
227    orientation: Orientation,
228    policy: SizePolicy,
229    w: u32,
230    h: u32,
231}
232
233/// Lays `elements` out in `container`.
234///
235/// Pass the previous result of the same container as `previous` to keep its
236/// choices (column count, forms, orientations) while the box stays within
237/// half a unit of a threshold. The result has one placement per element, in
238/// input order. This function never panics.
239///
240/// Forms and orientations are chosen from the grid's shape (its width, and
241/// its height when bounded), not from the room other elements leave: in a
242/// full bounded container, an element may overflow in a form that would
243/// have fit in another orientation. Each growth step re-runs the dense
244/// placement, so the cost grows with the cube of the element count; the
245/// engine is meant for panels of tens of elements, not thousands.
246pub fn layout(container: &Container, elements: &[Element], previous: Option<&Layout>) -> Layout {
247    layout_grouped(container, elements, &[], previous)
248}
249
250/// Lays `elements` out in `container`, in `groups`.
251///
252/// As [`layout`], but packing is dense only within each [`Group`] and
253/// within each run of loose elements between groups: each starts on a
254/// new band of rows below everything before it. A group's header, if it
255/// has one, takes a band of its own at the group's top; pins count from
256/// the top of the element's band ([`Placement::band_top`]). Groups that
257/// reach past the elements or cross another group's boundary are ignored
258/// ([`GroupPlacement::ignored`]).
259pub fn layout_grouped(
260    container: &Container,
261    elements: &[Element],
262    groups: &[Group],
263    previous: Option<&Layout>,
264) -> Layout {
265    let unit = container.unit;
266    let natural = container.twelfths(container.width);
267    let columns = columns(natural, container.unit, previous);
268    let max_rows = container.height.map(|h| container.twelfths(h));
269
270    // 1. Choose a form and an orientation for each element.
271    let choices: Vec<Result<Choice, (Reason, usize, Orientation)>> = elements
272        .iter()
273        .map(|e| {
274            // An overflow's choice is kept too: dropping it would make the
275            // next layout of the same box differ.
276            let prev = previous.and_then(|l| l.get(e.key));
277            choose(e, columns, natural, max_rows, prev)
278        })
279        .collect();
280
281    // 2. Place: pins first, then the flow, densely.
282    let mut sizes: Vec<Option<(u32, u32)>> = choices
283        .iter()
284        .map(|c| c.as_ref().ok().map(|c| (c.w, c.h)))
285        .collect();
286    let (nodes, parents, ignored) = tree(elements.len(), groups);
287    let grid = Grid {
288        elements,
289        nodes: &nodes,
290        groups: groups.len(),
291        columns,
292        max_rows,
293    };
294    let mut placed = grid.place(&sizes);
295
296    // 3. Grow into the leftover room, one step per element per round. A step
297    // is kept when the dense placement at the new sizes changes no status and
298    // stays within the bounded height, or for a container growing down, the
299    // height used before growth.
300    let rows_of = |rects: &[Option<GridRect>]| {
301        rects
302            .iter()
303            .flatten()
304            .map(GridRect::bottom)
305            .max()
306            .unwrap_or(0)
307    };
308    let row_limit = max_rows.unwrap_or_else(|| rows_of(&placed.rects));
309    loop {
310        let mut grew = false;
311        for i in 0..elements.len() {
312            let (Ok(c), Some(size)) = (&choices[i], sizes[i]) else {
313                continue;
314            };
315            if !placed.status[i].is_placed() {
316                continue;
317            }
318            let Some(next) = grown(&c.policy, size, columns) else {
319                continue;
320            };
321            let mut tried = sizes.clone();
322            tried[i] = Some(next);
323            let p = grid.place(&tried);
324            if p.status == placed.status && rows_of(&p.rects) <= row_limit {
325                (sizes, placed, grew) = (tried, p, true);
326            }
327        }
328        if !grew {
329            break;
330        }
331    }
332    let Placed {
333        rects,
334        mut status,
335        member_of,
336        band_top,
337        group_rects,
338        body_top,
339    } = placed;
340    for (i, c) in choices.iter().enumerate() {
341        if let Err((reason, _, _)) = c {
342            status[i] = Status::Overflow(*reason);
343        }
344    }
345
346    // 4. Visual order and output.
347    let mut order: Vec<usize> = (0..elements.len())
348        .filter(|&i| rects[i].is_some())
349        .collect();
350    order.sort_by_key(|&i| rects[i].map(|r| (r.y, r.x, i)));
351    let mut visual = vec![None; elements.len()];
352    for (rank, &i) in order.iter().enumerate() {
353        visual[i] = Some(rank);
354    }
355    let to_points = |t: u32| t as f32 * unit / TWELFTHS_PER_UNIT as f32;
356    let to_rect = |r: GridRect| PointRect {
357        x: to_points(r.x),
358        y: to_points(r.y),
359        w: to_points(r.w),
360        h: to_points(r.h),
361    };
362    let placements = elements
363        .iter()
364        .enumerate()
365        .map(|(i, e)| {
366            let (form, orientation) = match &choices[i] {
367                Ok(c) => (c.form, c.orientation),
368                Err((_, f, o)) => (*f, *o),
369            };
370            let rect = rects[i];
371            Placement {
372                key: e.key,
373                logical: i,
374                visual: visual[i],
375                form,
376                orientation,
377                rect,
378                points: rect.map(to_rect),
379                status: status[i],
380                group: member_of[i],
381                band_top: band_top[i],
382            }
383        })
384        .collect();
385    let groups = groups
386        .iter()
387        .enumerate()
388        .map(|(g, group)| GroupPlacement {
389            key: group.key,
390            parent: parents[g],
391            rect: group_rects[g],
392            points: group_rects[g].map(to_rect),
393            body_top: body_top[g],
394            ignored: ignored[g],
395        })
396        .collect();
397    Layout {
398        columns,
399        rows: rows_of(&rects),
400        unit,
401        placements,
402        groups,
403    }
404}
405
406/// The grid width in twelfths. A wider grid than before waits until the box
407/// is half a unit wider than the previous one; a narrower one is taken at
408/// once, so the grid never exceeds the box.
409fn columns(natural: u32, unit: f32, previous: Option<&Layout>) -> u32 {
410    match previous {
411        Some(p) if p.unit == unit && natural > p.columns => {
412            if natural < p.columns.saturating_add(HALF_UNIT) {
413                p.columns
414            } else {
415                natural
416            }
417        }
418        _ => natural,
419    }
420}
421
422/// The first form and orientation that fits, keeping the previous one unless
423/// a better one fits with half a unit to spare in the box's natural width
424/// (not the grid's, which may lag behind it).
425fn choose(
426    e: &Element,
427    columns: u32,
428    natural: u32,
429    max_rows: Option<u32>,
430    prev: Option<&Placement>,
431) -> Result<Choice, (Reason, usize, Orientation)> {
432    let orientations = e.orientation_order();
433    let mut candidates = Vec::new();
434    for (form, policy) in e.forms.iter().enumerate() {
435        for &o in &orientations {
436            candidates.push((form, o, policy.resolved(o)));
437        }
438    }
439    let fits = |&(form, orientation, policy): &(usize, Orientation, SizePolicy), width: u32| {
440        fit(&policy, width, max_rows).map(|(w, h)| Choice {
441            form,
442            orientation,
443            policy,
444            w,
445            h,
446        })
447    };
448    let kept = prev.and_then(|p| {
449        let at = candidates
450            .iter()
451            .position(|c| c.0 == p.form && c.1 == p.orientation)?;
452        fits(&candidates[at], columns).ok().map(|c| (at, c))
453    });
454    if let Some((at, kept)) = kept {
455        let margin = natural.saturating_sub(HALF_UNIT);
456        // A better choice must fit with half a unit to spare; its slot is
457        // still sized at the real width.
458        let better = candidates[..at]
459            .iter()
460            .filter(|c| fits(c, margin.min(columns)).is_ok())
461            .find_map(|c| fits(c, columns).ok());
462        return Ok(better.unwrap_or(kept));
463    }
464    // Overflow reports the last form, in its first orientation.
465    let mut last = (Reason::NoForms, 0, orientations[0]);
466    for c in &candidates {
467        match fits(c, columns) {
468            Ok(choice) => return Ok(choice),
469            Err(reason) => last = (reason, c.0, orientations[0]),
470        }
471    }
472    Err(last)
473}
474
475/// The slot an oriented policy gets in a grid `width` twelfths wide: the
476/// largest allowed size up to its preferred size that fits.
477fn fit(p: &SizePolicy, width: u32, max_rows: Option<u32>) -> Result<(u32, u32), Reason> {
478    let (min_w, min_h) = (p.min_size.width.twelfths(), p.min_size.height.twelfths());
479    if min_w > width {
480        return Err(Reason::TooNarrow);
481    }
482    if max_rows.is_some_and(|m| min_h > m) {
483        return Err(Reason::TooShort);
484    }
485    let mut w = floor_step(p.size.width.twelfths().min(width)).ok_or(Reason::TooNarrow)?;
486    while w >= min_w {
487        if let Some(h) = height_for(p, w, max_rows) {
488            return Ok((w, h));
489        }
490        w = match prev_step(w) {
491            Some(w) => w,
492            None => break,
493        };
494    }
495    Err(if p.aspect_ratio.is_some() {
496        Reason::TooShort
497    } else {
498        Reason::TooNarrow
499    })
500}
501
502/// The height an oriented policy takes at width `w`.
503fn height_for(p: &SizePolicy, w: u32, max_rows: Option<u32>) -> Option<u32> {
504    let (min_h, max_h) = (p.min_size.height.twelfths(), p.max_size.height.twelfths());
505    let cap = max_rows.unwrap_or(u32::MAX);
506    match p.aspect_ratio {
507        Some(r) => {
508            let num = w.checked_mul(r.height)?;
509            let h = num / r.width;
510            let ok =
511                num % r.width == 0 && is_allowed(h) && (min_h..=max_h).contains(&h) && h <= cap;
512            ok.then_some(h)
513        }
514        None => floor_step(p.size.height.twelfths().min(cap)).filter(|&h| h >= min_h),
515    }
516}
517
518/// What one placement pass gives.
519#[derive(Clone)]
520struct Placed {
521    rects: Vec<Option<GridRect>>,
522    status: Vec<Status>,
523    /// Each element's innermost group.
524    member_of: Vec<Option<usize>>,
525    /// Each element's band top, its pin's origin.
526    band_top: Vec<u32>,
527    /// Each group's band, when something of it is placed.
528    group_rects: Vec<Option<GridRect>>,
529    /// Each group's members' top.
530    body_top: Vec<u32>,
531}
532
533/// The grid and the element tree a placement pass works on.
534struct Grid<'a> {
535    elements: &'a [Element],
536    nodes: &'a [Node],
537    groups: usize,
538    columns: u32,
539    max_rows: Option<u32>,
540}
541
542impl Grid<'_> {
543    /// Places slots of the given sizes, band by band: each run of loose
544    /// elements and each group in turn, below the one before. Elements
545    /// without a size are left out with a placeholder status, which the
546    /// caller replaces.
547    fn place(&self, sizes: &[Option<(u32, u32)>]) -> Placed {
548        let n = self.elements.len();
549        let mut out = Placed {
550            rects: vec![None; n],
551            status: vec![Status::Placed; n],
552            member_of: vec![None; n],
553            band_top: vec![0; n],
554            group_rects: vec![None; self.groups],
555            body_top: vec![0; self.groups],
556        };
557        self.block(self.nodes, None, 0, sizes, &mut out);
558        out
559    }
560
561    /// Places a block of nodes from row `top` down; returns its bottom.
562    fn block(
563        &self,
564        nodes: &[Node],
565        group: Option<usize>,
566        top: u32,
567        sizes: &[Option<(u32, u32)>],
568        out: &mut Placed,
569    ) -> u32 {
570        let mut y = top;
571        let mut run = Vec::new();
572        for node in nodes {
573            match node {
574                Node::Element(i) => run.push(*i),
575                Node::Group {
576                    index,
577                    header,
578                    children,
579                } => {
580                    y = self.run(&run, group, y, sizes, out);
581                    run.clear();
582                    let start = y;
583                    if let Some(h) = header {
584                        y = self.run(&[*h], Some(*index), y, sizes, out);
585                    }
586                    out.body_top[*index] = y;
587                    y = self.block(children, Some(*index), y, sizes, out);
588                    if y > start {
589                        out.group_rects[*index] = Some(GridRect {
590                            x: 0,
591                            y: start,
592                            w: self.columns,
593                            h: y - start,
594                        });
595                    }
596                }
597            }
598        }
599        self.run(&run, group, y, sizes, out)
600    }
601
602    /// Places a run of elements densely in a band from row `top`: pinned
603    /// ones at their pins (counted from `top`), in logical order, then the
604    /// others at the first free position in reading order. Returns the
605    /// band's bottom.
606    fn run(
607        &self,
608        run: &[usize],
609        group: Option<usize>,
610        top: u32,
611        sizes: &[Option<(u32, u32)>],
612        out: &mut Placed,
613    ) -> u32 {
614        // The room left below `top`, in the band's own rows.
615        let max_rows = self.max_rows.map(|m| m.saturating_sub(top));
616        let mut taken: Vec<GridRect> = Vec::new();
617        for &i in run {
618            out.member_of[i] = group;
619            out.band_top[i] = top;
620            let (Some((w, h)), Some(pin)) = (sizes[i], self.elements[i].pin) else {
621                continue;
622            };
623            let r = GridRect {
624                x: pin.col,
625                y: pin.row,
626                w,
627                h,
628            };
629            let inside = r
630                .x
631                .checked_add(w)
632                .is_some_and(|right| right <= self.columns)
633                && r.y
634                    .checked_add(h)
635                    .and_then(|b| b.checked_add(top))
636                    .is_some_and(|b| b <= MAX_TWELFTHS && max_rows.is_none_or(|m| b - top <= m));
637            if !inside {
638                out.status[i] = Status::Unpinned(Reason::PinOutOfBounds);
639            } else if taken.iter().any(|t| t.overlaps(&r)) {
640                out.status[i] = Status::Unpinned(Reason::PinOverlap);
641            } else {
642                out.rects[i] = Some(r);
643                taken.push(r);
644            }
645        }
646        for &i in run {
647            let Some((w, h)) = sizes[i] else {
648                out.status[i] = Status::Overflow(Reason::NoForms);
649                continue;
650            };
651            if out.rects[i].is_some() {
652                continue;
653            }
654            match first_fit(&taken, w, h, self.columns, max_rows) {
655                Some(r) => {
656                    out.rects[i] = Some(r);
657                    taken.push(r);
658                }
659                None => out.status[i] = Status::Overflow(Reason::NoRoom),
660            }
661        }
662        // From the band's rows to the grid's.
663        for &i in run {
664            if let Some(r) = &mut out.rects[i] {
665                r.y = r.y.saturating_add(top);
666            }
667        }
668        top.saturating_add(taken.iter().map(GridRect::bottom).max().unwrap_or(0))
669    }
670}
671
672/// The size one growth step larger, if the policy allows it and it is no
673/// wider than the grid.
674fn grown(p: &SizePolicy, (w, h): (u32, u32), columns: u32) -> Option<(u32, u32)> {
675    let Grow::Along(axis) = p.grow else {
676        return None;
677    };
678    let (mut w, mut h) = (w, h);
679    match axis {
680        Axis::Width => w = next_step(w)?,
681        Axis::Height => h = next_step(h)?,
682    }
683    if let Some(ratio) = p.aspect_ratio {
684        match axis {
685            Axis::Width => {
686                let num = w.checked_mul(ratio.height)?;
687                (num % ratio.width == 0).then_some(())?;
688                h = num / ratio.width;
689            }
690            Axis::Height => {
691                let num = h.checked_mul(ratio.width)?;
692                (num % ratio.height == 0).then_some(())?;
693                w = num / ratio.height;
694            }
695        }
696        if !is_allowed(w) || !is_allowed(h) {
697            return None;
698        }
699    }
700    let within = w <= p.max_size.width.twelfths() && h <= p.max_size.height.twelfths();
701    (within && w <= columns).then_some((w, h))
702}
703
704/// The first free position in reading order for a `w` by `h` slot.
705///
706/// The top-most, then left-most, free position always has its top at 0 or at
707/// a slot's bottom, and its left at 0 or at a slot's right, so only those are
708/// tried.
709fn first_fit(
710    taken: &[GridRect],
711    w: u32,
712    h: u32,
713    columns: u32,
714    max_rows: Option<u32>,
715) -> Option<GridRect> {
716    if w > columns {
717        return None;
718    }
719    let mut ys: Vec<u32> = taken.iter().map(GridRect::bottom).chain([0]).collect();
720    let mut xs: Vec<u32> = taken.iter().map(GridRect::right).chain([0]).collect();
721    ys.sort_unstable();
722    ys.dedup();
723    xs.sort_unstable();
724    xs.dedup();
725    for &y in &ys {
726        if max_rows.is_some_and(|m| y.saturating_add(h) > m) {
727            break;
728        }
729        for &x in &xs {
730            if x + w > columns {
731                break;
732            }
733            let r = GridRect { x, y, w, h };
734            if !taken.iter().any(|t| t.overlaps(&r)) {
735                return Some(r);
736            }
737        }
738    }
739    None
740}