Skip to main content

mgui_core/layout/
expanded.rs

1//! Expanded / Flexible — Flex 容器子节点的弹性元数据包装器
2//!
3//! 二者**不是**独立的布局算法:自身是一个**透传 RO**(`PassthroughRenderObject`),
4//! 布局/绘制/命中全部原样交给 child。真正的 grow/basis 语义通过
5//! `Widget::parent_data()` 暴露给父级 `FlexWidget`(在 `push`/`push_node` 时转成
6//! `FlexItem` 消费),core 层不感知 flex 布局细节。
7//!
8//! - `Expanded(flex)`  = `Flexible(flex, FlexFit::Tight)`(basis=0,占满分配空间)
9//! - `Flexible(flex)`  = 默认 `FlexFit::Loose`(自然尺寸 + 弹性增长,可小于分配空间)
10//!
11//! **只在 `mgui_layout::FlexWidget` 下生效**:`ParentData::Flex` 的消费方只有
12//! Flex 容器;放进 `ColumnWidget` 等简单容器时包装器会退化为普通透传节点
13//! (且 debug 构建会断言失败,避免静默失效)。
14
15use crate::id::ElementId;
16use crate::paint::PaintList;
17use crate::render_object::{make_ro_shared, BoxConstraints, LayoutContext, RRectRenderObject, RenderObject, SharedRO};
18use crate::widget::{Widget, WidgetNode};
19use crate::{Color, Point, Size};
20
21use super::ParentData;
22
23/// Flex 子节点的适配方式
24#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
25pub enum FlexFit {
26    /// 自然尺寸(可小于分配空间)—— Flexible 默认
27    #[default]
28    Loose,
29    /// 强制填满分配空间 —— Expanded
30    Tight,
31}
32
33/// 透传 RO —— 布局/绘制/命中/子槽全部原样转交 child,自身不改变约束或尺寸。
34///
35/// 用途:`Expanded`/`Flexible` 等仅携带元数据、不改变渲染语义的包装器需要一个
36/// 携带 child 的 RO(框架约定「每 Widget 一个 Element + 一个 RO」)。
37pub struct PassthroughRenderObject {
38    child: Option<SharedRO>,
39    cached_size: Size,
40}
41
42impl PassthroughRenderObject {
43    pub fn new(child: Option<Box<dyn RenderObject>>) -> Self {
44        Self { child: child.map(make_ro_shared), cached_size: Size::ZERO }
45    }
46}
47
48impl RenderObject for PassthroughRenderObject {
49    fn layout(&mut self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size {
50        self.cached_size =
51            if let Some(child) = &mut self.child { child.layout_cached(constraints, ctx) } else { Size::ZERO };
52        self.cached_size
53    }
54
55    fn paint(&self, offset: Point, painter: &mut PaintList) {
56        if let Some(child) = &self.child {
57            child.borrow().paint(offset, painter);
58        }
59    }
60
61    fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
62        self.child.as_ref().and_then(|c| c.borrow().hit_test(position, offset))
63    }
64
65    fn content_size(&self) -> Size {
66        self.cached_size
67    }
68
69    fn propagate_element_ids(&mut self, child_ids: &[ElementId], stateful_ros: &mut [SharedRO]) {
70        if let (Some(child), Some(&cid)) = (self.child.as_mut(), child_ids.first()) {
71            if let Some(new_ro) = stateful_ros.first_mut() {
72                *child = new_ro.clone();
73            }
74            child.borrow_mut().set_element_id(cid);
75        }
76    }
77
78    fn child_slots(&self) -> Vec<(Point, SharedRO)> {
79        self.child.as_ref().map(|c| vec![(Point::ZERO, c.clone())]).unwrap_or_default()
80    }
81
82    fn for_each_child(&self, f: &mut dyn FnMut(Point, &SharedRO)) {
83        if let Some(c) = &self.child {
84            f(Point::ZERO, c);
85        }
86    }
87
88    fn children_count(&self) -> usize {
89        if self.child.is_some() {
90            1
91        } else {
92            0
93        }
94    }
95}
96
97/// 构造包装器的透传 RO(child 为空时用零尺寸叶子兜底)
98fn passthrough_ro(child: &Option<WidgetNode>) -> Box<dyn RenderObject> {
99    let child_ro = match child {
100        Some(c) => c.0.create_render_object(),
101        None => Box::new(RRectRenderObject::new(Size::ZERO, Color::TRANSPARENT, 0.0)),
102    };
103    Box::new(PassthroughRenderObject::new(Some(child_ro)))
104}
105
106/// Expanded —— Flex 里占满剩余空间(grow=flex,basis=0,等价 `Flexible` + `Tight`)
107#[derive(Debug)]
108pub struct ExpandedWidget {
109    pub flex: f32,
110    pub child: Option<WidgetNode>,
111}
112
113impl ExpandedWidget {
114    pub fn new(child: impl Widget) -> Self {
115        Self { flex: 1.0, child: Some(WidgetNode::new(child)) }
116    }
117
118    pub fn flex(mut self, flex: f32) -> Self {
119        self.flex = flex;
120        self
121    }
122}
123
124impl Widget for ExpandedWidget {
125    fn as_any(&self) -> &dyn std::any::Any {
126        self
127    }
128
129    fn create_render_object(&self) -> Box<dyn RenderObject> {
130        passthrough_ro(&self.child)
131    }
132
133    fn children(&self) -> Vec<WidgetNode> {
134        match &self.child {
135            Some(c) => vec![c.clone()],
136            None => vec![],
137        }
138    }
139
140    fn parent_data(&self) -> Option<ParentData> {
141        Some(ParentData::Flex { grow: self.flex, basis: Some(0.0), stretch: false })
142    }
143
144    fn is_equivalent(&self, old: &dyn Widget) -> bool {
145        old.as_any()
146            .downcast_ref::<ExpandedWidget>()
147            .is_some_and(|o| self.flex == o.flex && crate::widget::optional_child_equivalent(&self.child, &o.child))
148    }
149}
150
151/// Flexible —— Flex 里弹性增长(默认 `FlexFit::Loose`:自然尺寸 + 弹性填充)
152#[derive(Debug)]
153pub struct FlexibleWidget {
154    pub flex: f32,
155    pub fit: FlexFit,
156    pub child: Option<WidgetNode>,
157}
158
159impl FlexibleWidget {
160    /// 宽松适配(自然尺寸 + 弹性增长)
161    pub fn new(child: impl Widget) -> Self {
162        Self { flex: 1.0, fit: FlexFit::Loose, child: Some(WidgetNode::new(child)) }
163    }
164
165    /// 紧致适配(强制填满分配空间,等价 `Expanded`)
166    pub fn tight(child: impl Widget) -> Self {
167        Self { flex: 1.0, fit: FlexFit::Tight, child: Some(WidgetNode::new(child)) }
168    }
169
170    pub fn flex(mut self, flex: f32) -> Self {
171        self.flex = flex;
172        self
173    }
174
175    pub fn fit(mut self, fit: FlexFit) -> Self {
176        self.fit = fit;
177        self
178    }
179}
180
181impl Widget for FlexibleWidget {
182    fn as_any(&self) -> &dyn std::any::Any {
183        self
184    }
185
186    fn is_equivalent(&self, old: &dyn Widget) -> bool {
187        old.as_any().downcast_ref::<FlexibleWidget>().is_some_and(|o| {
188            self.flex == o.flex && self.fit == o.fit && crate::widget::optional_child_equivalent(&self.child, &o.child)
189        })
190    }
191
192    fn create_render_object(&self) -> Box<dyn RenderObject> {
193        passthrough_ro(&self.child)
194    }
195
196    fn children(&self) -> Vec<WidgetNode> {
197        match &self.child {
198            Some(c) => vec![c.clone()],
199            None => vec![],
200        }
201    }
202
203    fn parent_data(&self) -> Option<ParentData> {
204        // Tight = basis 0(占满分配空间);Loose = basis None(按 child 测量尺寸起算)
205        let basis = if self.fit == FlexFit::Tight { Some(0.0) } else { None };
206        Some(ParentData::Flex { grow: self.flex, basis, stretch: false })
207    }
208}