Skip to main content

mgui_core/layout/
decorated_box.rs

1//! DecoratedBox / BoxDecoration — 背景色 + 圆角 + 边框 + 阴影
2//!
3//! `BoxDecoration` 是装饰描述数据;`DecoratedBoxRenderObject` 按层叠顺序绘制:
4//! 阴影(GPU SDF blur)→ 背景色 → 边框环 → child。
5//! 无 stroke 绘制原语,边框用「外圈实心 + 内圈填背景色」模拟描边(与 Button ghost / BorderRO 同原理)。
6
7use crate::id::ElementId;
8use crate::paint::PaintList;
9use crate::render_object::{
10    make_ro_shared, Border, BoxConstraints, LayoutContext, RRectRenderObject, RenderObject, SharedRO,
11};
12use crate::widget::{Widget, WidgetNode};
13use crate::{Color, Point, Rect, Size};
14
15/// 盒子阴影规格(复用 `PaintList::box_shadow` 的 GPU SDF blur 通道)
16#[derive(Clone, Copy, Debug, PartialEq)]
17pub struct BoxShadowSpec {
18    pub offset: Point,
19    pub blur_radius: f32,
20    pub spread: f32,
21    pub color: Color,
22}
23
24impl BoxShadowSpec {
25    pub fn new(offset: Point, blur_radius: f32, color: Color) -> Self {
26        Self { offset, blur_radius, spread: 0.0, color }
27    }
28
29    pub fn spread(mut self, spread: f32) -> Self {
30        self.spread = spread;
31        self
32    }
33}
34
35/// 装饰描述(颜色 / 圆角 / 边框 / 阴影)
36#[derive(Clone, Copy, Debug, Default, PartialEq)]
37pub struct BoxDecoration {
38    pub color: Option<Color>,
39    pub radius: f32,
40    pub border: Option<Border>,
41    pub shadow: Option<BoxShadowSpec>,
42}
43
44impl BoxDecoration {
45    pub fn new() -> Self {
46        Self::default()
47    }
48
49    pub fn color(mut self, color: Color) -> Self {
50        self.color = Some(color);
51        self
52    }
53
54    pub fn radius(mut self, radius: f32) -> Self {
55        self.radius = radius;
56        self
57    }
58
59    pub fn border(mut self, border: Border) -> Self {
60        self.border = Some(border);
61        self
62    }
63
64    pub fn shadow(mut self, shadow: BoxShadowSpec) -> Self {
65        self.shadow = Some(shadow);
66        self
67    }
68}
69
70/// DecoratedBox RenderObject
71pub struct DecoratedBoxRenderObject {
72    pub decoration: BoxDecoration,
73    child: Option<SharedRO>,
74    cached_size: Size,
75    child_cached_size: Size,
76}
77
78impl DecoratedBoxRenderObject {
79    pub fn new(decoration: BoxDecoration, child: Option<Box<dyn RenderObject>>) -> Self {
80        Self { decoration, child: child.map(make_ro_shared), cached_size: Size::ZERO, child_cached_size: Size::ZERO }
81    }
82}
83
84impl RenderObject for DecoratedBoxRenderObject {
85    fn layout(&mut self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size {
86        // 透传约束(装饰不改变 child 布局),自身尺寸 = child 尺寸
87        self.child_cached_size =
88            if let Some(child) = &mut self.child { child.layout_cached(constraints, ctx) } else { Size::ZERO };
89        self.cached_size = constraints.constrain(self.child_cached_size);
90        self.cached_size
91    }
92
93    fn content_size(&self) -> Size {
94        self.cached_size
95    }
96
97    fn paint(&self, offset: Point, painter: &mut PaintList) {
98        let rect = Rect::new(offset.x, offset.y, self.cached_size.width, self.cached_size.height);
99        let radius = self.decoration.radius;
100
101        // 1. 阴影(最底层)
102        if let Some(sh) = self.decoration.shadow {
103            painter.box_shadow(rect, sh.offset, sh.blur_radius, sh.spread, sh.color, radius);
104        }
105        // 2. 背景色
106        if let Some(color) = self.decoration.color {
107            painter.rounded_rect(rect, color, radius);
108        }
109        // 3. 边框环(外圈实心 + 内圈填背景色)
110        if let Some(border) = self.decoration.border {
111            let inner_bg = self.decoration.color.unwrap_or(Color::TRANSPARENT);
112            border.paint_ring(rect, inner_bg, painter);
113        }
114        // 4. child
115        if let Some(child) = &self.child {
116            child.borrow().paint(offset, painter);
117        }
118    }
119
120    fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
121        self.child.as_ref().and_then(|c| c.borrow().hit_test(position, offset))
122    }
123
124    fn propagate_element_ids(&mut self, child_ids: &[ElementId], stateful_ros: &mut [SharedRO]) {
125        if let Some(child) = &mut self.child {
126            if let Some(&cid) = child_ids.first() {
127                if let Some(new_ro) = stateful_ros.first_mut() {
128                    *child = new_ro.clone();
129                }
130                child.borrow_mut().set_element_id(cid);
131            }
132        }
133    }
134
135    fn child_slots(&self) -> Vec<(Point, SharedRO)> {
136        self.child.as_ref().map(|c| vec![(Point::ZERO, c.clone())]).unwrap_or_default()
137    }
138
139    fn for_each_child(&self, f: &mut dyn FnMut(Point, &SharedRO)) {
140        if let Some(c) = &self.child {
141            f(Point::ZERO, c);
142        }
143    }
144
145    fn children_count(&self) -> usize {
146        if self.child.is_some() {
147            1
148        } else {
149            0
150        }
151    }
152}
153
154/// DecoratedBox(给 child 加背景装饰)
155#[derive(Debug)]
156pub struct DecoratedBoxWidget {
157    pub decoration: BoxDecoration,
158    pub child: Option<WidgetNode>,
159}
160
161impl DecoratedBoxWidget {
162    pub fn new(decoration: BoxDecoration, child: impl Widget) -> Self {
163        Self { decoration, child: Some(WidgetNode::new(child)) }
164    }
165}
166
167impl Widget for DecoratedBoxWidget {
168    fn as_any(&self) -> &dyn std::any::Any {
169        self
170    }
171
172    fn is_equivalent(&self, old: &dyn Widget) -> bool {
173        old.as_any().downcast_ref::<DecoratedBoxWidget>().is_some_and(|o| {
174            self.decoration == o.decoration && crate::widget::optional_child_equivalent(&self.child, &o.child)
175        })
176    }
177
178    fn create_render_object(&self) -> Box<dyn RenderObject> {
179        let child_ro = match &self.child {
180            Some(c) => c.0.create_render_object(),
181            None => Box::new(RRectRenderObject::new(Size::ZERO, Color::TRANSPARENT, 0.0)),
182        };
183        Box::new(DecoratedBoxRenderObject::new(self.decoration, Some(child_ro)))
184    }
185
186    fn children(&self) -> Vec<WidgetNode> {
187        match &self.child {
188            Some(c) => vec![c.clone()],
189            None => vec![],
190        }
191    }
192}