custom_tree_owned_unsafe/
custom_tree_owned_unsafe.rs1mod common {
2 pub mod image;
3 pub mod text;
4}
5
6use common::image::{image_measure_function, ImageContext};
7use common::text::{text_measure_function, FontMetrics, TextContext, WritingMode, LOREM_IPSUM};
8use gummy::tree::Cache;
9use gummy::util::print_tree;
10use gummy::{
11 compute_cached_layout, compute_flexbox_layout, compute_grid_layout, compute_leaf_layout, compute_root_layout,
12 prelude::*, round_layout, CacheTree,
13};
14
15#[derive(Debug, Copy, Clone)]
16#[allow(dead_code)]
17enum NodeKind {
18 Flexbox,
19 Grid,
20 Text,
21 Image,
22}
23
24struct Node {
25 kind: NodeKind,
26 style: Style,
27 text_data: Option<TextContext>,
28 image_data: Option<ImageContext>,
29 cache: Cache,
30 unrounded_layout: Layout,
31 pub(crate) has_new_layout: bool,
32 final_layout: Layout,
33 children: Vec<Node>,
34}
35
36impl Default for Node {
37 fn default() -> Self {
38 Node {
39 kind: NodeKind::Flexbox,
40 style: Style::default(),
41 text_data: None,
42 image_data: None,
43 cache: Cache::new(),
44 unrounded_layout: Layout::with_order(0),
45 has_new_layout: false,
46 final_layout: Layout::with_order(0),
47 children: Vec::new(),
48 }
49 }
50}
51
52#[allow(dead_code)]
53impl Node {
54 pub fn new_row(style: Style) -> Node {
55 Node {
56 kind: NodeKind::Flexbox,
57 style: Style { display: Display::Flex, flex_direction: FlexDirection::Row, ..style },
58 ..Node::default()
59 }
60 }
61 pub fn new_column(style: Style) -> Node {
62 Node {
63 kind: NodeKind::Flexbox,
64 style: Style { display: Display::Flex, flex_direction: FlexDirection::Column, ..style },
65 ..Node::default()
66 }
67 }
68 pub fn new_grid(style: Style) -> Node {
69 Node { kind: NodeKind::Grid, style: Style { display: Display::Grid, ..style }, ..Node::default() }
70 }
71 pub fn new_text(style: Style, text_data: TextContext) -> Node {
72 Node { kind: NodeKind::Text, style, text_data: Some(text_data), ..Node::default() }
73 }
74 pub fn new_image(style: Style, image_data: ImageContext) -> Node {
75 Node { kind: NodeKind::Image, style, image_data: Some(image_data), ..Node::default() }
76 }
77 pub fn append_child(&mut self, node: Node) {
78 self.children.push(node);
79 }
80
81 unsafe fn as_id(&self) -> NodeId {
82 NodeId::from(self as *const Node as usize)
83 }
84
85 pub fn compute_layout(&mut self, available_space: Size<AvailableSpace>, use_rounding: bool) {
86 let root_node_id = unsafe { self.as_id() };
87 compute_root_layout(&mut StatelessLayoutTree, root_node_id, available_space);
88 if use_rounding {
89 round_layout(&mut StatelessLayoutTree, root_node_id)
90 }
91 }
92
93 pub fn print_tree(&mut self) {
94 print_tree(&StatelessLayoutTree, unsafe { self.as_id() });
95 }
96}
97
98struct ChildIter<'a>(std::slice::Iter<'a, Node>);
99impl Iterator for ChildIter<'_> {
100 type Item = NodeId;
101 fn next(&mut self) -> Option<Self::Item> {
102 self.0.next().map(|c| NodeId::from(c as *const Node as usize))
103 }
104}
105
106#[inline(always)]
107unsafe fn node_from_id<'a>(node_id: NodeId) -> &'a Node {
108 &*(usize::from(node_id) as *const Node)
109}
110
111#[inline(always)]
112unsafe fn node_from_id_mut<'a>(node_id: NodeId) -> &'a mut Node {
113 &mut *(usize::from(node_id) as *mut Node)
114}
115
116struct StatelessLayoutTree;
117impl TraversePartialTree for StatelessLayoutTree {
118 type ChildIter<'a> = ChildIter<'a>;
119
120 fn child_ids(&self, node_id: NodeId) -> Self::ChildIter<'_> {
121 unsafe { ChildIter(node_from_id(node_id).children.iter()) }
122 }
123
124 fn child_count(&self, node_id: NodeId) -> usize {
125 unsafe { node_from_id(node_id).children.len() }
126 }
127
128 fn get_child_id(&self, node_id: NodeId, index: usize) -> NodeId {
129 unsafe { node_from_id(node_id).children[index].as_id() }
130 }
131}
132
133impl TraverseTree for StatelessLayoutTree {}
134
135impl LayoutPartialTree for StatelessLayoutTree {
136 type CoreContainerStyle<'a>
137 = &'a Style
138 where
139 Self: 'a;
140
141 type CustomIdent = String;
142
143 fn get_core_container_style(&self, node_id: NodeId) -> Self::CoreContainerStyle<'_> {
144 unsafe { &node_from_id(node_id).style }
145 }
146
147 fn set_unrounded_layout(&mut self, node_id: NodeId, layout: &Layout) {
148 unsafe {
149 let node = node_from_id_mut(node_id);
150 node.has_new_layout = &node.unrounded_layout != layout;
151 node.unrounded_layout = *layout;
152 };
153 }
154
155 fn resolve_calc_value(&self, _val: *const (), _basis: f32) -> f32 {
156 0.0
157 }
158
159 fn compute_child_layout(&mut self, node_id: NodeId, inputs: gummy::tree::LayoutInput) -> gummy::tree::LayoutOutput {
160 compute_cached_layout(self, node_id, inputs, |tree, node_id, inputs| {
161 let node = unsafe { node_from_id_mut(node_id) };
162 let font_metrics = FontMetrics { char_width: 10.0, char_height: 10.0 };
163
164 match node.kind {
165 NodeKind::Flexbox => compute_flexbox_layout(tree, node_id, inputs),
166 NodeKind::Grid => compute_grid_layout(tree, node_id, inputs),
167 NodeKind::Text => compute_leaf_layout(
168 inputs,
169 &node.style,
170 |val, basis| tree.resolve_calc_value(val, basis),
171 |known_dimensions, available_space| {
172 text_measure_function(
173 known_dimensions,
174 available_space,
175 node.text_data.as_ref().unwrap(),
176 &font_metrics,
177 )
178 },
179 ),
180 NodeKind::Image => compute_leaf_layout(
181 inputs,
182 &node.style,
183 |val, basis| tree.resolve_calc_value(val, basis),
184 |known_dimensions, _available_space| {
185 image_measure_function(known_dimensions, node.image_data.as_ref().unwrap())
186 },
187 ),
188 }
189 })
190 }
191}
192
193impl CacheTree for StatelessLayoutTree {
194 fn cache_get(&self, node_id: NodeId, inputs: &gummy::LayoutInput) -> Option<gummy::LayoutOutput> {
195 unsafe { node_from_id(node_id) }.cache.get(inputs)
196 }
197
198 fn cache_store(&mut self, node_id: NodeId, inputs: &gummy::LayoutInput, layout_output: gummy::LayoutOutput) {
199 unsafe { node_from_id_mut(node_id) }.cache.store(inputs, layout_output)
200 }
201
202 fn cache_clear(&mut self, node_id: NodeId) {
203 unsafe { node_from_id_mut(node_id) }.cache.clear();
204 }
205}
206
207impl gummy::LayoutFlexboxContainer for StatelessLayoutTree {
208 type FlexboxContainerStyle<'a>
209 = &'a Style
210 where
211 Self: 'a;
212
213 type FlexboxItemStyle<'a>
214 = &'a Style
215 where
216 Self: 'a;
217
218 fn get_flexbox_container_style(&self, node_id: NodeId) -> Self::FlexboxContainerStyle<'_> {
219 unsafe { &node_from_id(node_id).style }
220 }
221
222 fn get_flexbox_child_style(&self, child_node_id: NodeId) -> Self::FlexboxItemStyle<'_> {
223 unsafe { &node_from_id(child_node_id).style }
224 }
225}
226
227impl gummy::LayoutGridContainer for StatelessLayoutTree {
228 type GridContainerStyle<'a>
229 = &'a Style
230 where
231 Self: 'a;
232
233 type GridItemStyle<'a>
234 = &'a Style
235 where
236 Self: 'a;
237
238 fn get_grid_container_style(&self, node_id: NodeId) -> Self::GridContainerStyle<'_> {
239 unsafe { &node_from_id(node_id).style }
240 }
241
242 fn get_grid_child_style(&self, child_node_id: NodeId) -> Self::GridItemStyle<'_> {
243 unsafe { &node_from_id(child_node_id).style }
244 }
245}
246
247impl RoundTree for StatelessLayoutTree {
248 fn get_unrounded_layout(&self, node_id: NodeId) -> Layout {
249 unsafe { node_from_id_mut(node_id).unrounded_layout }
250 }
251
252 fn set_final_layout(&mut self, node_id: NodeId, layout: &Layout) {
253 unsafe { node_from_id_mut(node_id).final_layout = *layout }
254 }
255}
256
257impl PrintTree for StatelessLayoutTree {
258 fn get_debug_label(&self, node_id: NodeId) -> &'static str {
259 match unsafe { node_from_id(node_id).kind } {
260 NodeKind::Flexbox => "FLEX",
261 NodeKind::Grid => "GRID",
262 NodeKind::Text => "TEXT",
263 NodeKind::Image => "IMAGE",
264 }
265 }
266
267 fn get_final_layout(&self, node_id: NodeId) -> Layout {
268 unsafe { node_from_id(node_id).final_layout }
269 }
270
271 fn get_has_new_layout(&self, node_id: NodeId) -> bool {
272 unsafe { node_from_id(node_id).has_new_layout }
273 }
274}
275
276fn main() -> Result<(), gummy::GummyError> {
277 let mut root = Node::new_column(Style::DEFAULT);
278
279 let text_node = Node::new_text(
280 Style::default(),
281 TextContext { text_content: LOREM_IPSUM.into(), writing_mode: WritingMode::Horizontal },
282 );
283 root.append_child(text_node);
284
285 let image_node = Node::new_image(Style::default(), ImageContext { width: 400.0, height: 300.0 });
286 root.append_child(image_node);
287
288 root.compute_layout(Size::MAX_CONTENT, true);
290 root.print_tree();
291
292 Ok(())
293}