Skip to main content

mgui_core/layout/
unconstrained_box.rs

1//! UnconstrainedBox — child 用**无限约束**布局(取自然尺寸),自身被父约束夹紧
2//!
3//! 与 `ConstrainedBox` 相反:不向 child 施加任何上限,child 按内容自然尺寸布局;
4//! 容器自身尺寸 = `constraints.constrain(child_size)`(通常被父约束夹紧),
5//! 若 child 比容器大则**溢出**(paint/hit_test 不裁剪)。
6
7use crate::id::ElementId;
8use crate::paint::PaintList;
9use crate::render_object::{make_ro_shared, BoxConstraints, LayoutContext, RRectRenderObject, RenderObject, SharedRO};
10use crate::widget::{Widget, WidgetNode};
11use crate::{Color, Point, Size};
12
13use super::alignment::Alignment;
14
15/// UnconstrainedBox RenderObject
16pub struct UnconstrainedBoxRenderObject {
17    pub alignment: Alignment,
18    child: Option<SharedRO>,
19    cached_size: Size,
20    child_cached_size: Size,
21    child_offset: Point,
22}
23
24impl UnconstrainedBoxRenderObject {
25    pub fn new(alignment: Alignment, child: Option<Box<dyn RenderObject>>) -> Self {
26        Self {
27            alignment,
28            child: child.map(make_ro_shared),
29            cached_size: Size::ZERO,
30            child_cached_size: Size::ZERO,
31            child_offset: Point::ZERO,
32        }
33    }
34}
35
36impl RenderObject for UnconstrainedBoxRenderObject {
37    fn layout(&mut self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size {
38        // 1. child 用无限约束布局 → 自然尺寸
39        self.child_cached_size = if let Some(child) = &mut self.child {
40            child.layout_cached(BoxConstraints::UNBOUNDED, ctx)
41        } else {
42            Size::ZERO
43        };
44        // 2. 自身尺寸 = 父约束夹紧后的 child 尺寸
45        self.cached_size = constraints.constrain(self.child_cached_size);
46        // 3. 按 alignment 摆位 child(允许负值 → 溢出)
47        let delta_w = self.cached_size.width - self.child_cached_size.width;
48        let delta_h = self.cached_size.height - self.child_cached_size.height;
49        self.child_offset = Point::new(self.alignment.x * delta_w, self.alignment.y * delta_h);
50        self.cached_size
51    }
52
53    fn content_size(&self) -> Size {
54        self.cached_size
55    }
56
57    fn paint(&self, offset: Point, painter: &mut PaintList) {
58        if let Some(child) = &self.child {
59            child.borrow().paint(Point::new(offset.x + self.child_offset.x, offset.y + self.child_offset.y), painter);
60        }
61    }
62
63    fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
64        self.child.as_ref().and_then(|c| {
65            c.borrow().hit_test(position, Point::new(offset.x + self.child_offset.x, offset.y + self.child_offset.y))
66        })
67    }
68
69    fn propagate_element_ids(&mut self, child_ids: &[ElementId], stateful_ros: &mut [SharedRO]) {
70        if let Some(child) = &mut self.child {
71            if let Some(&cid) = child_ids.first() {
72                if let Some(new_ro) = stateful_ros.first_mut() {
73                    *child = new_ro.clone();
74                }
75                child.borrow_mut().set_element_id(cid);
76            }
77        }
78    }
79
80    fn child_slots(&self) -> Vec<(Point, SharedRO)> {
81        self.child.as_ref().map(|c| vec![(self.child_offset, c.clone())]).unwrap_or_default()
82    }
83
84    fn for_each_child(&self, f: &mut dyn FnMut(Point, &SharedRO)) {
85        if let Some(c) = &self.child {
86            f(self.child_offset, c);
87        }
88    }
89
90    fn children_count(&self) -> usize {
91        if self.child.is_some() {
92            1
93        } else {
94            0
95        }
96    }
97}
98
99/// UnconstrainedBox(child 不受约束,允许溢出)
100#[derive(Debug)]
101pub struct UnconstrainedBoxWidget {
102    pub alignment: Alignment,
103    pub child: Option<WidgetNode>,
104}
105
106impl UnconstrainedBoxWidget {
107    pub fn new(child: impl Widget) -> Self {
108        Self { alignment: Alignment::TOP_LEFT, child: Some(WidgetNode::new(child)) }
109    }
110
111    pub fn align(mut self, alignment: Alignment) -> Self {
112        self.alignment = alignment;
113        self
114    }
115}
116
117impl Widget for UnconstrainedBoxWidget {
118    fn as_any(&self) -> &dyn std::any::Any {
119        self
120    }
121
122    fn is_equivalent(&self, old: &dyn Widget) -> bool {
123        old.as_any().downcast_ref::<UnconstrainedBoxWidget>().is_some_and(|o| {
124            self.alignment == o.alignment && crate::widget::optional_child_equivalent(&self.child, &o.child)
125        })
126    }
127
128    fn create_render_object(&self) -> Box<dyn RenderObject> {
129        let child_ro = match &self.child {
130            Some(c) => c.0.create_render_object(),
131            None => Box::new(RRectRenderObject::new(Size::ZERO, Color::TRANSPARENT, 0.0)),
132        };
133        Box::new(UnconstrainedBoxRenderObject::new(self.alignment, Some(child_ro)))
134    }
135
136    fn children(&self) -> Vec<WidgetNode> {
137        match &self.child {
138            Some(c) => vec![c.clone()],
139            None => vec![],
140        }
141    }
142}