Skip to main content

mgui_core/layout/
aspect_ratio.rs

1//! AspectRatio — 强制宽高比的单 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/// AspectRatio RenderObject — 强制 child 宽高比
10///
11/// `ratio = width / height`。在父约束下选最大的符合 ratio 的 size。
12/// 优先级:width 有界 → height = width / ratio;height 有界 → width = height * ratio。
13pub struct AspectRatioRenderObject {
14    pub aspect_ratio: f32,
15    child: Option<SharedRO>,
16    cached_size: Size,
17}
18
19impl AspectRatioRenderObject {
20    pub fn new(ratio: f32, child: Option<Box<dyn RenderObject>>) -> Self {
21        Self { aspect_ratio: ratio, child: child.map(make_ro_shared), cached_size: Size::ZERO }
22    }
23
24    /// 根据约束算符合 ratio 的最大 size
25    fn resolve_size(&self, constraints: BoxConstraints) -> Size {
26        assert!(self.aspect_ratio > 0.0, "aspect_ratio must be > 0");
27
28        // 决定 self_size:在 constraints 内选最大的符合 ratio 的 size
29        let result = if constraints.is_bounded_width() && constraints.is_bounded_height() {
30            // 两边都有界 → 取更小的方向
31            let by_width = Size::new(constraints.max_width, constraints.max_width / self.aspect_ratio);
32            let by_height = Size::new(constraints.max_height * self.aspect_ratio, constraints.max_height);
33            if by_width.height <= constraints.max_height && by_height.width <= constraints.max_width {
34                // 都 fit — 取更大的那个(面积更大)
35                let by_w_area = by_width.width * by_width.height;
36                let by_h_area = by_height.width * by_height.height;
37                if by_w_area >= by_h_area {
38                    by_width
39                } else {
40                    by_height
41                }
42            } else if by_width.height <= constraints.max_height {
43                by_width
44            } else {
45                by_height
46            }
47        } else if constraints.is_bounded_width() {
48            Size::new(constraints.max_width, constraints.max_width / self.aspect_ratio)
49        } else if constraints.is_bounded_height() {
50            Size::new(constraints.max_height * self.aspect_ratio, constraints.max_height)
51        } else {
52            // 都无界 → 默认 0
53            Size::ZERO
54        };
55
56        // 夹紧到约束内(防 min 约束)
57        constraints.constrain(result)
58    }
59}
60
61impl RenderObject for AspectRatioRenderObject {
62    fn layout(&mut self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size {
63        let self_size = self.resolve_size(constraints);
64        // tight child 到 self_size
65        let child_constraints = BoxConstraints::tight(self_size);
66        if let Some(child) = &mut self.child {
67            child.layout_cached(child_constraints, ctx);
68        }
69        self.cached_size = self_size;
70        self_size
71    }
72
73    fn content_size(&self) -> Size {
74        self.cached_size
75    }
76
77    fn paint(&self, offset: Point, painter: &mut PaintList) {
78        if let Some(child) = &self.child {
79            child.borrow().paint(offset, painter);
80        }
81    }
82
83    fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
84        self.child.as_ref().and_then(|c| c.borrow().hit_test(position, offset))
85    }
86
87    fn propagate_element_ids(&mut self, child_ids: &[ElementId], stateful_ros: &mut [SharedRO]) {
88        if let Some(child) = &mut self.child {
89            if let Some(&cid) = child_ids.first() {
90                if let Some(new_ro) = stateful_ros.first_mut() {
91                    *child = new_ro.clone();
92                }
93                child.borrow_mut().set_element_id(cid);
94            }
95        }
96    }
97
98    fn child_slots(&self) -> Vec<(Point, SharedRO)> {
99        self.child.as_ref().map(|c| vec![(Point::ZERO, c.clone())]).unwrap_or_default()
100    }
101
102    fn for_each_child(&self, f: &mut dyn FnMut(Point, &SharedRO)) {
103        if let Some(c) = &self.child {
104            f(Point::ZERO, c);
105        }
106    }
107
108    fn children_count(&self) -> usize {
109        if self.child.is_some() {
110            1
111        } else {
112            0
113        }
114    }
115}
116
117/// AspectRatio(强制宽高比)
118///
119/// ```ignore
120/// AspectRatio::new(16.0 / 9.0).child(video_player)
121/// ```
122#[derive(Debug)]
123pub struct AspectRatioWidget {
124    pub aspect_ratio: f32,
125    pub child: Option<WidgetNode>,
126}
127
128impl AspectRatioWidget {
129    pub fn new(ratio: f32, child: impl Widget) -> Self {
130        assert!(ratio > 0.0, "aspect_ratio must be > 0");
131        Self { aspect_ratio: ratio, child: Some(WidgetNode::new(child)) }
132    }
133
134    /// 正方形(1:1)
135    pub fn square(child: impl Widget) -> Self {
136        Self::new(1.0, child)
137    }
138}
139
140impl Widget for AspectRatioWidget {
141    fn as_any(&self) -> &dyn std::any::Any {
142        self
143    }
144
145    fn is_equivalent(&self, old: &dyn Widget) -> bool {
146        old.as_any().downcast_ref::<AspectRatioWidget>().is_some_and(|o| {
147            self.aspect_ratio == o.aspect_ratio && crate::widget::optional_child_equivalent(&self.child, &o.child)
148        })
149    }
150
151    fn create_render_object(&self) -> Box<dyn RenderObject> {
152        let child_ro = match &self.child {
153            Some(c) => c.0.create_render_object(),
154            None => Box::new(RRectRenderObject::new(Size::ZERO, Color::TRANSPARENT, 0.0)),
155        };
156        Box::new(AspectRatioRenderObject::new(self.aspect_ratio, Some(child_ro)))
157    }
158
159    fn children(&self) -> Vec<WidgetNode> {
160        match &self.child {
161            Some(c) => vec![c.clone()],
162            None => vec![],
163        }
164    }
165}