tawasuyu

tawasuyu/taffy

A high performance rust-powered UI layout library

HTML 231Rust 10TOML 3CSS 1348 Sutichaykuna

⎇ 5db1a9d99aeb127615eb3d3dae90d83e7d5eaace examples/custom_tree_owned_unsafe.rs Rust · 293 siq'ikuna · 8.9 KB Ñawpa willay Pi imata llamkarqan ch'uya

Use `*const ()` to represent `CompactLength` and add implementation for 32 bit platforms (#789) 8d2a036c1 · Nico Burns ·

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, CacheTree,
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    fn get_core_container_style(&self, node_id: NodeId) -> Self::CoreContainerStyle<'_> {
139        unsafe { &node_from_id(node_id).style }
140    }
141
142    fn set_unrounded_layout(&mut self, node_id: NodeId, layout: &Layout) {
143        unsafe { node_from_id_mut(node_id).unrounded_layout = *layout };
144    }
145
146    fn resolve_calc_value(&self, _val: *const (), _basis: f32) -> f32 {
147        0.0
148    }
149
150    fn compute_child_layout(&mut self, node_id: NodeId, inputs: taffy::tree::LayoutInput) -> taffy::tree::LayoutOutput {
151        compute_cached_layout(self, node_id, inputs, |tree, node_id, inputs| {
152            let node = unsafe { node_from_id_mut(node_id) };
153            let font_metrics = FontMetrics { char_width: 10.0, char_height: 10.0 };
154
155            match node.kind {
156                NodeKind::Flexbox => compute_flexbox_layout(tree, node_id, inputs),
157                NodeKind::Grid => compute_grid_layout(tree, node_id, inputs),
158                NodeKind::Text => compute_leaf_layout(
159                    inputs,
160                    &node.style,
161                    |val, basis| tree.resolve_calc_value(val, basis),
162                    |known_dimensions, available_space| {
163                        text_measure_function(
164                            known_dimensions,
165                            available_space,
166                            node.text_data.as_ref().unwrap(),
167                            &font_metrics,
168                        )
169                    },
170                ),
171                NodeKind::Image => compute_leaf_layout(
172                    inputs,
173                    &node.style,
174                    |val, basis| tree.resolve_calc_value(val, basis),
175                    |known_dimensions, _available_space| {
176                        image_measure_function(known_dimensions, node.image_data.as_ref().unwrap())
177                    },
178                ),
179            }
180        })
181    }
182}
183
184impl CacheTree for StatelessLayoutTree {
185    fn cache_get(
186        &self,
187        node_id: NodeId,
188        known_dimensions: Size<Option<f32>>,
189        available_space: Size<AvailableSpace>,
190        run_mode: taffy::RunMode,
191    ) -> Option<taffy::LayoutOutput> {
192        unsafe { node_from_id(node_id) }.cache.get(known_dimensions, available_space, run_mode)
193    }
194
195    fn cache_store(
196        &mut self,
197        node_id: NodeId,
198        known_dimensions: Size<Option<f32>>,
199        available_space: Size<AvailableSpace>,
200        run_mode: taffy::RunMode,
201        layout_output: taffy::LayoutOutput,
202    ) {
203        unsafe { node_from_id_mut(node_id) }.cache.store(known_dimensions, available_space, run_mode, layout_output)
204    }
205
206    fn cache_clear(&mut self, node_id: NodeId) {
207        unsafe { node_from_id_mut(node_id) }.cache.clear();
208    }
209}
210
211impl taffy::LayoutFlexboxContainer for StatelessLayoutTree {
212    type FlexboxContainerStyle<'a>
213        = &'a Style
214    where
215        Self: 'a;
216
217    type FlexboxItemStyle<'a>
218        = &'a Style
219    where
220        Self: 'a;
221
222    fn get_flexbox_container_style(&self, node_id: NodeId) -> Self::FlexboxContainerStyle<'_> {
223        unsafe { &node_from_id(node_id).style }
224    }
225
226    fn get_flexbox_child_style(&self, child_node_id: NodeId) -> Self::FlexboxItemStyle<'_> {
227        unsafe { &node_from_id(child_node_id).style }
228    }
229}
230
231impl taffy::LayoutGridContainer for StatelessLayoutTree {
232    type GridContainerStyle<'a>
233        = &'a Style
234    where
235        Self: 'a;
236
237    type GridItemStyle<'a>
238        = &'a Style
239    where
240        Self: 'a;
241
242    fn get_grid_container_style(&self, node_id: NodeId) -> Self::GridContainerStyle<'_> {
243        unsafe { &node_from_id(node_id).style }
244    }
245
246    fn get_grid_child_style(&self, child_node_id: NodeId) -> Self::GridItemStyle<'_> {
247        unsafe { &node_from_id(child_node_id).style }
248    }
249}
250
251impl RoundTree for StatelessLayoutTree {
252    fn get_unrounded_layout(&self, node_id: NodeId) -> &Layout {
253        unsafe { &node_from_id_mut(node_id).unrounded_layout }
254    }
255
256    fn set_final_layout(&mut self, node_id: NodeId, layout: &Layout) {
257        unsafe { node_from_id_mut(node_id).final_layout = *layout }
258    }
259}
260
261impl PrintTree for StatelessLayoutTree {
262    fn get_debug_label(&self, node_id: NodeId) -> &'static str {
263        match unsafe { node_from_id(node_id).kind } {
264            NodeKind::Flexbox => "FLEX",
265            NodeKind::Grid => "GRID",
266            NodeKind::Text => "TEXT",
267            NodeKind::Image => "IMAGE",
268        }
269    }
270
271    fn get_final_layout(&self, node_id: NodeId) -> &Layout {
272        unsafe { &node_from_id(node_id).final_layout }
273    }
274}
275
276fn main() -> Result<(), taffy::TaffyError> {
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    // Compute layout and print result
289    root.compute_layout(Size::MAX_CONTENT, true);
290    root.print_tree();
291
292    Ok(())
293}