Skip to main content

mgui_core/layout/
constrained_box.rs

1//! ConstrainedBox — 附加约束(与父约束相交)的单 child 容器
2
3use crate::id::ElementId;
4use crate::paint::PaintList;
5use crate::render_object::{make_ro_shared, BoxConstraints, LayoutContext, RRectRenderObject, RenderObject, SharedRO};
6use crate::widget::{Widget, WidgetNode};
7use crate::{Color, Point, Size};
8
9/// ConstrainedBox RenderObject — 附加约束(与父约束相交)
10pub struct ConstrainedBoxRenderObject {
11    pub min_width: f32,
12    pub max_width: f32,
13    pub min_height: f32,
14    pub max_height: f32,
15    child: Option<SharedRO>,
16    cached_size: Size,
17    child_cached_size: Size,
18}
19
20impl ConstrainedBoxRenderObject {
21    pub fn new(
22        min_width: f32,
23        max_width: f32,
24        min_height: f32,
25        max_height: f32,
26        child: Option<Box<dyn RenderObject>>,
27    ) -> Self {
28        Self {
29            min_width,
30            max_width,
31            min_height,
32            max_height,
33            child: child.map(make_ro_shared),
34            cached_size: Size::ZERO,
35            child_cached_size: Size::ZERO,
36        }
37    }
38
39    /// 计算附加约束与父约束的相交,并夹紧 min ≤ max 避免产生无效约束
40    fn intersect(&self, parent: BoxConstraints) -> BoxConstraints {
41        let mut result = BoxConstraints {
42            min_width: parent.min_width.max(self.min_width),
43            max_width: parent.max_width.min(self.max_width),
44            min_height: parent.min_height.max(self.min_height),
45            max_height: parent.max_height.min(self.max_height),
46        };
47        // 夹紧:相交后可能出现 min > max(父 min 比 self max 还大),非法
48        result.min_width = result.min_width.min(result.max_width);
49        result.min_height = result.min_height.min(result.max_height);
50        result
51    }
52}
53
54impl RenderObject for ConstrainedBoxRenderObject {
55    fn layout(&mut self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size {
56        let child_constraints = self.intersect(constraints);
57        self.child_cached_size =
58            if let Some(child) = &mut self.child { child.layout_cached(child_constraints, ctx) } else { Size::ZERO };
59        self.cached_size = self.child_cached_size;
60        constraints.constrain(self.cached_size)
61    }
62
63    fn content_size(&self) -> Size {
64        self.cached_size
65    }
66
67    fn paint(&self, offset: Point, painter: &mut PaintList) {
68        if let Some(child) = &self.child {
69            child.borrow().paint(offset, painter);
70        }
71    }
72
73    fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
74        self.child.as_ref().and_then(|c| c.borrow().hit_test(position, offset))
75    }
76
77    fn propagate_element_ids(&mut self, child_ids: &[ElementId], stateful_ros: &mut [SharedRO]) {
78        if let Some(child) = &mut self.child {
79            if let Some(&cid) = child_ids.first() {
80                if let Some(new_ro) = stateful_ros.first_mut() {
81                    *child = new_ro.clone();
82                }
83                child.borrow_mut().set_element_id(cid);
84            }
85        }
86    }
87
88    fn child_slots(&self) -> Vec<(Point, SharedRO)> {
89        self.child.as_ref().map(|c| vec![(Point::ZERO, c.clone())]).unwrap_or_default()
90    }
91
92    fn for_each_child(&self, f: &mut dyn FnMut(Point, &SharedRO)) {
93        if let Some(c) = &self.child {
94            f(Point::ZERO, c);
95        }
96    }
97
98    fn children_count(&self) -> usize {
99        if self.child.is_some() {
100            1
101        } else {
102            0
103        }
104    }
105}
106
107/// ConstrainedBox(附加约束,与父约束相交)
108///
109/// 例: `ConstrainedBox::new().min_w(200.0).max_w(400.0).child(button)`
110///   → button width 永远在 200..400 之间
111#[derive(Debug)]
112pub struct ConstrainedBoxWidget {
113    pub min_width: f32,
114    pub max_width: f32,
115    pub min_height: f32,
116    pub max_height: f32,
117    pub child: Option<WidgetNode>,
118}
119
120impl ConstrainedBoxWidget {
121    /// 最大 — 不附加任何约束,只限制上限
122    pub fn big(child: impl Widget) -> Self {
123        Self {
124            min_width: 0.0,
125            max_width: f32::INFINITY,
126            min_height: 0.0,
127            max_height: f32::INFINITY,
128            child: Some(WidgetNode::new(child)),
129        }
130    }
131
132    pub fn min_w(mut self, w: f32) -> Self {
133        self.min_width = w;
134        self
135    }
136    pub fn max_w(mut self, w: f32) -> Self {
137        self.max_width = w;
138        self
139    }
140    pub fn min_h(mut self, h: f32) -> Self {
141        self.min_height = h;
142        self
143    }
144    pub fn max_h(mut self, h: f32) -> Self {
145        self.max_height = h;
146        self
147    }
148
149    pub fn min(mut self, size: Size) -> Self {
150        self.min_width = size.width;
151        self.min_height = size.height;
152        self
153    }
154    pub fn max(mut self, size: Size) -> Self {
155        self.max_width = size.width;
156        self.max_height = size.height;
157        self
158    }
159}
160
161impl Widget for ConstrainedBoxWidget {
162    fn as_any(&self) -> &dyn std::any::Any {
163        self
164    }
165
166    fn is_equivalent(&self, old: &dyn Widget) -> bool {
167        old.as_any().downcast_ref::<ConstrainedBoxWidget>().is_some_and(|o| {
168            self.min_width == o.min_width
169                && self.max_width == o.max_width
170                && self.min_height == o.min_height
171                && self.max_height == o.max_height
172                && crate::widget::optional_child_equivalent(&self.child, &o.child)
173        })
174    }
175
176    fn create_render_object(&self) -> Box<dyn RenderObject> {
177        let child_ro = match &self.child {
178            Some(c) => c.0.create_render_object(),
179            None => Box::new(RRectRenderObject::new(Size::ZERO, Color::TRANSPARENT, 0.0)),
180        };
181        Box::new(ConstrainedBoxRenderObject::new(
182            self.min_width,
183            self.max_width,
184            self.min_height,
185            self.max_height,
186            Some(child_ro),
187        ))
188    }
189
190    fn children(&self) -> Vec<WidgetNode> {
191        match &self.child {
192            Some(c) => vec![c.clone()],
193            None => vec![],
194        }
195    }
196}