Skip to main content

mgui_core/layout/
sized_box.rs

1//! SizedBox — 固定尺寸或宽/高单边强制的单 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/// SizedBox RenderObject
10///
11/// 语义:
12/// - `width=None, height=None` → child 透传约束(等价于 Padding 0)
13/// - `width=Some(w)` → 强制 child width=w(用 tight 约束);height 取 child height
14/// - `height=Some(h)` → 强制 child height=h;height 取 child height;width 取 child width
15/// - 两者都 Some → tight(w, h)
16pub struct SizedBoxRenderObject {
17    pub width: Option<f32>,
18    pub height: Option<f32>,
19    child: Option<SharedRO>,
20    cached_size: Size,
21    child_cached_size: Size,
22}
23
24impl SizedBoxRenderObject {
25    pub fn new(width: Option<f32>, height: Option<f32>, child: Option<Box<dyn RenderObject>>) -> Self {
26        Self { width, height, child: child.map(make_ro_shared), cached_size: Size::ZERO, child_cached_size: Size::ZERO }
27    }
28}
29
30impl RenderObject for SizedBoxRenderObject {
31    fn layout(&mut self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size {
32        // 构造传给 child 的约束
33        let child_constraints = match (self.width, self.height) {
34            (Some(w), Some(h)) => BoxConstraints::tight(Size::new(w, h)),
35            (Some(w), None) => BoxConstraints {
36                min_width: w,
37                max_width: w,
38                min_height: constraints.min_height,
39                max_height: constraints.max_height,
40            },
41            (None, Some(h)) => BoxConstraints {
42                min_width: constraints.min_width,
43                max_width: constraints.max_width,
44                min_height: h,
45                max_height: h,
46            },
47            (None, None) => constraints,
48        };
49
50        self.child_cached_size =
51            if let Some(child) = &mut self.child { child.layout_cached(child_constraints, ctx) } else { Size::ZERO };
52
53        let w = self.width.unwrap_or(self.child_cached_size.width);
54        let h = self.height.unwrap_or(self.child_cached_size.height);
55        self.cached_size = Size::new(w, h);
56        constraints.constrain(self.cached_size)
57    }
58
59    fn content_size(&self) -> Size {
60        self.cached_size
61    }
62
63    fn paint(&self, offset: Point, painter: &mut PaintList) {
64        if let Some(child) = &self.child {
65            child.borrow().paint(offset, painter);
66        }
67    }
68
69    fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
70        if let Some(child) = &self.child {
71            child.borrow().hit_test(position, offset)
72        } else {
73            None
74        }
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/// SizedBox(固定尺寸或宽/高单边强制)
108#[derive(Debug)]
109pub struct SizedBoxWidget {
110    pub width: Option<f32>,
111    pub height: Option<f32>,
112    pub child: Option<WidgetNode>,
113}
114
115impl SizedBoxWidget {
116    pub fn new(width: Option<f32>, height: Option<f32>, child: impl Widget) -> Self {
117        Self { width, height, child: Some(WidgetNode::new(child)) }
118    }
119
120    pub fn sized(width: f32, height: f32, child: impl Widget) -> Self {
121        Self::new(Some(width), Some(height), child)
122    }
123
124    pub fn width(w: f32, child: impl Widget) -> Self {
125        Self::new(Some(w), None, child)
126    }
127
128    pub fn height(h: f32, child: impl Widget) -> Self {
129        Self::new(None, Some(h), child)
130    }
131
132    /// 让 child 填满父约束(passthrough,等价于 Flutter 的 SizedBox.expand)
133    pub fn expand(child: impl Widget) -> Self {
134        Self::new(None, None, child)
135    }
136}
137
138impl Widget for SizedBoxWidget {
139    fn as_any(&self) -> &dyn std::any::Any {
140        self
141    }
142
143    fn create_render_object(&self) -> Box<dyn RenderObject> {
144        let child_ro = match &self.child {
145            Some(c) => c.0.create_render_object(),
146            None => Box::new(RRectRenderObject::new(Size::ZERO, Color::TRANSPARENT, 0.0)),
147        };
148        Box::new(SizedBoxRenderObject::new(self.width, self.height, Some(child_ro)))
149    }
150
151    fn children(&self) -> Vec<WidgetNode> {
152        match &self.child {
153            Some(c) => vec![c.clone()],
154            None => vec![],
155        }
156    }
157
158    fn is_equivalent(&self, old: &dyn Widget) -> bool {
159        let Some(o) = old.as_any().downcast_ref::<SizedBoxWidget>() else {
160            return false;
161        };
162        self.width == o.width
163            && self.height == o.height
164            && crate::widget::optional_child_equivalent(&self.child, &o.child)
165    }
166}