1use 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
8const MAX_TWELFTHS: u32 = 10_000 * TWELFTHS_PER_UNIT;
10
11#[derive(Clone, Copy, Debug, PartialEq)]
13#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
14pub struct Container {
15 pub width: f32,
17 pub height: Option<f32>,
19 pub unit: f32,
21}
22
23impl Container {
24 pub const fn new(width: f32, unit: f32) -> Container {
27 Container {
28 width,
29 height: None,
30 unit,
31 }
32 }
33
34 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 (t.floor() as u32).min(MAX_TWELFTHS)
47 }
48}
49
50#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
52#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
53pub struct GridRect {
54 pub x: u32,
56 pub y: u32,
58 pub w: u32,
60 pub h: u32,
62}
63
64impl GridRect {
65 pub fn right(&self) -> u32 {
67 self.x + self.w
68 }
69
70 pub fn bottom(&self) -> u32 {
72 self.y + self.h
73 }
74
75 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#[derive(Clone, Copy, Debug, PartialEq)]
86#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
87pub struct PointRect {
88 pub x: f32,
90 pub y: f32,
92 pub w: f32,
94 pub h: f32,
96}
97
98#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
100#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
101pub enum Reason {
102 NoForms,
104 TooNarrow,
106 TooShort,
108 NoRoom,
110 PinOutOfBounds,
112 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
131#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
132pub enum Status {
133 Placed,
135 Unpinned(Reason),
137 Overflow(Reason),
139}
140
141impl Status {
142 pub fn is_placed(&self) -> bool {
144 !matches!(self, Status::Overflow(_))
145 }
146}
147
148#[derive(Clone, Copy, Debug, PartialEq)]
150#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
151pub struct Placement {
152 pub key: u64,
154 pub logical: usize,
157 pub visual: Option<usize>,
160 pub form: usize,
162 pub orientation: Orientation,
164 pub rect: Option<GridRect>,
166 pub points: Option<PointRect>,
168 pub status: Status,
170 pub group: Option<usize>,
173 pub band_top: u32,
177}
178
179#[derive(Clone, Debug, PartialEq)]
181#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
182pub struct Layout {
183 pub columns: u32,
185 pub rows: u32,
187 pub unit: f32,
189 pub placements: Vec<Placement>,
191 pub groups: Vec<GroupPlacement>,
193}
194
195impl Layout {
196 pub fn get(&self, key: u64) -> Option<&Placement> {
198 self.placements.iter().find(|p| p.key == key)
199 }
200
201 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 pub fn group(&self, key: u64) -> Option<&GroupPlacement> {
214 self.groups.iter().find(|g| g.key == key)
215 }
216
217 pub fn height_points(&self) -> f32 {
219 self.rows as f32 * self.unit / TWELFTHS_PER_UNIT as f32
220 }
221}
222
223#[derive(Clone, Copy)]
225struct Choice {
226 form: usize,
227 orientation: Orientation,
228 policy: SizePolicy,
229 w: u32,
230 h: u32,
231}
232
233pub fn layout(container: &Container, elements: &[Element], previous: Option<&Layout>) -> Layout {
247 layout_grouped(container, elements, &[], previous)
248}
249
250pub 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 let choices: Vec<Result<Choice, (Reason, usize, Orientation)>> = elements
272 .iter()
273 .map(|e| {
274 let prev = previous.and_then(|l| l.get(e.key));
277 choose(e, columns, natural, max_rows, prev)
278 })
279 .collect();
280
281 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 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 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
406fn 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
422fn 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 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 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
475fn 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
502fn 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#[derive(Clone)]
520struct Placed {
521 rects: Vec<Option<GridRect>>,
522 status: Vec<Status>,
523 member_of: Vec<Option<usize>>,
525 band_top: Vec<u32>,
527 group_rects: Vec<Option<GridRect>>,
529 body_top: Vec<u32>,
531}
532
533struct 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 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 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 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 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 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
672fn 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
704fn 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}