⎇ f37efc58a41a9d9313e015c3e3d7179162c543b7
examples/custom_tree_owned_unsafe.rs
History
Who touched what
raw
Update to latest rustfmt (format associated types with GATs) (#737)
1mod common {
2 pub mod image;
3 pub mod text;
4}
5use common::image::{image_measure_function, ImageContext};
6use common::text::{text_measure_function, FontMetrics, TextContext, WritingMode, LOREM_IPSUM};
7use taffy::tree::Cache;
8use taffy::util::print_tree;
9use taffy::{
10 compute_cached_layout, compute_flexbox_layout, compute_grid_layout, compute_leaf_layout, compute_root_layout,
11 prelude::*, round_layout,
12};
13
14#[derive(Debug, Copy, Clone)]
15#[allow(dead_code)]
16enum NodeKind {
17 Flexbox,
18 Grid,
19 Text,
20 Image,
21}
22
23struct Node {
24 kind: NodeKind,
25 style: Style,
26 text_data: Option<TextContext>,
27 image_data: Option<ImageContext>,
28 cache: Cache,
29 unrounded_layout: Layout,
30 final_layout: Layout,
31 children: Vec<Node>,
32}
33
34impl Default for Node {
35 fn default() -> Self {
36 Node {
37 kind: NodeKind::Flexbox,
38 style: Style::default(),
39 text_data: None,
40 image_data: None,
41 cache: Cache::new(),
42 unrounded_layout: Layout::with_order(0),
43 final_layout: Layout::with_order(0),
44 children: Vec::new(),
45 }
46 }
47}
48
49#[allow(dead_code)]
50impl Node {
51 pub fn new_row(style: Style) -> Node {
52 Node {
53 kind: NodeKind::Flexbox,
54 style: Style { display: Display::Flex, flex_direction: FlexDirection::Row, ..style },
55 ..Node::default()
56 }
57 }
58 pub fn new_column(style: Style) -> Node {
59 Node {
60 kind: NodeKind::Flexbox,
61 style: Style { display: Display::Flex, flex_direction: FlexDirection::Column, ..style },
62 ..Node::default()
63 }
64 }
65 pub fn new_grid(style: Style) -> Node {
66 Node { kind: NodeKind::Grid, style: Style { display: Display::Grid, ..style }, ..Node::default() }
67 }
68 pub fn new_text(style: Style, text_data: TextContext) -> Node {
69 Node { kind: NodeKind::Text, style, text_data: Some(text_data), ..Node::default() }
70 }
71 pub fn new_image(style: Style, image_data: ImageContext) -> Node {
72 Node { kind: NodeKind::Image, style, image_data: Some(image_data), ..Node::default() }
73 }
74 pub fn append_child(&mut self, node: Node) {
75 self.children.push(node);
76 }
77
78 unsafe fn as_id(&self) -> NodeId {
79 NodeId::from(self as *const Node as usize)
80 }
81
82 pub fn compute_layout(&mut self, available_space: Size<AvailableSpace>, use_rounding: bool) {
83 let root_node_id = unsafe { self.as_id() };
84 compute_root_layout(&mut StatelessLayoutTree, root_node_id, available_space);
85 if use_rounding {
86 round_layout(&mut StatelessLayoutTree, root_node_id)
87 }
88 }
89
90 pub fn print_tree(&mut self) {
91 print_tree(&StatelessLayoutTree, unsafe { self.as_id() });
92 }
93}
94
95struct ChildIter<'a>(std::slice::Iter<'a, Node>);
96impl Iterator for ChildIter<'_> {
97 type Item = NodeId;
98 fn next(&mut self) -> Option<Self::Item> {
99 self.0.next().map(|c| NodeId::from(c as *const Node as usize))
100 }
101}
102
103#[inline(always)]
104unsafe fn node_from_id<'a>(node_id: NodeId) -> &'a Node {
105 &*(usize::from(node_id) as *const Node)
106}
107
108#[inline(always)]
109unsafe fn node_from_id_mut<'a>(node_id: NodeId) -> &'a mut Node {
110 &mut *(usize::from(node_id) as *mut Node)
111}
112
113struct StatelessLayoutTree;
114impl TraversePartialTree for StatelessLayoutTree {
115 type ChildIter<'a> = ChildIter<'a>;
116
117 fn child_ids(&self, node_id: NodeId) -> Self::ChildIter<'_> {
118 unsafe { ChildIter(node_from_id(node_id).children.iter()) }
119 }
120
121 fn child_count(&self, node_id: NodeId) -> usize {
122 unsafe { node_from_id(node_id).children.len() }
123 }
124
125 fn get_child_id(&self, node_id: NodeId, index: usize) -> NodeId {
126 unsafe { node_from_id(node_id).children[index].as_id() }
127 }
128}
129
130impl TraverseTree for StatelessLayoutTree {}
131
132impl LayoutPartialTree for StatelessLayoutTree {
133 type CoreContainerStyle<'a>
134 = &'a Style
135 where
136 Self: 'a;
137
138 type CacheMut<'b>
139 = &'b mut Cache
140 where
141 Self: 'b;
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 get_cache_mut(&mut self, node_id: NodeId) -> &mut Cache {
152 unsafe { &mut node_from_id_mut(node_id).cache }
153 }
154
155 fn compute_child_layout(&mut self, node_id: NodeId, inputs: taffy::tree::LayoutInput) -> taffy::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 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(inputs, &node.style, |known_dimensions, available_space| {
164 text_measure_function(
165 known_dimensions,
166 available_space,
167 node.text_data.as_ref().unwrap(),
168 &font_metrics,
169 )
170 }),
171 NodeKind::Image => compute_leaf_layout(inputs, &node.style, |known_dimensions, _available_space| {
172 image_measure_function(known_dimensions, node.image_data.as_ref().unwrap())
173 }),
174 }
175 })
176 }
177}
178
179impl taffy::LayoutFlexboxContainer for StatelessLayoutTree {
180 type FlexboxContainerStyle<'a>
181 = &'a Style
182 where
183 Self: 'a;
184
185 type FlexboxItemStyle<'a>
186 = &'a Style
187 where
188 Self: 'a;
189
190 fn get_flexbox_container_style(&self, node_id: NodeId) -> Self::FlexboxContainerStyle<'_> {
191 unsafe { &node_from_id(node_id).style }
192 }
193
194 fn get_flexbox_child_style(&self, child_node_id: NodeId) -> Self::FlexboxItemStyle<'_> {
195 unsafe { &node_from_id(child_node_id).style }
196 }
197}
198
199impl taffy::LayoutGridContainer for StatelessLayoutTree {
200 type GridContainerStyle<'a>
201 = &'a Style
202 where
203 Self: 'a;
204
205 type GridItemStyle<'a>
206 = &'a Style
207 where
208 Self: 'a;
209
210 fn get_grid_container_style(&self, node_id: NodeId) -> Self::GridContainerStyle<'_> {
211 unsafe { &node_from_id(node_id).style }
212 }
213
214 fn get_grid_child_style(&self, child_node_id: NodeId) -> Self::GridItemStyle<'_> {
215 unsafe { &node_from_id(child_node_id).style }
216 }
217}
218
219impl RoundTree for StatelessLayoutTree {
220 fn get_unrounded_layout(&self, node_id: NodeId) -> &Layout {
221 unsafe { &node_from_id_mut(node_id).unrounded_layout }
222 }
223
224 fn set_final_layout(&mut self, node_id: NodeId, layout: &Layout) {
225 unsafe { node_from_id_mut(node_id).final_layout = *layout }
226 }
227}
228
229impl PrintTree for StatelessLayoutTree {
230 fn get_debug_label(&self, node_id: NodeId) -> &'static str {
231 match unsafe { node_from_id(node_id).kind } {
232 NodeKind::Flexbox => "FLEX",
233 NodeKind::Grid => "GRID",
234 NodeKind::Text => "TEXT",
235 NodeKind::Image => "IMAGE",
236 }
237 }
238
239 fn get_final_layout(&self, node_id: NodeId) -> &Layout {
240 unsafe { &node_from_id(node_id).final_layout }
241 }
242}
243
244fn main() -> Result<(), taffy::TaffyError> {
245 let mut root = Node::new_column(Style::DEFAULT);
246
247 let text_node = Node::new_text(
248 Style::default(),
249 TextContext { text_content: LOREM_IPSUM.into(), writing_mode: WritingMode::Horizontal },
250 );
251 root.append_child(text_node);
252
253 let image_node = Node::new_image(Style::default(), ImageContext { width: 400.0, height: 300.0 });
254 root.append_child(image_node);
255
256 // Compute layout and print result
257 root.compute_layout(Size::MAX_CONTENT, true);
258 root.print_tree();
259
260 Ok(())
261}