Skip to main content

mgui_core/layout/
limited_box.rs

1//! LimitedBox — 仅在对应轴**无界**时给 child 施加最大尺寸限制
2//!
3//! 语义(对齐 Flutter `RenderLimitedBox`):
4//! - 若传入 `constraints.max_width` 为无限 → child 该轴 max 用自身 `max_width`;
5//!   否则透传父 `max_width`
6//! - 高度同理
7//! - 自身尺寸 = `constraints.constrain(child_size)`
8//!
9//! 典型用途:作为无界父(如 Column 主轴方向)里子节点的默认尺寸上限,
10//! 有界父下不产生任何影响。
11
12use crate::id::ElementId;
13use crate::paint::PaintList;
14use crate::render_object::{make_ro_shared, BoxConstraints, LayoutContext, RRectRenderObject, RenderObject, SharedRO};
15use crate::widget::{Widget, WidgetNode};
16use crate::{Color, Point, Size};
17
18/// LimitedBox RenderObject
19pub struct LimitedBoxRenderObject {
20    pub max_width: f32,
21    pub max_height: f32,
22    child: Option<SharedRO>,
23    cached_size: Size,
24    child_cached_size: Size,
25}
26
27impl LimitedBoxRenderObject {
28    pub fn new(max_width: f32, max_height: f32, child: Option<Box<dyn RenderObject>>) -> Self {
29        Self {
30            max_width,
31            max_height,
32            child: child.map(make_ro_shared),
33            cached_size: Size::ZERO,
34            child_cached_size: Size::ZERO,
35        }
36    }
37}
38
39impl RenderObject for LimitedBoxRenderObject {
40    fn layout(&mut self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size {
41        // 仅当父约束该轴无限时才施加自身上限
42        let child_constraints = BoxConstraints {
43            min_width: constraints.min_width,
44            max_width: if constraints.max_width.is_infinite() { self.max_width } else { constraints.max_width },
45            min_height: constraints.min_height,
46            max_height: if constraints.max_height.is_infinite() { self.max_height } else { constraints.max_height },
47        };
48        self.child_cached_size =
49            if let Some(child) = &mut self.child { child.layout_cached(child_constraints, ctx) } else { Size::ZERO };
50        self.cached_size = self.child_cached_size;
51        constraints.constrain(self.cached_size)
52    }
53
54    fn content_size(&self) -> Size {
55        self.cached_size
56    }
57
58    fn paint(&self, offset: Point, painter: &mut PaintList) {
59        if let Some(child) = &self.child {
60            child.borrow().paint(offset, painter);
61        }
62    }
63
64    fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
65        self.child.as_ref().and_then(|c| c.borrow().hit_test(position, offset))
66    }
67
68    fn propagate_element_ids(&mut self, child_ids: &[ElementId], stateful_ros: &mut [SharedRO]) {
69        if let Some(child) = &mut self.child {
70            if let Some(&cid) = child_ids.first() {
71                if let Some(new_ro) = stateful_ros.first_mut() {
72                    *child = new_ro.clone();
73                }
74                child.borrow_mut().set_element_id(cid);
75            }
76        }
77    }
78
79    fn child_slots(&self) -> Vec<(Point, SharedRO)> {
80        self.child.as_ref().map(|c| vec![(Point::ZERO, c.clone())]).unwrap_or_default()
81    }
82
83    fn for_each_child(&self, f: &mut dyn FnMut(Point, &SharedRO)) {
84        if let Some(c) = &self.child {
85            f(Point::ZERO, c);
86        }
87    }
88
89    fn children_count(&self) -> usize {
90        if self.child.is_some() {
91            1
92        } else {
93            0
94        }
95    }
96}
97
98/// LimitedBox(仅无界轴上施加最大尺寸)
99#[derive(Debug)]
100pub struct LimitedBoxWidget {
101    pub max_width: f32,
102    pub max_height: f32,
103    pub child: Option<WidgetNode>,
104}
105
106impl LimitedBoxWidget {
107    pub fn new(child: impl Widget) -> Self {
108        Self { max_width: f32::INFINITY, max_height: f32::INFINITY, child: Some(WidgetNode::new(child)) }
109    }
110
111    pub fn max_w(mut self, w: f32) -> Self {
112        self.max_width = w;
113        self
114    }
115    pub fn max_h(mut self, h: f32) -> Self {
116        self.max_height = h;
117        self
118    }
119}
120
121impl Widget for LimitedBoxWidget {
122    fn as_any(&self) -> &dyn std::any::Any {
123        self
124    }
125
126    fn is_equivalent(&self, old: &dyn Widget) -> bool {
127        old.as_any().downcast_ref::<LimitedBoxWidget>().is_some_and(|o| {
128            self.max_width == o.max_width
129                && self.max_height == o.max_height
130                && crate::widget::optional_child_equivalent(&self.child, &o.child)
131        })
132    }
133
134    fn create_render_object(&self) -> Box<dyn RenderObject> {
135        let child_ro = match &self.child {
136            Some(c) => c.0.create_render_object(),
137            None => Box::new(RRectRenderObject::new(Size::ZERO, Color::TRANSPARENT, 0.0)),
138        };
139        Box::new(LimitedBoxRenderObject::new(self.max_width, self.max_height, Some(child_ro)))
140    }
141
142    fn children(&self) -> Vec<WidgetNode> {
143        match &self.child {
144            Some(c) => vec![c.clone()],
145            None => vec![],
146        }
147    }
148}