Skip to main content

custom_tree_owned_partial/
custom_tree_owned_partial.rs

1//! ## Example: Partial Tree with Directly Owned Children
2//!
3//! The following example demonstrate an implementation of Gummy's Partial trait and usage of the low-level compute APIs.
4//! This example uses directly owned children with NodeId's being index's into vec on parent node.
5//! Since an iterator created from a node can't access grandchildren, we are limited to only implement `TraversePartialTree`.
6//! See the [`crate::tree::traits`] module for more details about the low-level traits.
7
8mod common {
9    pub mod image;
10    pub mod text;
11}
12use common::image::{image_measure_function, ImageContext};
13use common::text::{text_measure_function, FontMetrics, TextContext, WritingMode, LOREM_IPSUM};
14use gummy::{
15    compute_cached_layout, compute_flexbox_layout, compute_grid_layout, compute_leaf_layout, compute_root_layout,
16    prelude::*, Cache, CacheTree, Layout, Style,
17};
18
19#[derive(Debug, Copy, Clone)]
20#[allow(dead_code)]
21enum NodeKind {
22    Flexbox,
23    Grid,
24    Text,
25    Image,
26}
27
28struct Node {
29    kind: NodeKind,
30    style: Style,
31    text_data: Option<TextContext>,
32    image_data: Option<ImageContext>,
33    cache: Cache,
34    has_new_layout: bool,
35    layout: Layout,
36    children: Vec<Node>,
37}
38
39impl Default for Node {
40    fn default() -> Self {
41        Node {
42            kind: NodeKind::Flexbox,
43            style: Style::default(),
44            text_data: None,
45            image_data: None,
46            cache: Cache::new(),
47            has_new_layout: true,
48            layout: Layout::with_order(0),
49            children: Vec::new(),
50        }
51    }
52}
53
54#[allow(dead_code)]
55impl Node {
56    pub fn new_row(style: Style) -> Node {
57        Node {
58            kind: NodeKind::Flexbox,
59            style: Style { display: Display::Flex, flex_direction: FlexDirection::Row, ..style },
60            ..Node::default()
61        }
62    }
63    pub fn new_column(style: Style) -> Node {
64        Node {
65            kind: NodeKind::Flexbox,
66            style: Style { display: Display::Flex, flex_direction: FlexDirection::Column, ..style },
67            ..Node::default()
68        }
69    }
70    pub fn new_grid(style: Style) -> Node {
71        Node { kind: NodeKind::Grid, style: Style { display: Display::Grid, ..style }, ..Node::default() }
72    }
73    pub fn new_text(style: Style, text_data: TextContext) -> Node {
74        Node { kind: NodeKind::Text, style, text_data: Some(text_data), ..Node::default() }
75    }
76    pub fn new_image(style: Style, image_data: ImageContext) -> Node {
77        Node { kind: NodeKind::Image, style, image_data: Some(image_data), ..Node::default() }
78    }
79    pub fn append_child(&mut self, node: Node) {
80        self.children.push(node);
81    }
82
83    pub fn compute_layout(&mut self, available_space: Size<AvailableSpace>) {
84        compute_root_layout(self, NodeId::from(usize::MAX), available_space);
85    }
86
87    /// The methods on LayoutPartialTree need to be able to access:
88    ///
89    ///  - The node being laid out
90    ///  - Direct children of the node being laid out
91    ///
92    /// Each must have an ID. For children we simply use it's index. For the node itself
93    /// we use usize::MAX on the assumption that there will never be that many children.
94    fn node_from_id(&self, node_id: NodeId) -> &Node {
95        let idx = usize::from(node_id);
96        if idx == usize::MAX {
97            self
98        } else {
99            &self.children[idx]
100        }
101    }
102
103    fn node_from_id_mut(&mut self, node_id: NodeId) -> &mut Node {
104        let idx = usize::from(node_id);
105        if idx == usize::MAX {
106            self
107        } else {
108            &mut self.children[idx]
109        }
110    }
111}
112
113struct ChildIter(std::ops::Range<usize>);
114impl Iterator for ChildIter {
115    type Item = NodeId;
116    fn next(&mut self) -> Option<Self::Item> {
117        self.0.next().map(NodeId::from)
118    }
119}
120
121impl gummy::TraversePartialTree for Node {
122    type ChildIter<'a> = ChildIter;
123
124    fn child_ids(&self, _node_id: NodeId) -> Self::ChildIter<'_> {
125        ChildIter(0..self.children.len())
126    }
127
128    fn child_count(&self, _node_id: NodeId) -> usize {
129        self.children.len()
130    }
131
132    fn get_child_id(&self, _node_id: NodeId, index: usize) -> NodeId {
133        NodeId::from(index)
134    }
135}
136
137impl gummy::LayoutPartialTree for Node {
138    type CoreContainerStyle<'a>
139        = &'a Style
140    where
141        Self: 'a;
142
143    type CustomIdent = String;
144
145    fn get_core_container_style(&self, node_id: NodeId) -> Self::CoreContainerStyle<'_> {
146        &self.node_from_id(node_id).style
147    }
148
149    fn set_unrounded_layout(&mut self, node_id: NodeId, layout: &Layout) {
150        let node = self.node_from_id_mut(node_id);
151        node.has_new_layout = &node.layout != layout;
152        node.layout = *layout;
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, |parent, node_id, inputs| {
161            let node = parent.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(node, node_id, inputs),
166                NodeKind::Grid => compute_grid_layout(node, node_id, inputs),
167                NodeKind::Text => compute_leaf_layout(
168                    inputs,
169                    &node.style,
170                    |_val, _basis| 0.0,
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| 0.0,
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 Node {
194    fn cache_get(&self, node_id: NodeId, inputs: &gummy::LayoutInput) -> Option<gummy::LayoutOutput> {
195        self.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        self.node_from_id_mut(node_id).cache.store(inputs, layout_output)
200    }
201
202    fn cache_clear(&mut self, node_id: NodeId) {
203        self.node_from_id_mut(node_id).cache.clear();
204    }
205}
206
207impl gummy::LayoutFlexboxContainer for Node {
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        &self.node_from_id(node_id).style
220    }
221
222    fn get_flexbox_child_style(&self, child_node_id: NodeId) -> Self::FlexboxItemStyle<'_> {
223        &self.node_from_id(child_node_id).style
224    }
225}
226
227impl gummy::LayoutGridContainer for Node {
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        &self.node_from_id(node_id).style
240    }
241
242    fn get_grid_child_style(&self, child_node_id: NodeId) -> Self::GridItemStyle<'_> {
243        &self.node_from_id(child_node_id).style
244    }
245}
246
247fn main() -> Result<(), gummy::GummyError> {
248    let mut root = Node::new_column(Style::DEFAULT);
249
250    let text_node = Node::new_text(
251        Style::default(),
252        TextContext { text_content: LOREM_IPSUM.into(), writing_mode: WritingMode::Horizontal },
253    );
254    root.append_child(text_node);
255
256    let image_node = Node::new_image(Style::default(), ImageContext { width: 400.0, height: 300.0 });
257    root.append_child(image_node);
258
259    // Compute layout
260    root.compute_layout(Size::MAX_CONTENT);
261
262    Ok(())
263}