1use std::rc::Rc;
9
10day_reactive::tls_slots! {
11 layout;
12 static REPORTED: std::cell::RefCell<std::collections::HashSet<RNode>> =
15 std::cell::RefCell::new(std::collections::HashSet::new());
16}
17
18use day_spec::*;
19
20use crate::tree::{Flex, RNode, Tree, TreeOps};
21
22pub trait Layout: 'static {
25 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size;
26 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect);
27 fn baseline(&self, _cx: &mut dyn LayoutOps, _children: &[RNode], _size: Size) -> Option<f64> {
35 None
36 }
37}
38
39pub trait LayoutOps {
41 fn measure_child(&mut self, child: RNode, p: Proposal) -> Size;
42 fn place_child(&mut self, child: RNode, rect: Rect);
43 fn place_child_native(&mut self, child: RNode, rect: Rect) {
46 self.place_child(child, rect);
47 }
48 fn flex_of(&self, child: RNode) -> Flex;
49 fn children_of(&self, node: RNode) -> Vec<RNode>;
50 fn measure_leaf(&mut self, p: Proposal) -> Size;
52 fn baseline_of(&mut self, child: RNode, size: Size) -> Option<f64>;
56 fn set_scroll_content(&mut self, content: Size);
59 fn scroll_bar_inset(&mut self, _vertical: bool) -> f64 {
62 0.0
63 }
64 fn report_overflow(&mut self, _needed: f64, _available: f64) {}
70}
71
72pub struct EngineCx<'a, B: Toolkit> {
73 pub(crate) tree: &'a mut Tree<B>,
74 pub(crate) offset: Point,
75 pub(crate) current: RNode,
76 pub(crate) parent_size: Size,
78 pub(crate) direction: day_geometry::LayoutDirection,
81}
82
83impl<B: Toolkit> LayoutOps for EngineCx<'_, B> {
84 fn measure_child(&mut self, child: RNode, p: Proposal) -> Size {
85 measure_node(self.tree, child, p)
86 }
87 fn place_child(&mut self, child: RNode, rect: Rect) {
88 let rect = if self.direction == day_geometry::LayoutDirection::Rtl {
96 Rect::new(
97 self.parent_size.width - rect.origin.x - rect.size.width,
98 rect.origin.y,
99 rect.size.width,
100 rect.size.height,
101 )
102 } else {
103 rect
104 };
105 place_node(self.tree, child, rect, self.offset, false);
106 }
107 fn place_child_native(&mut self, child: RNode, rect: Rect) {
108 place_node(self.tree, child, rect, self.offset, false);
109 }
110 fn flex_of(&self, child: RNode) -> Flex {
111 self.tree.node(child).map_or_default(|n| n.flex)
112 }
113 fn children_of(&self, node: RNode) -> Vec<RNode> {
114 self.tree.node(node).map_or_default(|n| n.children.clone())
115 }
116 fn measure_leaf(&mut self, p: Proposal) -> Size {
117 let Some(n) = self.tree.node(self.current) else {
118 return Size::ZERO;
119 };
120 let kind = n.kind;
121 let Some(h) = n.handle.clone() else {
122 return Size::ZERO;
123 };
124 self.tree.toolkit.measure(&h, kind, p)
125 }
126 fn baseline_of(&mut self, child: RNode, size: Size) -> Option<f64> {
127 baseline_node(self.tree, child, size)
128 }
129 fn set_scroll_content(&mut self, content: Size) {
130 self.parent_size = content;
133 let current = self.current;
134 let Some(n) = self.tree.node_mut(current) else {
135 return;
136 };
137 let viewport = n.last_native_frame.map_or(Size::ZERO, |f| f.size);
141 let overflows = |c: Size| c.width > viewport.width + 0.5;
142 let to_leading = self.direction == day_geometry::LayoutDirection::Rtl
143 && viewport.width > 0.0
144 && overflows(content)
145 && !n.scroll_content.is_some_and(overflows);
146 n.scroll_content = Some(content);
148 let Some(h) = n.handle.clone() else { return };
149 self.tree.toolkit.set_scroll_content(&h, content);
150 if to_leading {
151 let edge = Rect::new((content.width - 1.0).max(0.0), 0.0, 1.0, 1.0);
152 self.tree.toolkit.scroll_to(&h, edge, false);
153 }
154 }
155 fn scroll_bar_inset(&mut self, vertical: bool) -> f64 {
156 let Some(h) = self.tree.node(self.current).and_then(|n| n.handle.clone()) else {
157 return 0.0;
158 };
159 self.tree.toolkit.scroll_bar_inset(&h, vertical).max(0.0)
160 }
161
162 #[cfg(debug_assertions)]
163 fn report_overflow(&mut self, needed: f64, available: f64) {
164 if REPORTED.with(|r| !r.borrow_mut().insert(self.current)) {
168 return;
169 }
170 let mut ids: Vec<String> = Vec::new();
175 let mut stack = vec![self.current];
176 while let Some(node) = stack.pop() {
177 if ids.len() >= 6 {
178 break;
179 }
180 if let Some(n) = self.tree.node(node) {
181 ids.extend(n.id.clone());
182 stack.extend(n.children.iter().rev());
183 }
184 }
185 let who = if ids.is_empty() {
186 String::from("no .id in reach")
187 } else {
188 ids.join(", ")
189 };
190 log::warn!(
191 "day layout: children overflow their container by {:.0}pt ({needed:.0} needed, \
192 {available:.0} available; {who}) — give the row a fit policy: \
193 .fit(RowFit::Wrap/Scroll) or adaptive(..) (docs/size-classes.md)",
194 needed - available,
195 );
196 }
197}
198
199pub(crate) fn measure_node<B: Toolkit>(tree: &mut Tree<B>, node: RNode, p: Proposal) -> Size {
200 let key = p.cache_key();
201 let (layout, children) = {
202 let Some(n) = tree.node(node) else {
203 return Size::ZERO;
204 };
205 if !n.needs_measure
206 && let Some(&(_, s)) = n.cache.iter().find(|(k, _)| *k == key)
207 {
208 return s;
209 }
210 (n.layout.clone(), n.children.clone())
211 };
212 let mut cx = EngineCx {
213 tree,
214 offset: Point::ZERO,
215 current: node,
216 parent_size: Size::ZERO, direction: crate::layout_direction(),
218 };
219 let size = layout.measure(&mut cx, &children, p);
220 if let Some(n) = tree.node_mut(node) {
221 n.needs_measure = false;
222 if n.cache.len() >= 4 {
223 n.cache.clear();
224 }
225 n.cache.push((key, size));
226 }
227 size
228}
229
230pub(crate) fn baseline_node<B: Toolkit>(
236 tree: &mut Tree<B>,
237 node: RNode,
238 size: Size,
239) -> Option<f64> {
240 let key = Proposal::exact(size).cache_key();
241 let (layout, children, handle, kind) = {
242 let n = tree.node(node)?;
243 if !n.needs_measure
244 && let Some((k, b)) = n.baseline_cache
245 && k == key
246 {
247 return b;
248 }
249 (
250 n.layout.clone(),
251 n.children.clone(),
252 n.handle.clone(),
253 n.kind,
254 )
255 };
256 let baseline = match handle {
258 Some(h) if children.is_empty() => tree.toolkit.first_baseline(&h, kind, size),
259 _ => {
260 let mut cx = EngineCx {
261 tree,
262 offset: Point::ZERO,
263 current: node,
264 parent_size: Size::ZERO,
265 direction: crate::layout_direction(),
266 };
267 layout.baseline(&mut cx, &children, size)
268 }
269 };
270 if let Some(n) = tree.node_mut(node) {
271 n.baseline_cache = Some((key, baseline));
272 }
273 baseline
274}
275
276thread_local! {
277 static FRAME_REPORTS: std::cell::RefCell<std::collections::HashSet<RNode>> =
280 std::cell::RefCell::new(std::collections::HashSet::new());
281}
282
283pub fn report_frames(node: RNode) {
287 FRAME_REPORTS.with(|r| r.borrow_mut().insert(node));
288}
289
290pub fn stop_frame_reports(node: RNode) {
292 let _ = FRAME_REPORTS.try_with(|r| r.borrow_mut().remove(&node));
293}
294
295pub type FramePatch = std::rc::Rc<dyn Fn(Size) -> Option<Box<dyn std::any::Any>>>;
299
300thread_local! {
301 static FRAME_PATCHES: std::cell::RefCell<std::collections::HashMap<RNode, FramePatch>> =
303 std::cell::RefCell::new(std::collections::HashMap::new());
304}
305
306pub fn patch_on_frame(node: RNode, patch: FramePatch) {
312 FRAME_PATCHES.with(|p| p.borrow_mut().insert(node, patch));
313}
314
315pub fn stop_frame_patches(node: RNode) {
317 let _ = FRAME_PATCHES.try_with(|p| p.borrow_mut().remove(&node));
318}
319
320pub(crate) fn place_node<B: Toolkit>(
323 tree: &mut Tree<B>,
324 node: RNode,
325 rect: Rect,
326 offset: Point,
327 is_root: bool,
328) {
329 let abs = Rect {
330 origin: rect.origin.offset(offset.x, offset.y),
331 size: rect.size,
332 };
333 let (layout, children, has_handle) = {
334 let Some(n) = tree.node(node) else { return };
335 (n.layout.clone(), n.children.clone(), n.handle.is_some())
336 };
337 let native_frame = tree
345 .node(node)
346 .is_some_and(|n| n.kind == day_spec::kinds::COVER);
347 let child_offset = if has_handle {
348 if !is_root && !native_frame {
349 let changed = tree
350 .node(node)
351 .is_some_and(|n| n.last_native_frame.is_none_or(|f| !f.approx_eq(&abs, 0.25)));
352 if changed {
353 let h = tree.node(node).and_then(|n| n.handle.clone());
354 if let Some(h) = h {
355 let anim = tree.resolve_anim(node);
356 tree.toolkit.set_frame(&h, abs, anim.as_ref());
357 let patch = FRAME_PATCHES
358 .with(|p| p.borrow().get(&node).cloned())
359 .and_then(|f| f(abs.size));
360 if let (Some(patch), Some(kind)) = (patch, tree.node(node).map(|n| n.kind)) {
361 tree.toolkit.update(&h, kind, patch.as_ref(), anim.as_ref());
362 }
363 }
364 if tree
365 .node(node)
366 .is_some_and(|n| n.kind == day_spec::kinds::CANVAS)
367 || FRAME_REPORTS.with(|r| r.borrow().contains(&node))
368 {
369 crate::tree::enqueue_event(
371 crate::tree::rnode_to_id(node),
372 day_spec::Event::FrameChanged(abs.size),
373 );
374 }
375 }
376 }
377 Point::ZERO
378 } else {
379 abs.origin
380 };
381 let (is_list, old_frame) = tree.node(node).map_or((false, None), |n| {
388 (n.kind == day_spec::kinds::LIST, n.last_native_frame)
389 });
390 let fills = is_list
393 && old_frame.is_none_or(|f| (f.size.height - abs.size.height).abs() > 0.25)
394 && tree
395 .list_driver(node)
396 .is_some_and(|d| d.supplements.empty.is_some());
397 let relayout_cells = is_list
398 && (fills || old_frame.is_some_and(|f| (f.size.width - abs.size.width).abs() > 0.25));
399 if let Some(n) = tree.node_mut(node) {
400 n.last_native_frame = Some(abs);
401 n.needs_layout = false;
402 }
403 if relayout_cells {
404 for key in tree.list_cell_keys(node) {
405 tree.list_layout_cell(node, key);
406 }
407 }
408 let direction = tree.sync_direction(node);
411 let mut cx = EngineCx {
412 tree,
413 offset: child_offset,
414 current: node,
415 parent_size: rect.size,
416 direction,
417 };
418 layout.place(&mut cx, &children, Rect::from_size(rect.size));
419}
420
421fn wrapper_baseline(
434 cx: &mut dyn LayoutOps,
435 children: &[RNode],
436 child_size: Size,
437 dy: f64,
438) -> Option<f64> {
439 let &c = children.first()?;
440 Some(cx.baseline_of(c, child_size)? + dy)
441}
442
443pub struct PassThrough;
445
446impl Layout for PassThrough {
447 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
448 match children.first() {
449 Some(&c) => cx.measure_child(c, p),
450 None => Size::ZERO,
451 }
452 }
453 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
454 if let Some(&c) = children.first() {
455 let s = cx.measure_child(c, Proposal::exact(bounds.size));
456 cx.place_child(c, Rect::from_size(s));
457 }
458 }
459}
460
461pub struct CellCenter;
466
467impl Layout for CellCenter {
468 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
469 match children.first() {
470 Some(&c) => cx.measure_child(c, p),
471 None => Size::ZERO,
472 }
473 }
474 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
475 if let Some(&c) = children.first() {
476 let s = cx.measure_child(c, Proposal::exact(bounds.size));
477 let y = ((bounds.size.height - s.height) / 2.0).max(0.0);
478 cx.place_child(
479 c,
480 Rect::new(0.0, y, s.width, s.height.min(bounds.size.height)),
481 );
482 }
483 }
484 fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
485 PassThrough::forward(cx, children, size)
486 }
487}
488
489pub struct CellMetrics(pub day_spec::RowMetrics);
493
494impl CellMetrics {
495 fn for_child(&self, cx: &dyn LayoutOps, child: RNode) -> day_spec::RowMetrics {
498 let mut node = child;
500 for _ in 0..8 {
501 if cx.flex_of(node).whole_row {
502 let i = self.0.insets;
503 return day_spec::RowMetrics {
504 insets: day_spec::Insets {
505 top: 0.0,
506 leading: i.leading,
507 bottom: 0.0,
508 trailing: i.trailing,
509 },
510 min_height: 0.0,
511 };
512 }
513 match cx.children_of(node)[..] {
514 [only] => node = only,
515 _ => break,
516 }
517 }
518 self.0
519 }
520}
521
522impl Layout for CellMetrics {
523 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
524 let Some(&c) = children.first() else {
525 return Size::ZERO;
526 };
527 let m = self.for_child(cx, c);
528 let i = m.insets;
529 let (dx, dy) = (i.leading + i.trailing, i.top + i.bottom);
530 let s = cx.measure_child(
531 c,
532 Proposal::new(
533 p.width.map(|w| (w - dx).max(0.0)),
534 p.height.map(|h| (h - dy).max(0.0)),
535 ),
536 );
537 Size::new(s.width + dx, (s.height + dy).max(m.min_height))
538 }
539 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
540 let Some(&c) = children.first() else {
541 return;
542 };
543 let i = self.for_child(cx, c).insets;
544 let inner = Size::new(
545 (bounds.size.width - i.leading - i.trailing).max(0.0),
546 (bounds.size.height - i.top - i.bottom).max(0.0),
547 );
548 let s = cx.measure_child(c, Proposal::new(Some(inner.width), None));
549 let (y, h) = if s.height <= inner.height {
552 (i.top + (inner.height - s.height) / 2.0, s.height)
553 } else {
554 let h = s.height.min(bounds.size.height);
555 (((bounds.size.height - h) / 2.0).max(0.0), h)
556 };
557 cx.place_child(c, Rect::new(i.leading, y, inner.width, h));
558 }
559 fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
560 PassThrough::forward(cx, children, size)
561 }
562}
563
564impl PassThrough {
565 fn forward(cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
567 let &c = children.first()?;
568 let cs = cx.measure_child(c, Proposal::exact(size));
569 wrapper_baseline(cx, children, cs, 0.0)
570 }
571}
572
573pub struct FillThrough;
580
581impl Layout for FillThrough {
582 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
583 match children.first() {
584 Some(&c) => cx.measure_child(c, p),
585 None => Size::ZERO,
586 }
587 }
588 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
589 if let Some(&c) = children.first() {
590 cx.place_child(c, Rect::from_size(bounds.size));
591 }
592 }
593 fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
594 wrapper_baseline(cx, children, size, 0.0)
595 }
596}
597
598pub struct LeafLayout;
600
601impl Layout for LeafLayout {
602 fn measure(&self, cx: &mut dyn LayoutOps, _children: &[RNode], p: Proposal) -> Size {
603 cx.measure_leaf(p)
604 }
605 fn place(&self, _cx: &mut dyn LayoutOps, _children: &[RNode], _bounds: Rect) {}
606}
607
608#[derive(Clone, Copy, PartialEq, Eq)]
609pub enum Axis {
610 Vertical,
611 Horizontal,
612}
613
614#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
615pub enum CrossAlign {
616 Leading,
617 #[default]
618 Center,
619 Trailing,
620 FirstBaseline,
625}
626
627impl CrossAlign {
628 fn fraction(self) -> f64 {
630 match self {
631 CrossAlign::Leading => 0.0,
632 CrossAlign::Center | CrossAlign::FirstBaseline => 0.5,
635 CrossAlign::Trailing => 1.0,
636 }
637 }
638}
639
640pub struct StackLayout {
643 pub axis: Axis,
644 pub spacing: f64,
645 pub align: CrossAlign,
646}
647
648impl StackLayout {
649 fn main(&self, s: Size) -> f64 {
650 match self.axis {
651 Axis::Vertical => s.height,
652 Axis::Horizontal => s.width,
653 }
654 }
655 fn cross(&self, s: Size) -> f64 {
656 match self.axis {
657 Axis::Vertical => s.width,
658 Axis::Horizontal => s.height,
659 }
660 }
661 fn mk(&self, main: f64, cross: f64) -> Size {
662 match self.axis {
663 Axis::Vertical => Size::new(cross, main),
664 Axis::Horizontal => Size::new(main, cross),
665 }
666 }
667 fn split(&self, p: Proposal) -> (Option<f64>, Option<f64>) {
668 match self.axis {
669 Axis::Vertical => (p.height, p.width),
670 Axis::Horizontal => (p.width, p.height),
671 }
672 }
673 fn proposal(&self, main: Option<f64>, cross: Option<f64>) -> Proposal {
674 match self.axis {
675 Axis::Vertical => Proposal::new(cross, main),
676 Axis::Horizontal => Proposal::new(main, cross),
677 }
678 }
679 fn grows_main(&self, f: Flex) -> bool {
680 f.is_spacer
681 || match self.axis {
682 Axis::Vertical => f.grow_h,
683 Axis::Horizontal => f.grow_w,
684 }
685 }
686 fn yields_main(&self, f: Flex) -> bool {
689 self.axis == Axis::Vertical && f.yields_h && !self.grows_main(f)
690 }
691 fn grows_cross(&self, f: Flex) -> bool {
692 match self.axis {
693 Axis::Vertical => f.grow_w,
694 Axis::Horizontal => f.grow_h,
695 }
696 }
697
698 fn flatten(cx: &mut dyn LayoutOps, children: &[RNode], out: &mut Vec<RNode>) {
699 for &c in children {
700 if cx.flex_of(c).is_group {
701 let inner = cx.children_of(c);
702 Self::flatten(cx, &inner, out);
703 } else {
704 out.push(c);
705 }
706 }
707 }
708
709 fn negotiate(&self, cx: &mut dyn LayoutOps, kids: &[RNode], p: Proposal) -> Vec<Size> {
710 let (main_p, cross_p) = self.split(p);
711 let mut sizes = vec![Size::ZERO; kids.len()];
712 let mut flex_idx = Vec::new();
713 let mut yield_idx = Vec::new();
714 let mut rigid_main = 0.0;
715 for (i, &k) in kids.iter().enumerate() {
716 let f = cx.flex_of(k);
717 if self.grows_main(f) {
718 flex_idx.push(i);
719 } else if self.yields_main(f) {
720 yield_idx.push(i);
721 } else {
722 let s = cx.measure_child(k, self.proposal(None, cross_p));
723 rigid_main += self.main(s);
724 sizes[i] = s;
725 }
726 }
727 if let Some(mp) = main_p {
734 let spacing_total = self.spacing * (kids.len().saturating_sub(1)) as f64;
735 let available = (mp - spacing_total).max(0.0);
736 if rigid_main > available {
737 let mut budget = available;
738 rigid_main = 0.0;
739 for (i, &k) in kids.iter().enumerate() {
740 let f = cx.flex_of(k);
741 if self.grows_main(f) || self.yields_main(f) {
742 continue;
743 }
744 if self.main(sizes[i]) > budget {
745 sizes[i] = cx.measure_child(k, self.proposal(Some(budget), cross_p));
746 }
747 let m = self.main(sizes[i]);
748 rigid_main += m;
749 budget = (budget - m).max(0.0);
750 }
751 }
752 }
753 for &i in &yield_idx {
756 let spacing_total = self.spacing * (kids.len().saturating_sub(1)) as f64;
757 let left = main_p.map(|mp| (mp - rigid_main - spacing_total).max(0.0));
758 sizes[i] = cx.measure_child(kids[i], self.proposal(left, cross_p));
759 rigid_main += self.main(sizes[i]);
760 }
761 if !flex_idx.is_empty() {
762 let spacing_total = self.spacing * (kids.len().saturating_sub(1)) as f64;
763 match main_p {
764 Some(mp) => {
765 let remaining = (mp - rigid_main - spacing_total).max(0.0);
766 let total: f64 = flex_idx.iter().map(|&i| cx.flex_of(kids[i]).weight()).sum();
769 for &i in &flex_idx {
770 let f = cx.flex_of(kids[i]);
771 let share = remaining * f.weight() / total;
772 sizes[i] = if f.is_spacer {
773 self.mk(share, 0.0)
774 } else {
775 cx.measure_child(kids[i], self.proposal(Some(share), cross_p))
776 };
777 }
778 }
779 None => {
780 for &i in &flex_idx {
781 let f = cx.flex_of(kids[i]);
782 sizes[i] = if f.is_spacer {
783 Size::ZERO
784 } else {
785 cx.measure_child(kids[i], self.proposal(None, cross_p))
786 };
787 }
788 }
789 }
790 }
791 sizes
792 }
793
794 fn baselines(
798 &self,
799 cx: &mut dyn LayoutOps,
800 kids: &[RNode],
801 sizes: &[Size],
802 ) -> Vec<Option<f64>> {
803 if self.align != CrossAlign::FirstBaseline || self.axis != Axis::Horizontal {
804 return vec![None; kids.len()];
805 }
806 kids.iter()
807 .zip(sizes)
808 .map(|(&k, &s)| cx.baseline_of(k, s))
809 .collect()
810 }
811
812 #[expect(
816 clippy::float_cmp,
817 reason = "`f64::MIN` is the fold's seed, compared as a no-baseline sentinel"
818 )]
819 fn baseline_cross_extent(&self, baselines: &[Option<f64>], sizes: &[Size]) -> Option<f64> {
820 let deepest = baselines.iter().flatten().copied().fold(f64::MIN, f64::max);
821 if deepest == f64::MIN {
822 return None;
823 }
824 let below = baselines
825 .iter()
826 .zip(sizes)
827 .filter_map(|(b, s)| b.map(|b| self.cross(*s) - b))
828 .fold(0.0, f64::max);
829 Some(deepest + below)
830 }
831}
832
833impl Layout for StackLayout {
834 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
835 let mut kids = Vec::new();
836 Self::flatten(cx, children, &mut kids);
837 if kids.is_empty() {
838 return Size::ZERO;
839 }
840 let (main_p, cross_p) = self.split(p);
841 let sizes = self.negotiate(cx, &kids, p);
842 let spacing_total = self.spacing * (kids.len() - 1) as f64;
843 let has_flex = kids.iter().any(|&k| self.grows_main(cx.flex_of(k)));
844 let needed = sizes.iter().map(|&s| self.main(s)).sum::<f64>() + spacing_total;
848 let main_total = match main_p {
849 Some(mp) if has_flex => mp.max(needed),
850 _ => needed,
851 };
852 let grows_cross = kids.iter().any(|&k| self.grows_cross(cx.flex_of(k)));
853 let tallest = sizes.iter().map(|&s| self.cross(s)).fold(0.0, f64::max);
854 let stacked = self
857 .baseline_cross_extent(&self.baselines(cx, &kids, &sizes), &sizes)
858 .unwrap_or(0.0)
859 .max(tallest);
860 let cross_total = match cross_p {
861 Some(cp) if grows_cross => cp,
862 _ => stacked,
863 };
864 self.mk(main_total, cross_total)
865 }
866
867 fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
871 let mut kids = Vec::new();
872 Self::flatten(cx, children, &mut kids);
873 if kids.is_empty() {
874 return None;
875 }
876 let sizes = self.negotiate(cx, &kids, Proposal::exact(size));
877 match self.axis {
878 Axis::Horizontal => {
879 let baselines: Vec<Option<f64>> = kids
880 .iter()
881 .zip(&sizes)
882 .map(|(&k, &s)| cx.baseline_of(k, s))
883 .collect();
884 if self.align == CrossAlign::FirstBaseline {
885 return baselines.iter().flatten().copied().reduce(f64::max);
886 }
887 baselines.iter().zip(&sizes).find_map(|(baseline, child)| {
888 baseline.map(|b| {
889 let offset = match self.align {
890 CrossAlign::Leading => 0.0,
891 CrossAlign::Center => ((size.height - child.height) / 2.0).max(0.0),
892 CrossAlign::Trailing => (size.height - child.height).max(0.0),
893 CrossAlign::FirstBaseline => unreachable!("handled above"),
894 };
895 offset + b
896 })
897 })
898 }
899 Axis::Vertical => {
900 let mut pos = 0.0;
901 for (&k, &s) in kids.iter().zip(&sizes) {
902 if let Some(b) = cx.baseline_of(k, s) {
903 return Some(pos + b);
904 }
905 pos += self.main(s) + self.spacing;
906 }
907 None
908 }
909 }
910 }
911
912 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
913 let mut kids = Vec::new();
914 Self::flatten(cx, children, &mut kids);
915 if kids.is_empty() {
916 return;
917 }
918 let sizes = self.negotiate(cx, &kids, Proposal::exact(bounds.size));
919 let needed = sizes.iter().map(|&s| self.main(s)).sum::<f64>()
924 + self.spacing * (kids.len() - 1) as f64;
925 let available = self.main(bounds.size);
926 if available > 0.5 && needed > available + 0.5 {
932 cx.report_overflow(needed, available);
933 }
934 let bounds_cross = self.cross(bounds.size);
935 let baselines = self.baselines(cx, &kids, &sizes);
939 let deepest = baselines.iter().flatten().copied().fold(f64::MIN, f64::max);
940 let mut pos = 0.0;
941 for (i, &k) in kids.iter().enumerate() {
942 let s = sizes[i];
943 let cross_off = match (self.align, baselines[i]) {
944 (CrossAlign::FirstBaseline, Some(b)) => deepest - b,
945 (CrossAlign::Leading, _) => 0.0,
946 (CrossAlign::Center | CrossAlign::FirstBaseline, _) => {
947 ((bounds_cross - self.cross(s)) / 2.0).max(0.0)
948 }
949 (CrossAlign::Trailing, _) => (bounds_cross - self.cross(s)).max(0.0),
950 };
951 let rect = match self.axis {
952 Axis::Vertical => Rect::new(cross_off, pos, s.width, s.height),
953 Axis::Horizontal => Rect::new(pos, cross_off, s.width, s.height),
954 };
955 cx.place_child(k, rect);
956 pos += self.main(s) + self.spacing;
957 }
958 }
959}
960
961pub struct FlowLayout {
969 pub spacing: f64,
970 pub run_spacing: f64,
972 pub align: CrossAlign,
974 pub uniform: bool,
979}
980
981struct FlowLine {
983 start: usize,
984 end: usize,
985 height: f64,
986}
987
988struct FlowPlan {
991 sizes: Vec<Size>,
992 lines: Vec<FlowLine>,
993}
994
995impl FlowLayout {
996 fn pack(&self, sizes: &[Size], max_w: Option<f64>) -> Vec<FlowLine> {
999 let mut lines = Vec::new();
1000 let mut start = 0;
1001 let mut w = 0.0;
1002 let mut h: f64 = 0.0;
1003 for (i, s) in sizes.iter().enumerate() {
1004 let grown = if i == start {
1005 s.width
1006 } else {
1007 w + self.spacing + s.width
1008 };
1009 if i > start && max_w.is_some_and(|m| grown > m + 0.5) {
1010 lines.push(FlowLine {
1011 start,
1012 end: i,
1013 height: h,
1014 });
1015 start = i;
1016 w = s.width;
1017 h = s.height;
1018 } else {
1019 w = grown;
1020 h = h.max(s.height);
1021 }
1022 }
1023 if start < sizes.len() {
1024 lines.push(FlowLine {
1025 start,
1026 end: sizes.len(),
1027 height: h,
1028 });
1029 }
1030 lines
1031 }
1032
1033 fn grow_lines(
1036 &self,
1037 cx: &mut dyn LayoutOps,
1038 kids: &[RNode],
1039 sizes: &mut [Size],
1040 lines: &mut [FlowLine],
1041 max_w: f64,
1042 ) {
1043 for line in lines {
1044 let range = line.start..line.end;
1045 let weights: Vec<f64> = kids[range.clone()]
1046 .iter()
1047 .map(|&k| {
1048 let f = cx.flex_of(k);
1049 if f.grow_w && !f.is_spacer {
1050 f.weight()
1051 } else {
1052 0.0
1053 }
1054 })
1055 .collect();
1056 let total: f64 = weights.iter().sum();
1057 if total <= 0.0 {
1058 continue;
1059 }
1060 let used = sizes[range.clone()].iter().map(|s| s.width).sum::<f64>()
1061 + self.spacing * (range.len() - 1) as f64;
1062 let spare = (max_w - used).max(0.0);
1063 if spare <= 0.0 {
1064 continue;
1065 }
1066 for (offset, weight) in weights.iter().enumerate() {
1067 if *weight <= 0.0 {
1068 continue;
1069 }
1070 let i = line.start + offset;
1071 let width = sizes[i].width + spare * weight / total;
1072 let s = cx.measure_child(kids[i], Proposal::new(Some(width), None));
1073 sizes[i] = Size::new(width, s.height);
1074 }
1075 line.height = sizes[range].iter().map(|s| s.height).fold(0.0, f64::max);
1076 }
1077 }
1078
1079 fn natural_sizes(cx: &mut dyn LayoutOps, kids: &[RNode]) -> Vec<Size> {
1080 kids.iter()
1081 .map(|&k| cx.measure_child(k, Proposal::UNCONSTRAINED))
1082 .collect()
1083 }
1084
1085 fn plan(&self, cx: &mut dyn LayoutOps, kids: &[RNode], max_w: Option<f64>) -> FlowPlan {
1088 let natural = Self::natural_sizes(cx, kids);
1089 if !self.uniform {
1090 let mut lines = self.pack(&natural, max_w);
1091 let mut sizes = natural;
1092 if let Some(max_w) = max_w {
1093 self.grow_lines(cx, kids, &mut sizes, &mut lines, max_w);
1094 }
1095 return FlowPlan { sizes, lines };
1096 }
1097 let cell_w = natural.iter().map(|s| s.width).fold(0.0, f64::max);
1099 let cols = match max_w {
1100 Some(m) if cell_w > 0.0 => {
1103 (((m + self.spacing) / (cell_w + self.spacing)).floor() as usize).max(1)
1104 }
1105 _ => kids.len().max(1),
1107 };
1108 let col_w = match max_w {
1113 Some(m) if kids.iter().any(|&k| cx.flex_of(k).grow_w) => {
1114 ((m - self.spacing * (cols - 1) as f64) / cols as f64).max(cell_w)
1115 }
1116 _ => cell_w,
1117 };
1118 let col_w = max_w.map_or(col_w, |m| col_w.min(m));
1122 let sizes: Vec<Size> = kids
1126 .iter()
1127 .map(|&k| {
1128 let s = cx.measure_child(k, Proposal::new(Some(col_w), None));
1129 Size::new(col_w, s.height)
1130 })
1131 .collect();
1132 let mut lines = Vec::new();
1133 let mut start = 0;
1134 while start < sizes.len() {
1135 let end = (start + cols).min(sizes.len());
1136 let height = sizes[start..end]
1137 .iter()
1138 .map(|s| s.height)
1139 .fold(0.0, f64::max);
1140 lines.push(FlowLine { start, end, height });
1141 start = end;
1142 }
1143 FlowPlan { sizes, lines }
1144 }
1145}
1146
1147impl Layout for FlowLayout {
1148 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1149 let mut kids = Vec::new();
1150 StackLayout::flatten(cx, children, &mut kids);
1151 if kids.is_empty() {
1152 return Size::ZERO;
1153 }
1154 let plan = self.plan(cx, &kids, p.width);
1155 let height = plan.lines.iter().map(|l| l.height).sum::<f64>()
1156 + self.run_spacing * plan.lines.len().saturating_sub(1) as f64;
1157 let width = p.width.unwrap_or_else(|| {
1160 plan.sizes.iter().map(|s| s.width).sum::<f64>()
1161 + self.spacing * plan.sizes.len().saturating_sub(1) as f64
1162 });
1163 Size::new(width, height)
1164 }
1165
1166 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1167 let mut kids = Vec::new();
1168 StackLayout::flatten(cx, children, &mut kids);
1169 if kids.is_empty() {
1170 return;
1171 }
1172 let plan = self.plan(cx, &kids, Some(bounds.size.width));
1173 let mut y = 0.0;
1174 for line in &plan.lines {
1175 let mut x = 0.0;
1176 let range = line.start..line.end;
1177 for (&k, &s) in kids[range.clone()].iter().zip(&plan.sizes[range]) {
1178 let dy = ((line.height - s.height) * self.align.fraction()).max(0.0);
1179 cx.place_child(k, Rect::new(x, y + dy, s.width, s.height));
1180 x += s.width + self.spacing;
1181 }
1182 y += line.height + self.run_spacing;
1183 }
1184 }
1185}
1186
1187pub struct LanesLayout {
1192 pub min_width: f64,
1194 pub max: usize,
1196 pub spacing: f64,
1198 pub run_spacing: f64,
1200 pub balanced: bool,
1202}
1203
1204struct LanesPlan {
1206 frames: Vec<Rect>,
1207 size: Size,
1208}
1209
1210impl LanesLayout {
1211 #[must_use]
1214 pub fn lane_count(&self, width: Option<f64>) -> usize {
1215 let max = self.max.max(1);
1216 match width {
1217 Some(w) if self.min_width > 0.0 => {
1218 let fit = ((w + self.spacing) / (self.min_width + self.spacing)).floor();
1219 (fit as usize).clamp(1, max)
1220 }
1221 _ => max,
1222 }
1223 }
1224
1225 fn plan(&self, cx: &mut dyn LayoutOps, kids: &[RNode], width: Option<f64>) -> LanesPlan {
1226 let lanes = self.lane_count(width).min(kids.len().max(1));
1227 let lane_w = match width {
1228 Some(w) => ((w - self.spacing * (lanes - 1) as f64) / lanes as f64).max(0.0),
1229 None => self.min_width,
1230 };
1231 let mut heights = vec![0.0_f64; lanes];
1232 let mut frames = Vec::with_capacity(kids.len());
1233 for (i, &kid) in kids.iter().enumerate() {
1234 let lane = if self.balanced {
1235 heights
1238 .iter()
1239 .enumerate()
1240 .fold((0, f64::INFINITY), |best, (at, h)| {
1241 if *h < best.1 - 0.5 { (at, *h) } else { best }
1242 })
1243 .0
1244 } else {
1245 i % lanes
1246 };
1247 let s = cx.measure_child(kid, Proposal::new(Some(lane_w), None));
1248 let y = if heights[lane] > 0.0 {
1249 heights[lane] + self.run_spacing
1250 } else {
1251 0.0
1252 };
1253 frames.push(Rect::new(
1254 lane as f64 * (lane_w + self.spacing),
1255 y,
1256 lane_w,
1257 s.height,
1258 ));
1259 heights[lane] = y + s.height;
1260 }
1261 let size = Size::new(
1262 width.unwrap_or(lane_w * lanes as f64 + self.spacing * (lanes - 1) as f64),
1263 heights.iter().copied().fold(0.0, f64::max),
1264 );
1265 LanesPlan { frames, size }
1266 }
1267}
1268
1269impl Layout for LanesLayout {
1270 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1271 let mut kids = Vec::new();
1272 StackLayout::flatten(cx, children, &mut kids);
1273 if kids.is_empty() {
1274 return Size::new(p.width.unwrap_or(0.0), 0.0);
1275 }
1276 self.plan(cx, &kids, p.width).size
1277 }
1278
1279 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1280 let mut kids = Vec::new();
1281 StackLayout::flatten(cx, children, &mut kids);
1282 if kids.is_empty() {
1283 return;
1284 }
1285 let plan = self.plan(cx, &kids, Some(bounds.size.width));
1286 for (&kid, frame) in kids.iter().zip(plan.frames) {
1287 cx.place_child(kid, frame);
1288 }
1289 }
1290}
1291
1292struct GridCell {
1295 node: RNode,
1296 col: usize,
1297 span: usize,
1298 flex: Flex,
1299}
1300
1301struct GridRowRef {
1303 cells: Vec<GridCell>,
1304 full_width: bool,
1305 valign: Option<CrossAlign>,
1306}
1307
1308struct GridGeom {
1310 rows: Vec<GridRowRef>,
1311 col_x: Vec<f64>,
1312 col_w: Vec<f64>,
1313 row_y: Vec<f64>,
1314 row_h: Vec<f64>,
1315 cell_sizes: Vec<Vec<Size>>,
1317 size: Size,
1318}
1319
1320pub struct GridLayout {
1327 pub row_spacing: f64,
1328 pub column_spacing: f64,
1329 pub align: Alignment,
1330}
1331
1332impl GridLayout {
1333 fn flatten_cells(cx: &mut dyn LayoutOps, children: &[RNode], out: &mut Vec<RNode>) {
1337 for &c in children {
1338 let f = cx.flex_of(c);
1339 if f.is_group && !(f.grid.holds_cell && cx.children_of(c).is_empty()) {
1340 let inner = cx.children_of(c);
1341 Self::flatten_cells(cx, &inner, out);
1342 } else {
1343 out.push(c);
1344 }
1345 }
1346 }
1347
1348 fn collect(cx: &mut dyn LayoutOps, children: &[RNode]) -> (Vec<GridRowRef>, usize) {
1350 let mut tops = Vec::new();
1351 StackLayout::flatten(cx, children, &mut tops);
1352 let mut rows = Vec::new();
1353 let mut ncols = 0usize;
1354 for &t in &tops {
1355 let f = cx.flex_of(t);
1356 if f.grid.is_row {
1357 let inner = cx.children_of(t);
1358 let mut cell_nodes = Vec::new();
1359 Self::flatten_cells(cx, &inner, &mut cell_nodes);
1360 let mut cells = Vec::new();
1361 let mut col = 0usize;
1362 for &c in &cell_nodes {
1363 let cf = cx.flex_of(c);
1364 let span = cf.grid.col_span.max(1) as usize;
1365 cells.push(GridCell {
1366 node: c,
1367 col,
1368 span,
1369 flex: cf,
1370 });
1371 col += span;
1372 }
1373 ncols = ncols.max(col);
1374 rows.push(GridRowRef {
1375 cells,
1376 full_width: false,
1377 valign: f.grid.row_valign,
1378 });
1379 } else {
1380 rows.push(GridRowRef {
1383 cells: vec![GridCell {
1384 node: t,
1385 col: 0,
1386 span: 1,
1387 flex: f,
1388 }],
1389 full_width: true,
1390 valign: None,
1391 });
1392 }
1393 }
1394 (rows, ncols)
1395 }
1396
1397 fn span_width(&self, col_w: &[f64], col: usize, span: usize) -> f64 {
1398 let end = (col + span).min(col_w.len());
1399 let cols: f64 = col_w[col..end].iter().sum();
1400 cols + self.column_spacing * (end.saturating_sub(col + 1)) as f64
1401 }
1402
1403 fn geometry(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> GridGeom {
1408 let (mut rows, ncols) = Self::collect(cx, children);
1409 if rows.is_empty() {
1410 return GridGeom {
1411 rows,
1412 col_x: Vec::new(),
1413 col_w: Vec::new(),
1414 row_y: Vec::new(),
1415 row_h: Vec::new(),
1416 cell_sizes: Vec::new(),
1417 size: Size::ZERO,
1418 };
1419 }
1420 let ncols = ncols.max(1);
1421 for r in &mut rows {
1422 if r.full_width {
1423 r.cells[0].span = ncols;
1424 }
1425 }
1426 let unconstrained = Proposal::new(None, None);
1427
1428 let mut col_ideal = vec![0.0f64; ncols];
1431 let mut col_flex = vec![false; ncols];
1432 let mut flex_ideal = vec![0.0f64; ncols];
1433 for r in rows.iter().filter(|r| !r.full_width) {
1434 for c in r.cells.iter().filter(|c| c.span == 1 && !c.flex.is_spacer) {
1435 if c.flex.grow_w {
1436 col_flex[c.col] = true;
1437 if p.width.is_none() {
1438 let s = cx.measure_child(c.node, unconstrained);
1439 flex_ideal[c.col] = flex_ideal[c.col].max(s.width);
1440 }
1441 } else {
1442 let s = cx.measure_child(c.node, unconstrained);
1443 col_ideal[c.col] = col_ideal[c.col].max(s.width);
1444 }
1445 }
1446 }
1447 for r in rows.iter().filter(|r| !r.full_width) {
1449 for c in r.cells.iter().filter(|c| c.span > 1 && !c.flex.is_spacer) {
1450 if c.flex.grow_w {
1451 let end = (c.col + c.span).min(ncols);
1452 col_flex[c.col..end].fill(true);
1453 }
1454 }
1455 }
1456 for r in rows.iter().filter(|r| !r.full_width) {
1459 for c in r.cells.iter().filter(|c| c.span > 1 && !c.flex.is_spacer) {
1460 if c.flex.grow_w {
1461 continue;
1462 }
1463 let s = cx.measure_child(c.node, unconstrained);
1464 let end = (c.col + c.span).min(ncols);
1465 let avail = self.span_width(&col_ideal, c.col, c.span);
1466 let deficit = s.width - avail;
1467 if deficit > 0.0 {
1468 let flexed: Vec<usize> = (c.col..end).filter(|&k| col_flex[k]).collect();
1469 let targets = if flexed.is_empty() {
1470 (c.col..end).collect()
1471 } else {
1472 flexed
1473 };
1474 let add = deficit / targets.len() as f64;
1475 for k in targets {
1476 col_ideal[k] += add;
1477 }
1478 }
1479 }
1480 }
1481 let mut fw_ideal = 0.0f64;
1484 let mut fw_flex = false;
1485 for r in rows.iter().filter(|r| r.full_width) {
1486 let c = &r.cells[0];
1487 if c.flex.is_spacer {
1488 continue;
1489 }
1490 if c.flex.grow_w {
1491 fw_flex = true;
1492 } else {
1493 let s = cx.measure_child(c.node, unconstrained);
1494 fw_ideal = fw_ideal.max(s.width);
1495 }
1496 }
1497
1498 let gutters = self.column_spacing * (ncols - 1) as f64;
1500 let has_flex_col = col_flex.iter().any(|&f| f);
1501 let mut col_w = vec![0.0f64; ncols];
1502 match p.width {
1503 Some(pw) if has_flex_col => {
1504 let rigid: f64 = (0..ncols)
1505 .filter(|&k| !col_flex[k])
1506 .map(|k| col_ideal[k])
1507 .sum();
1508 let share = (pw - rigid - gutters).max(0.0)
1509 / col_flex.iter().filter(|&&f| f).count() as f64;
1510 for k in 0..ncols {
1511 col_w[k] = if col_flex[k] { share } else { col_ideal[k] };
1512 }
1513 }
1514 _ => {
1515 for k in 0..ncols {
1516 col_w[k] = if col_flex[k] {
1517 flex_ideal[k].max(col_ideal[k])
1518 } else {
1519 col_ideal[k]
1520 };
1521 }
1522 }
1523 }
1524 let cols_total: f64 = col_w.iter().sum::<f64>() + gutters;
1525 let grid_w = match p.width {
1526 Some(pw) if has_flex_col || fw_flex => pw,
1527 _ => cols_total.max(fw_ideal),
1528 };
1529
1530 let nrows = rows.len();
1532 let mut cell_sizes: Vec<Vec<Size>> = Vec::with_capacity(nrows);
1533 let mut row_h = vec![0.0f64; nrows];
1534 let mut row_flex = vec![false; nrows];
1535 for (ri, r) in rows.iter().enumerate() {
1536 let mut sizes = Vec::with_capacity(r.cells.len());
1537 for c in &r.cells {
1538 if c.flex.is_spacer {
1539 sizes.push(Size::ZERO);
1540 continue;
1541 }
1542 let w = if r.full_width {
1543 grid_w
1544 } else {
1545 self.span_width(&col_w, c.col, c.span)
1546 };
1547 let s = cx.measure_child(c.node, Proposal::new(Some(w), None));
1548 row_h[ri] = row_h[ri].max(s.height);
1549 if c.flex.grow_h {
1550 row_flex[ri] = true;
1551 }
1552 sizes.push(s);
1553 }
1554 cell_sizes.push(sizes);
1555 }
1556 let vgutters = self.row_spacing * (nrows - 1) as f64;
1559 if let Some(ph) = p.height
1560 && row_flex.iter().any(|&f| f)
1561 {
1562 let total: f64 = row_h.iter().sum::<f64>() + vgutters;
1563 let extra = (ph - total).max(0.0) / row_flex.iter().filter(|&&f| f).count() as f64;
1564 for (ri, flexed) in row_flex.iter().enumerate() {
1565 if *flexed {
1566 row_h[ri] += extra;
1567 }
1568 }
1569 }
1570 let grid_h = row_h.iter().sum::<f64>() + vgutters;
1571
1572 let mut col_x = vec![0.0f64; ncols];
1573 let mut x = 0.0;
1574 for k in 0..ncols {
1575 col_x[k] = x;
1576 x += col_w[k] + self.column_spacing;
1577 }
1578 let mut row_y = vec![0.0f64; nrows];
1579 let mut y = 0.0;
1580 for ri in 0..nrows {
1581 row_y[ri] = y;
1582 y += row_h[ri] + self.row_spacing;
1583 }
1584 GridGeom {
1585 rows,
1586 col_x,
1587 col_w,
1588 row_y,
1589 row_h,
1590 cell_sizes,
1591 size: Size::new(grid_w, grid_h),
1592 }
1593 }
1594}
1595
1596impl Layout for GridLayout {
1597 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1598 self.geometry(cx, children, p).size
1599 }
1600
1601 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1602 let g = self.geometry(cx, children, Proposal::exact(bounds.size));
1603 for (ri, r) in g.rows.iter().enumerate() {
1604 for (ci, c) in r.cells.iter().enumerate() {
1605 if c.flex.is_spacer {
1606 continue;
1607 }
1608 let cell = if r.full_width {
1609 Rect::new(0.0, g.row_y[ri], g.size.width, g.row_h[ri])
1610 } else {
1611 Rect::new(
1612 g.col_x[c.col],
1613 g.row_y[ri],
1614 self.span_width(&g.col_w, c.col, c.span),
1615 g.row_h[ri],
1616 )
1617 };
1618 let s = g.cell_sizes[ri][ci];
1619 let w = if c.flex.grow_w {
1620 cell.size.width
1621 } else {
1622 s.width.min(cell.size.width)
1623 };
1624 let h = if c.flex.grow_h {
1625 cell.size.height
1626 } else {
1627 s.height.min(cell.size.height)
1628 };
1629 let hf = match c.flex.grid.align {
1632 Some(a) => a.h_fraction(),
1633 None => self.align.h_fraction(),
1634 };
1635 let vf = match (c.flex.grid.align, r.valign) {
1636 (Some(a), _) => a.v_fraction(),
1637 (None, Some(v)) => v.fraction(),
1638 (None, None) => self.align.v_fraction(),
1639 };
1640 let x = cell.origin.x + (cell.size.width - w) * hf;
1641 let y = cell.origin.y + (cell.size.height - h) * vf;
1642 cx.place_child(c.node, Rect::new(x, y, w, h));
1643 }
1644 }
1645 }
1647}
1648
1649#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
1652pub enum Alignment {
1653 TopLeading,
1654 Top,
1655 TopTrailing,
1656 Leading,
1657 #[default]
1658 Center,
1659 Trailing,
1660 BottomLeading,
1661 Bottom,
1662 BottomTrailing,
1663}
1664
1665impl Alignment {
1666 fn h_fraction(self) -> f64 {
1668 match self {
1669 Alignment::TopLeading | Alignment::Leading | Alignment::BottomLeading => 0.0,
1670 Alignment::Top | Alignment::Center | Alignment::Bottom => 0.5,
1671 Alignment::TopTrailing | Alignment::Trailing | Alignment::BottomTrailing => 1.0,
1672 }
1673 }
1674 fn v_fraction(self) -> f64 {
1676 match self {
1677 Alignment::TopLeading | Alignment::Top | Alignment::TopTrailing => 0.0,
1678 Alignment::Leading | Alignment::Center | Alignment::Trailing => 0.5,
1679 Alignment::BottomLeading | Alignment::Bottom | Alignment::BottomTrailing => 1.0,
1680 }
1681 }
1682}
1683
1684pub struct AlignmentLayout {
1687 pub align: Alignment,
1688}
1689
1690impl Layout for AlignmentLayout {
1691 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1692 children
1693 .first()
1694 .map_or(Size::ZERO, |&c| cx.measure_child(c, p))
1695 }
1696
1697 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1698 if let Some(&c) = children.first() {
1699 let size = cx.measure_child(c, Proposal::exact(bounds.size));
1700 let x = (bounds.size.width - size.width).max(0.0) * self.align.h_fraction();
1703 let y = (bounds.size.height - size.height).max(0.0) * self.align.v_fraction();
1704 cx.place_child(c, Rect::new(x, y, size.width, size.height));
1705 }
1706 }
1707
1708 fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
1709 let &child = children.first()?;
1710 let child_size = cx.measure_child(child, Proposal::exact(size));
1711 let offset = (size.height - child_size.height).max(0.0) * self.align.v_fraction();
1712 cx.baseline_of(child, child_size)
1713 .map(|baseline| baseline + offset)
1714 }
1715}
1716
1717#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1720pub enum Dimension {
1721 Width,
1722 Height,
1723 Both,
1724}
1725
1726impl Dimension {
1727 #[must_use]
1731 pub fn weight(self, weight: f64) -> Grow {
1732 Grow {
1733 dimension: self,
1734 weight,
1735 }
1736 }
1737}
1738
1739#[derive(Clone, Copy, PartialEq, Debug)]
1743pub struct Grow {
1744 pub dimension: Dimension,
1745 pub weight: f64,
1747}
1748
1749impl From<Dimension> for Grow {
1750 fn from(dimension: Dimension) -> Self {
1751 Grow {
1752 dimension,
1753 weight: 1.0,
1754 }
1755 }
1756}
1757
1758pub struct OverlayLayout {
1765 pub align: Alignment,
1766 pub size_to_first: bool,
1767}
1768
1769impl OverlayLayout {
1770 fn flatten(cx: &mut dyn LayoutOps, children: &[RNode], out: &mut Vec<RNode>) {
1772 for &c in children {
1773 if cx.flex_of(c).is_group {
1774 let inner = cx.children_of(c);
1775 Self::flatten(cx, &inner, out);
1776 } else {
1777 out.push(c);
1778 }
1779 }
1780 }
1781}
1782
1783impl Layout for OverlayLayout {
1784 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1785 let mut kids = Vec::new();
1786 Self::flatten(cx, children, &mut kids);
1787 if self.size_to_first {
1788 return match kids.first() {
1789 Some(&c) => cx.measure_child(c, p),
1790 None => Size::ZERO,
1791 };
1792 }
1793 let mut size = Size::ZERO;
1794 for &c in &kids {
1795 let s = cx.measure_child(c, p);
1796 size.width = size.width.max(s.width);
1797 size.height = size.height.max(s.height);
1798 }
1799 size
1800 }
1801 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1802 let mut kids = Vec::new();
1803 Self::flatten(cx, children, &mut kids);
1804 for &c in &kids {
1805 let s = cx.measure_child(c, Proposal::exact(bounds.size));
1806 let x = (bounds.size.width - s.width) * self.align.h_fraction();
1807 let y = (bounds.size.height - s.height) * self.align.v_fraction();
1808 cx.place_child(c, Rect::new(x, y, s.width, s.height));
1809 }
1810 }
1811}
1812
1813pub struct PaddingLayout {
1815 pub insets: std::cell::Cell<Insets>,
1818}
1819
1820impl Layout for PaddingLayout {
1821 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1822 let inner = Proposal::new(
1823 p.width
1824 .map(|w| (w - self.insets.get().horizontal_total()).max(0.0)),
1825 p.height
1826 .map(|h| (h - self.insets.get().vertical_total()).max(0.0)),
1827 );
1828 let s = match children.first() {
1829 Some(&c) => cx.measure_child(c, inner),
1830 None => Size::ZERO,
1831 };
1832 Size::new(
1833 s.width + self.insets.get().horizontal_total(),
1834 s.height + self.insets.get().vertical_total(),
1835 )
1836 }
1837 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1838 if let Some(&c) = children.first() {
1839 let inner = bounds.inset_by(self.insets.get());
1840 let s = cx.measure_child(c, Proposal::exact(inner.size));
1841 cx.place_child(
1842 c,
1843 Rect {
1844 origin: inner.origin,
1845 size: s,
1846 },
1847 );
1848 }
1849 }
1850 fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
1851 let inner = Size::new(
1853 (size.width - self.insets.get().horizontal_total()).max(0.0),
1854 (size.height - self.insets.get().vertical_total()).max(0.0),
1855 );
1856 wrapper_baseline(cx, children, inner, self.insets.get().top)
1857 }
1858}
1859
1860pub struct AspectRatioLayout {
1867 pub ratio: std::cell::Cell<f64>,
1869}
1870
1871impl Layout for AspectRatioLayout {
1872 fn measure(&self, cx: &mut dyn LayoutOps, _children: &[RNode], p: Proposal) -> Size {
1873 match (p.width, p.height) {
1874 (Some(w), Some(h)) => {
1875 if w / h > self.ratio.get() {
1876 Size::new(h * self.ratio.get(), h)
1877 } else {
1878 Size::new(w, w / self.ratio.get())
1879 }
1880 }
1881 (Some(w), None) => Size::new(w, w / self.ratio.get()),
1882 (None, Some(h)) => Size::new(h * self.ratio.get(), h),
1883 (None, None) => cx.measure_leaf(p),
1884 }
1885 }
1886 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1887 for &c in children {
1889 cx.place_child(c, Rect::from_size(bounds.size));
1890 }
1891 }
1892 fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
1893 wrapper_baseline(cx, children, size, 0.0)
1894 }
1895}
1896
1897pub struct GrowLayout {
1901 pub w: bool,
1902 pub h: bool,
1903}
1904
1905impl Layout for GrowLayout {
1906 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1907 let cs = match children.first() {
1908 Some(&c) => cx.measure_child(c, p),
1909 None => Size::ZERO,
1910 };
1911 Size::new(
1915 if self.w {
1916 p.width.map_or(cs.width, |w| w.max(cs.width))
1917 } else {
1918 cs.width
1919 },
1920 if self.h {
1921 p.height.map_or(cs.height, |h| h.max(cs.height))
1922 } else {
1923 cs.height
1924 },
1925 )
1926 }
1927 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1928 if let Some(&c) = children.first() {
1929 let cs = cx.measure_child(c, Proposal::exact(bounds.size));
1930 let w = if self.w { bounds.size.width } else { cs.width };
1932 let h = if self.h {
1933 bounds.size.height
1934 } else {
1935 cs.height
1936 };
1937 cx.place_child(c, Rect::from_size(Size::new(w, h)));
1938 }
1939 }
1940 fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
1941 let &child = children.first()?;
1942 let measured = cx.measure_child(child, Proposal::exact(size));
1943 wrapper_baseline(
1944 cx,
1945 children,
1946 Size::new(
1947 if self.w { size.width } else { measured.width },
1948 if self.h { size.height } else { measured.height },
1949 ),
1950 0.0,
1951 )
1952 }
1953}
1954
1955pub struct MaxWidthLayout {
1959 pub max: std::cell::Cell<f64>,
1961}
1962
1963impl Layout for MaxWidthLayout {
1964 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
1965 let capped = Proposal::new(
1966 Some(p.width.map_or(self.max.get(), |w| w.min(self.max.get()))),
1967 p.height,
1968 );
1969 match children.first() {
1970 Some(&c) => {
1971 let s = cx.measure_child(c, capped);
1972 Size::new(s.width.min(self.max.get()), s.height)
1973 }
1974 None => Size::ZERO,
1975 }
1976 }
1977 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
1978 if let Some(&c) = children.first() {
1979 let w = bounds.size.width.min(self.max.get());
1980 let s = cx.measure_child(c, Proposal::exact(Size::new(w, bounds.size.height)));
1981 cx.place_child(c, Rect::from_size(Size::new(s.width.min(w), s.height)));
1982 }
1983 }
1984 fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
1985 PassThrough::forward(cx, children, size)
1986 }
1987}
1988
1989pub struct MaxHeightLayout {
1995 pub max: std::cell::Cell<f64>,
1997}
1998
1999impl Layout for MaxHeightLayout {
2000 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
2001 let capped = Proposal::new(
2002 p.width,
2003 Some(p.height.map_or(self.max.get(), |h| h.min(self.max.get()))),
2004 );
2005 match children.first() {
2006 Some(&c) => {
2007 let s = cx.measure_child(c, capped);
2008 Size::new(s.width, s.height.min(self.max.get()))
2009 }
2010 None => Size::ZERO,
2011 }
2012 }
2013 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
2014 if let Some(&c) = children.first() {
2015 let h = bounds.size.height.min(self.max.get());
2016 let s = cx.measure_child(c, Proposal::exact(Size::new(bounds.size.width, h)));
2017 cx.place_child(c, Rect::from_size(Size::new(s.width, s.height.min(h))));
2018 }
2019 }
2020 fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
2021 PassThrough::forward(cx, children, size)
2022 }
2023}
2024
2025pub struct MinWidthLayout {
2031 pub min: std::cell::Cell<f64>,
2033}
2034
2035impl Layout for MinWidthLayout {
2036 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
2037 let floored = Proposal::new(p.width.map(|w| w.max(self.min.get())), p.height);
2038 match children.first() {
2039 Some(&c) => {
2040 let s = cx.measure_child(c, floored);
2041 Size::new(s.width.max(self.min.get()), s.height)
2042 }
2043 None => Size::new(self.min.get(), 0.0),
2044 }
2045 }
2046 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
2047 if let Some(&c) = children.first() {
2048 let w = bounds.size.width.max(self.min.get());
2049 let s = cx.measure_child(c, Proposal::exact(Size::new(w, bounds.size.height)));
2050 cx.place_child(c, Rect::from_size(Size::new(w, s.height)));
2051 }
2052 }
2053 fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
2054 PassThrough::forward(cx, children, size)
2055 }
2056}
2057
2058pub struct MinHeightLayout {
2061 pub min: std::cell::Cell<f64>,
2063}
2064
2065impl Layout for MinHeightLayout {
2066 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
2067 let floored = Proposal::new(p.width, p.height.map(|h| h.max(self.min.get())));
2068 match children.first() {
2069 Some(&c) => {
2070 let s = cx.measure_child(c, floored);
2071 Size::new(s.width, s.height.max(self.min.get()))
2072 }
2073 None => Size::new(0.0, self.min.get()),
2074 }
2075 }
2076 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
2077 if let Some(&c) = children.first() {
2078 let height = bounds.size.height.max(self.min.get());
2079 let size = cx.measure_child(c, Proposal::exact(Size::new(bounds.size.width, height)));
2080 cx.place_child(c, Rect::from_size(Size::new(size.width, height)));
2081 }
2082 }
2083 fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
2084 let &child = children.first()?;
2085 let height = size.height.max(self.min.get());
2086 let measured = cx.measure_child(child, Proposal::exact(Size::new(size.width, height)));
2087 cx.baseline_of(child, Size::new(measured.width, height))
2088 }
2089}
2090
2091pub struct ReserveLayout;
2103
2104impl Layout for ReserveLayout {
2105 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
2106 let Some(&content) = children.first() else {
2107 return Size::ZERO;
2108 };
2109 let c = cx.measure_child(content, p);
2110 let s = children
2111 .get(1)
2112 .map_or(Size::ZERO, |&sample| cx.measure_child(sample, p));
2113 Size::new(s.width.max(c.width), s.height.max(c.height))
2114 }
2115
2116 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
2117 if let Some(&content) = children.first() {
2118 cx.place_child(content, Rect::from_size(bounds.size));
2119 }
2120 if let Some(&sample) = children.get(1) {
2121 cx.place_child(sample, Rect::from_size(Size::ZERO));
2122 }
2123 }
2124
2125 fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
2126 cx.baseline_of(*children.first()?, size)
2127 }
2128}
2129
2130pub struct FrameLayout {
2131 pub width: Option<f64>,
2132 pub height: Option<f64>,
2133}
2134
2135impl Layout for FrameLayout {
2136 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
2137 let child_p = Proposal::new(self.width.or(p.width), self.height.or(p.height));
2138 let s = match children.first() {
2139 Some(&c) => cx.measure_child(c, child_p),
2140 None => Size::ZERO,
2141 };
2142 Size::new(
2143 self.width.unwrap_or(s.width),
2144 self.height.unwrap_or(s.height),
2145 )
2146 }
2147 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
2148 if let Some(&c) = children.first() {
2149 cx.place_child(c, bounds);
2150 }
2151 }
2152 fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
2153 wrapper_baseline(cx, children, size, 0.0)
2154 }
2155}
2156
2157pub struct ScrollLayout {
2161 pub axis: Axis,
2162 pub padding: Insets,
2165}
2166
2167impl ScrollLayout {
2168 fn pad(&self) -> (f64, f64) {
2170 let (h, v) = (
2171 self.padding.leading + self.padding.trailing,
2172 self.padding.top + self.padding.bottom,
2173 );
2174 match self.axis {
2175 Axis::Vertical => (h, v),
2176 Axis::Horizontal => (v, h),
2177 }
2178 }
2179}
2180
2181impl Layout for ScrollLayout {
2182 fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
2183 let (pad_w, pad_h) = (
2184 self.padding.leading + self.padding.trailing,
2185 self.padding.top + self.padding.bottom,
2186 );
2187 let content_p = match self.axis {
2188 Axis::Vertical => Proposal::new(p.width.map(|w| (w - pad_w).max(0.0)), None),
2189 Axis::Horizontal => Proposal::new(None, p.height.map(|h| (h - pad_h).max(0.0))),
2190 };
2191 let cs = match children.first() {
2192 Some(&c) => cx.measure_child(c, content_p),
2193 None => Size::ZERO,
2194 };
2195 Size::new(
2196 p.width.unwrap_or(cs.width + pad_w),
2197 p.height.unwrap_or(cs.height + pad_h),
2198 )
2199 }
2200 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
2201 if let Some(&c) = children.first() {
2202 let vertical = self.axis == Axis::Vertical;
2203 let (pad_cross, pad_main) = self.pad();
2204 let proposal = |cross: f64| {
2205 let cross = (cross - pad_cross).max(0.0);
2206 match self.axis {
2207 Axis::Vertical => Proposal::new(Some(cross), None),
2208 Axis::Horizontal => Proposal::new(None, Some(cross)),
2209 }
2210 };
2211 let (cross, main) = match self.axis {
2212 Axis::Vertical => (bounds.size.width, bounds.size.height),
2213 Axis::Horizontal => (bounds.size.height, bounds.size.width),
2214 };
2215 let mut cs = cx.measure_child(c, proposal(cross));
2216 let overflows = |s: Size| if vertical { s.height } else { s.width } + pad_main > main;
2217 let mut cross = cross;
2221 if overflows(cs) {
2222 let inset = cx.scroll_bar_inset(vertical);
2223 if inset > 0.0 {
2224 cross = (cross - inset).max(0.0);
2225 cs = cx.measure_child(c, proposal(cross));
2226 }
2227 }
2228 let (content, child) = match self.axis {
2230 Axis::Vertical => {
2231 let h = (cs.height + pad_main).max(bounds.size.height);
2232 (
2233 Size::new(cross, h),
2234 Size::new((cross - pad_cross).max(0.0), h - pad_main),
2235 )
2236 }
2237 Axis::Horizontal => {
2238 let w = (cs.width + pad_main).max(bounds.size.width);
2239 (
2240 Size::new(w, cross),
2241 Size::new(w - pad_main, (cross - pad_cross).max(0.0)),
2242 )
2243 }
2244 };
2245 cx.set_scroll_content(content);
2249 cx.place_child(
2250 c,
2251 Rect::new(
2252 self.padding.leading,
2253 self.padding.top,
2254 child.width,
2255 child.height,
2256 ),
2257 );
2258 }
2259 }
2260}
2261
2262pub struct NavLayout {
2267 pub sizes: std::rc::Rc<std::cell::RefCell<std::collections::HashMap<RNode, Size>>>,
2268 pub presentation: std::rc::Rc<std::cell::Cell<day_spec::props::NavPresentation>>,
2272 pub sidebar: std::rc::Rc<std::cell::Cell<Option<RNode>>>,
2275 pub list: std::rc::Rc<std::cell::Cell<Option<RNode>>>,
2277 pub list_width: f64,
2279 pub list_visible: std::rc::Rc<std::cell::Cell<bool>>,
2283}
2284
2285pub use day_spec::{NAV_LIST_WIDTH, NAV_SIDEBAR_WIDTH};
2286
2287impl NavLayout {
2288 pub fn stack(
2291 sizes: std::rc::Rc<std::cell::RefCell<std::collections::HashMap<RNode, Size>>>,
2292 ) -> Self {
2293 NavLayout {
2294 sizes,
2295 presentation: std::rc::Rc::new(std::cell::Cell::new(
2296 day_spec::props::NavPresentation::Stack,
2297 )),
2298 sidebar: std::rc::Rc::new(std::cell::Cell::new(None)),
2299 list: std::rc::Rc::new(std::cell::Cell::new(None)),
2300 list_width: NAV_LIST_WIDTH,
2301 list_visible: std::rc::Rc::new(std::cell::Cell::new(true)),
2302 }
2303 }
2304}
2305
2306impl Layout for NavLayout {
2307 fn measure(&self, _cx: &mut dyn LayoutOps, _children: &[RNode], p: Proposal) -> Size {
2308 Size::new(p.width.unwrap_or(480.0), p.height.unwrap_or(640.0))
2312 }
2313 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
2314 let pres = self.presentation.get();
2315 let split = pres.is_split();
2316 let sidebar = self.sidebar.get();
2317 let list = self.list.get();
2318 let list_w = if split && list.is_some() && self.list_visible.get() {
2321 self.list_width
2322 } else {
2323 0.0
2324 };
2325 for &page in children {
2326 let reported = self.sizes.borrow().get(&page).copied();
2327 let sz = reported.unwrap_or_else(|| {
2331 let is_sidebar = Some(page) == sidebar;
2332 let is_list = Some(page) == list;
2333 if pres.rows_are_chrome() {
2334 if is_sidebar {
2340 Size::new(NAV_SIDEBAR_WIDTH, bounds.size.height)
2341 } else if is_list {
2342 Size::new(self.list_width, bounds.size.height)
2343 } else {
2344 bounds.size
2345 }
2346 } else if !split {
2347 bounds.size
2351 } else if is_sidebar {
2352 Size::new(NAV_SIDEBAR_WIDTH, bounds.size.height)
2353 } else if is_list {
2354 Size::new(self.list_width, bounds.size.height)
2355 } else {
2356 Size::new(
2357 (bounds.size.width - NAV_SIDEBAR_WIDTH - list_w - 1.0).max(0.0),
2358 bounds.size.height,
2359 )
2360 }
2361 });
2362 cx.place_child_native(page, Rect::from_size(sz));
2363 }
2364 }
2365}
2366
2367pub struct InspectorLayout {
2373 pub sizes: std::rc::Rc<std::cell::RefCell<std::collections::HashMap<RNode, Size>>>,
2374 pub visible: std::rc::Rc<std::cell::Cell<bool>>,
2377 pub width: f64,
2379}
2380
2381impl Layout for InspectorLayout {
2382 fn measure(&self, _cx: &mut dyn LayoutOps, _children: &[RNode], p: Proposal) -> Size {
2383 Size::new(p.width.unwrap_or(480.0), p.height.unwrap_or(640.0))
2385 }
2386 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
2387 for (i, &pane) in children.iter().enumerate() {
2389 let reported = self.sizes.borrow().get(&pane).copied();
2390 let sz = reported.unwrap_or_else(|| {
2391 let panel_w = if self.visible.get() { self.width } else { 0.0 };
2392 if i == 0 {
2393 Size::new((bounds.size.width - panel_w).max(0.0), bounds.size.height)
2394 } else {
2395 Size::new(panel_w, bounds.size.height)
2396 }
2397 });
2398 cx.place_child_native(pane, Rect::from_size(sz));
2399 }
2400 }
2401}
2402
2403pub struct SplitLayout {
2408 pub sizes: std::rc::Rc<std::cell::RefCell<std::collections::HashMap<RNode, Size>>>,
2409 pub stacked: std::rc::Rc<std::cell::Cell<bool>>,
2411 pub fraction: std::rc::Rc<std::cell::Cell<f64>>,
2413}
2414
2415impl Layout for SplitLayout {
2416 fn measure(&self, _cx: &mut dyn LayoutOps, _children: &[RNode], p: Proposal) -> Size {
2417 Size::new(p.width.unwrap_or(480.0), p.height.unwrap_or(640.0))
2419 }
2420 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
2421 let f = self.fraction.get().clamp(0.0, 1.0);
2423 let (w, h) = (bounds.size.width, bounds.size.height);
2424 for (i, &pane) in children.iter().enumerate() {
2425 let reported = self.sizes.borrow().get(&pane).copied();
2426 let sz = reported.unwrap_or_else(|| {
2427 let share = if i == 0 { f } else { 1.0 - f };
2428 if self.stacked.get() {
2429 Size::new(w, (h * share).floor())
2430 } else {
2431 Size::new((w * share).floor(), h)
2432 }
2433 });
2434 cx.place_child_native(pane, Rect::from_size(sz));
2435 }
2436 }
2437}
2438
2439pub struct CoverLayout {
2444 pub size: std::rc::Rc<std::cell::RefCell<Option<Size>>>,
2445}
2446
2447impl Layout for CoverLayout {
2448 fn measure(&self, _cx: &mut dyn LayoutOps, _children: &[RNode], _p: Proposal) -> Size {
2449 Size::new(0.0, 0.0)
2450 }
2451 fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], _bounds: Rect) {
2452 let Some(sz) = *self.size.borrow() else {
2453 return; };
2455 for &child in children {
2456 cx.place_child_native(child, Rect::from_size(sz));
2457 }
2458 }
2459}
2460
2461pub fn rc_layout<L: Layout>(l: L) -> Rc<dyn Layout> {
2463 Rc::new(l)
2464}