Skip to main content

mgui_core/layout/
align.rs

1//! Align — 按 Alignment 定位单 child,可选 width/heightFactor
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
9use super::alignment::Alignment;
10
11/// Align RenderObject — 按 Alignment 定位 child;可选 width/heightFactor
12pub struct AlignRenderObject {
13    pub alignment: Alignment,
14    pub width_factor: Option<f32>,
15    pub height_factor: Option<f32>,
16    child: Option<SharedRO>,
17    cached_size: Size,
18    child_cached_size: Size,
19    pub child_offset: Point,
20}
21
22impl AlignRenderObject {
23    pub fn new(
24        alignment: Alignment,
25        width_factor: Option<f32>,
26        height_factor: Option<f32>,
27        child: Option<Box<dyn RenderObject>>,
28    ) -> Self {
29        Self {
30            alignment,
31            width_factor,
32            height_factor,
33            child: child.map(make_ro_shared),
34            cached_size: Size::ZERO,
35            child_cached_size: Size::ZERO,
36            child_offset: Point::ZERO,
37        }
38    }
39}
40
41impl RenderObject for AlignRenderObject {
42    fn layout(&mut self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size {
43        // 1. 用 loosed 约束测 child(Align 不强制 child 大小)
44        let child_constraints = BoxConstraints {
45            min_width: 0.0,
46            max_width: constraints.max_width,
47            min_height: 0.0,
48            max_height: constraints.max_height,
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        // 2. 算 self_size(per-axis):
54        //    单轴 factor 是 Some → 该轴 self_size = child_size * factor
55        //    单轴 constraints tight → self_size = constraints tight 值
56        //    否则 → constrain(child_size, constraints)
57        let child_size = self.child_cached_size;
58        let self_size = if constraints.is_tight() {
59            Size::new(constraints.min_width, constraints.min_height)
60        } else {
61            let w = if let Some(wf) = self.width_factor {
62                child_size.width * wf
63            } else {
64                child_size.width.clamp(constraints.min_width, constraints.max_width)
65            };
66            let h = if let Some(hf) = self.height_factor {
67                child_size.height * hf
68            } else {
69                child_size.height.clamp(constraints.min_height, constraints.max_height)
70            };
71            Size::new(w, h)
72        };
73        self.cached_size = self_size;
74
75        // 3. child_offset = alignment * (self_size - child_size)
76        //    alignment (0..1) → 实际偏移比例(0 左/上, 0.5 中心, 1 右/下)
77        let delta_w = (self_size.width - child_size.width).max(0.0);
78        let delta_h = (self_size.height - child_size.height).max(0.0);
79        self.child_offset = Point::new(self.alignment.x * delta_w, self.alignment.y * delta_h);
80
81        self_size
82    }
83
84    fn content_size(&self) -> Size {
85        self.cached_size
86    }
87
88    fn paint(&self, offset: Point, painter: &mut PaintList) {
89        if let Some(child) = &self.child {
90            child.borrow().paint(Point::new(offset.x + self.child_offset.x, offset.y + self.child_offset.y), painter);
91        }
92    }
93
94    fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
95        if let Some(child) = &self.child {
96            child
97                .borrow()
98                .hit_test(position, Point::new(offset.x + self.child_offset.x, offset.y + self.child_offset.y))
99        } else {
100            None
101        }
102    }
103
104    fn propagate_element_ids(&mut self, child_ids: &[ElementId], stateful_ros: &mut [SharedRO]) {
105        if let Some(child) = &mut self.child {
106            if let Some(&cid) = child_ids.first() {
107                if let Some(new_ro) = stateful_ros.first_mut() {
108                    *child = new_ro.clone();
109                }
110                child.borrow_mut().set_element_id(cid);
111            }
112        }
113    }
114
115    fn child_slots(&self) -> Vec<(Point, SharedRO)> {
116        self.child.as_ref().map(|c| vec![(self.child_offset, c.clone())]).unwrap_or_default()
117    }
118
119    fn for_each_child(&self, f: &mut dyn FnMut(Point, &SharedRO)) {
120        if let Some(c) = &self.child {
121            f(self.child_offset, c);
122        }
123    }
124
125    fn children_count(&self) -> usize {
126        if self.child.is_some() {
127            1
128        } else {
129            0
130        }
131    }
132}
133
134/// Align(子节点对齐)
135///
136/// ```ignore
137/// Align::new(Alignment::CENTER)          // 居中
138///      .width_factor(1.0)                // self_width = child_width * 1.0
139///      .height_factor(1.0)               // self_height = child_height * 1.0
140///      .child(button)
141/// ```
142#[derive(Debug)]
143pub struct AlignWidget {
144    pub alignment: Alignment,
145    pub width_factor: Option<f32>,
146    pub height_factor: Option<f32>,
147    pub child: Option<WidgetNode>,
148}
149
150impl AlignWidget {
151    pub fn new(alignment: Alignment, child: impl Widget) -> Self {
152        Self { alignment, width_factor: None, height_factor: None, child: Some(WidgetNode::new(child)) }
153    }
154
155    pub fn width_factor(mut self, f: f32) -> Self {
156        self.width_factor = Some(f);
157        self
158    }
159    pub fn height_factor(mut self, f: f32) -> Self {
160        self.height_factor = Some(f);
161        self
162    }
163
164    pub fn center(child: impl Widget) -> Self {
165        Self::new(Alignment::CENTER, child)
166    }
167    pub fn top_left(child: impl Widget) -> Self {
168        Self::new(Alignment::TOP_LEFT, child)
169    }
170    pub fn top_center(child: impl Widget) -> Self {
171        Self::new(Alignment::TOP_CENTER, child)
172    }
173    pub fn bottom_center(child: impl Widget) -> Self {
174        Self::new(Alignment::BOTTOM_CENTER, child)
175    }
176}
177
178impl Widget for AlignWidget {
179    fn as_any(&self) -> &dyn std::any::Any {
180        self
181    }
182
183    fn create_render_object(&self) -> Box<dyn RenderObject> {
184        let child_ro = match &self.child {
185            Some(c) => c.0.create_render_object(),
186            None => Box::new(RRectRenderObject::new(Size::ZERO, Color::TRANSPARENT, 0.0)),
187        };
188        Box::new(AlignRenderObject::new(self.alignment, self.width_factor, self.height_factor, Some(child_ro)))
189    }
190
191    fn children(&self) -> Vec<WidgetNode> {
192        match &self.child {
193            Some(c) => vec![c.clone()],
194            None => vec![],
195        }
196    }
197
198    fn is_equivalent(&self, old: &dyn Widget) -> bool {
199        let Some(o) = old.as_any().downcast_ref::<AlignWidget>() else {
200            return false;
201        };
202        self.alignment == o.alignment
203            && self.width_factor == o.width_factor
204            && self.height_factor == o.height_factor
205            && crate::widget::optional_child_equivalent(&self.child, &o.child)
206    }
207}
208
209/// Center(Align::CENTER 语法糖)
210#[derive(Debug)]
211pub struct CenterWidget {
212    pub child: Option<WidgetNode>,
213}
214
215impl CenterWidget {
216    pub fn new(child: impl Widget) -> Self {
217        Self { child: Some(WidgetNode::new(child)) }
218    }
219}
220
221impl Widget for CenterWidget {
222    fn as_any(&self) -> &dyn std::any::Any {
223        self
224    }
225
226    fn create_render_object(&self) -> Box<dyn RenderObject> {
227        let child_ro = match &self.child {
228            Some(c) => c.0.create_render_object(),
229            None => Box::new(RRectRenderObject::new(Size::ZERO, Color::TRANSPARENT, 0.0)),
230        };
231        Box::new(AlignRenderObject::new(Alignment::CENTER, None, None, Some(child_ro)))
232    }
233
234    fn children(&self) -> Vec<WidgetNode> {
235        match &self.child {
236            Some(c) => vec![c.clone()],
237            None => vec![],
238        }
239    }
240
241    fn is_equivalent(&self, old: &dyn Widget) -> bool {
242        old.as_any()
243            .downcast_ref::<CenterWidget>()
244            .is_some_and(|o| crate::widget::optional_child_equivalent(&self.child, &o.child))
245    }
246
247    fn semantics(&self) -> Option<crate::semantics::WidgetSemantics> {
248        use crate::semantics::{SemanticsRole, WidgetSemantics};
249        Some(WidgetSemantics::new(SemanticsRole::Container).non_focusable())
250    }
251}