mgui_core/render_object/
margin.rs1use super::*;
2
3pub struct MarginRenderObject {
12 pub margin: EdgeInsets,
13 child: Option<SharedRO>,
14 cached_size: Size,
15 child_cached_size: Size,
16}
17
18impl MarginRenderObject {
19 pub fn new(margin: f32, child: impl RenderObject + 'static) -> Self {
20 Self::new_insets(EdgeInsets::all(margin), child)
21 }
22
23 pub fn new_insets(margin: EdgeInsets, child: impl RenderObject + 'static) -> Self {
24 Self {
25 margin,
26 child: Some(make_ro_shared(Box::new(child))),
27 cached_size: Size::ZERO,
28 child_cached_size: Size::ZERO,
29 }
30 }
31
32 pub fn empty(margin: EdgeInsets) -> Self {
33 Self { margin, child: None, cached_size: Size::ZERO, child_cached_size: Size::ZERO }
34 }
35}
36
37impl RenderObject for MarginRenderObject {
38 fn layout(&mut self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size {
39 self.child_cached_size =
41 if let Some(child) = &mut self.child { child.layout_cached(constraints, ctx) } else { Size::ZERO };
42 let m = &self.margin;
43 self.cached_size =
44 Size::new(self.child_cached_size.width + m.horizontal(), self.child_cached_size.height + m.vertical());
45 constraints.constrain(self.cached_size)
46 }
47
48 fn content_size(&self) -> Size {
49 self.cached_size
50 }
51
52 fn paint(&self, offset: Point, painter: &mut PaintList) {
53 if let Some(child) = &self.child {
54 let m = &self.margin;
55 child.borrow().paint(Point::new(offset.x + m.left, offset.y + m.top), painter);
56 }
57 }
58
59 fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
60 if let Some(child) = &self.child {
61 let m = &self.margin;
62 return child.borrow().hit_test(position, Point::new(offset.x + m.left, offset.y + m.top));
63 }
64 None
65 }
66
67 fn propagate_element_ids(&mut self, child_ids: &[ElementId], stateful_ros: &mut [SharedRO]) {
68 if let Some(child) = &mut self.child {
69 if let Some(&cid) = child_ids.first() {
70 if let Some(new_ro) = stateful_ros.first_mut() {
71 *child = new_ro.clone();
72 }
73 child.borrow_mut().set_element_id(cid);
74 }
75 }
76 }
77
78 fn child_slots(&self) -> Vec<(Point, SharedRO)> {
79 self.child
80 .as_ref()
81 .map(|c| vec![(Point::new(self.margin.left, self.margin.top), c.clone())])
82 .unwrap_or_default()
83 }
84
85 fn for_each_child(&self, f: &mut dyn FnMut(Point, &SharedRO)) {
86 if let Some(c) = &self.child {
87 f(Point::new(self.margin.left, self.margin.top), c);
88 }
89 }
90
91 fn children_count(&self) -> usize {
92 if self.child.is_some() {
93 1
94 } else {
95 0
96 }
97 }
98}