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 takia::tree::Cache;
9use takia::util::print_tree;
10use takia::{
11 compute_cached_layout, compute_flexbox_layout, compute_grid_layout, compute_leaf_layout, compute_oof_layout,
12 compute_root_layout, prelude::*, round_layout, CacheTree, LayoutContainingBlock,
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 final_layout: Layout,
32 children: Vec<Node>,
33 hoisted_children: Vec<NodeId>,
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 final_layout: Layout::with_order(0),
46 children: Vec::new(),
47 hoisted_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 { node_from_id_mut(node_id).unrounded_layout = *layout };
149 }
150
151 fn resolve_calc_value(&self, _val: *const (), _basis: f32) -> f32 {
152 0.0
153 }
154
155 fn compute_child_layout(&mut self, node_id: NodeId, inputs: takia::tree::LayoutInput) -> takia::tree::LayoutOutput {
156 compute_cached_layout(self, node_id, inputs, |tree, node_id, inputs| {
157 let node = unsafe { node_from_id_mut(node_id) };
158 let font_metrics = FontMetrics { char_width: 10.0, char_height: 10.0 };
159
160 let mut output = match node.kind {
161 NodeKind::Flexbox => compute_flexbox_layout(tree, node_id, inputs),
162 NodeKind::Grid => compute_grid_layout(tree, node_id, inputs),
163 NodeKind::Text => compute_leaf_layout(
164 inputs,
165 &node.style,
166 |val, basis| tree.resolve_calc_value(val, basis),
167 |known_dimensions, available_space| {
168 text_measure_function(
169 known_dimensions,
170 available_space,
171 node.text_data.as_ref().unwrap(),
172 &font_metrics,
173 )
174 },
175 ),
176 NodeKind::Image => compute_leaf_layout(
177 inputs,
178 &node.style,
179 |val, basis| tree.resolve_calc_value(val, basis),
180 |known_dimensions, _available_space| {
181 image_measure_function(known_dimensions, node.image_data.as_ref().unwrap())
182 },
183 ),
184 };
185
186 if inputs.run_mode == takia::RunMode::PerformLayout {
188 compute_oof_layout(tree, node_id, &mut output);
189 }
190
191 output
192 })
193 }
194}
195
196impl LayoutContainingBlock for StatelessLayoutTree {
197 type OofItemStyle<'a>
198 = &'a Style
199 where
200 Self: 'a;
201
202 fn get_oof_item_style(&self, node_id: NodeId) -> Self::OofItemStyle<'_> {
203 unsafe { &node_from_id(node_id).style }
204 }
205
206 fn clear_hoisted_children(&mut self, node_id: NodeId) {
207 unsafe { node_from_id_mut(node_id).hoisted_children.clear() };
208 }
209
210 fn add_hoisted_children(&mut self, node_id: NodeId, hoisted: &[NodeId]) {
211 unsafe { node_from_id_mut(node_id).hoisted_children.extend_from_slice(hoisted) };
212 }
213}
214
215impl CacheTree for StatelessLayoutTree {
216 fn cache_get(&mut self, node_id: NodeId, inputs: &takia::LayoutInput) -> Option<takia::LayoutOutput> {
217 unsafe { node_from_id_mut(node_id) }.cache.get(inputs)
218 }
219
220 fn cache_store(&mut self, node_id: NodeId, inputs: &takia::LayoutInput, layout_output: takia::LayoutOutput) {
221 unsafe { node_from_id_mut(node_id) }.cache.store(inputs, layout_output)
222 }
223
224 fn cache_clear(&mut self, node_id: NodeId) {
225 unsafe { node_from_id_mut(node_id) }.cache.clear();
226 }
227}
228
229impl takia::LayoutFlexboxContainer for StatelessLayoutTree {
230 type FlexboxContainerStyle<'a>
231 = &'a Style
232 where
233 Self: 'a;
234
235 type FlexboxItemStyle<'a>
236 = &'a Style
237 where
238 Self: 'a;
239
240 fn get_flexbox_container_style(&self, node_id: NodeId) -> Self::FlexboxContainerStyle<'_> {
241 unsafe { &node_from_id(node_id).style }
242 }
243
244 fn get_flexbox_child_style(&self, child_node_id: NodeId) -> Self::FlexboxItemStyle<'_> {
245 unsafe { &node_from_id(child_node_id).style }
246 }
247}
248
249impl takia::LayoutGridContainer for StatelessLayoutTree {
250 type GridContainerStyle<'a>
251 = &'a Style
252 where
253 Self: 'a;
254
255 type GridItemStyle<'a>
256 = &'a Style
257 where
258 Self: 'a;
259
260 fn get_grid_container_style(&self, node_id: NodeId) -> Self::GridContainerStyle<'_> {
261 unsafe { &node_from_id(node_id).style }
262 }
263
264 fn get_grid_child_style(&self, child_node_id: NodeId) -> Self::GridItemStyle<'_> {
265 unsafe { &node_from_id(child_node_id).style }
266 }
267}
268
269impl RoundTree for StatelessLayoutTree {
270 fn get_unrounded_layout(&self, node_id: NodeId) -> Layout {
271 unsafe { node_from_id_mut(node_id).unrounded_layout }
272 }
273
274 fn set_final_layout(&mut self, node_id: NodeId, layout: &Layout) {
275 unsafe { node_from_id_mut(node_id).final_layout = *layout }
276 }
277
278 fn is_out_of_flow(&self, node_id: NodeId) -> bool {
279 unsafe { node_from_id(node_id).style.position.is_out_of_flow() }
280 }
281
282 fn hoisted_child_count(&self, node_id: NodeId) -> usize {
283 unsafe { node_from_id(node_id).hoisted_children.len() }
284 }
285
286 fn get_hoisted_child_id(&self, node_id: NodeId, index: usize) -> NodeId {
287 unsafe { node_from_id(node_id).hoisted_children[index] }
288 }
289}
290
291impl PrintTree for StatelessLayoutTree {
292 fn get_debug_label(&self, node_id: NodeId) -> &'static str {
293 match unsafe { node_from_id(node_id).kind } {
294 NodeKind::Flexbox => "FLEX",
295 NodeKind::Grid => "GRID",
296 NodeKind::Text => "TEXT",
297 NodeKind::Image => "IMAGE",
298 }
299 }
300
301 fn get_final_layout(&self, node_id: NodeId) -> Layout {
302 unsafe { node_from_id(node_id).final_layout }
303 }
304}
305
306fn main() -> Result<(), takia::TakiaError> {
307 let mut root = Node::new_column(Style::DEFAULT);
308
309 let text_node = Node::new_text(
310 Style::default(),
311 TextContext { text_content: LOREM_IPSUM.into(), writing_mode: WritingMode::Horizontal },
312 );
313 root.append_child(text_node);
314
315 let image_node = Node::new_image(Style::default(), ImageContext { width: 400.0, height: 300.0 });
316 root.append_child(image_node);
317
318 root.compute_layout(Size::MAX_CONTENT, true);
320 root.print_tree();
321
322 Ok(())
323}