Skip to main content

alchemy_styles/stretch/
node.rs

1//! This module is included while awaiting an upstream merge in stretch proper.
2//! You should not rely on it, and consider it an implementation detail.
3
4use core::any::Any;
5
6use std::collections::HashMap;
7use std::ops::Drop;
8use std::sync::Mutex;
9
10use lazy_static::lazy_static;
11
12use crate::stretch::geometry::Size;
13use crate::stretch::id;
14use crate::stretch::number::Number;
15use crate::stretch::result::{Cache, Layout};
16use crate::stretch::style::*;
17use crate::stretch::Error;
18
19type MeasureFunc = Box<Fn(Size<Number>) -> Result<Size<f32>, Box<Any>> + Send + Sync + 'static>;
20
21lazy_static! {
22    /// Global stretch instance id allocator.
23    static ref INSTANCE_ALLOCATOR: Mutex<id::Allocator> = Mutex::new(id::Allocator::new());
24}
25
26#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
27pub struct Node {
28    instance: id::Id,
29    local: id::Id,
30}
31
32pub(crate) struct Storage<T>(HashMap<Node, T>);
33
34impl<T> Storage<T> {
35    pub fn new() -> Self {
36        Storage(HashMap::new())
37    }
38
39    pub fn get(&self, node: Node) -> Result<&T, Error> {
40        match self.0.get(&node) {
41            Some(v) => Ok(v),
42            None => Err(Error::InvalidNode(node)),
43        }
44    }
45
46    pub fn get_mut(&mut self, node: Node) -> Result<&mut T, Error> {
47        match self.0.get_mut(&node) {
48            Some(v) => Ok(v),
49            None => Err(Error::InvalidNode(node)),
50        }
51    }
52
53    pub fn insert(&mut self, node: Node, value: T) -> Option<T> {
54        self.0.insert(node, value)
55    }
56}
57
58impl<T> std::ops::Index<&Node> for Storage<T> {
59    type Output = T;
60
61    fn index(&self, idx: &Node) -> &T {
62        &(self.0)[idx]
63    }
64}
65
66pub struct Stretch {
67    id: id::Id,
68    nodes: id::Allocator,
69    pub(crate) style: Storage<Style>,
70    pub(crate) parents: Storage<Vec<Node>>,
71    pub(crate) children: Storage<Vec<Node>>,
72    pub(crate) measure: Storage<Option<MeasureFunc>>,
73    pub(crate) layout: Storage<Layout>,
74    pub(crate) layout_cache: Storage<Option<Cache>>,
75    pub(crate) is_dirty: Storage<bool>,
76}
77
78impl Stretch {
79    pub fn new() -> Self {
80        Stretch {
81            id: INSTANCE_ALLOCATOR.lock().unwrap().allocate(),
82            nodes: id::Allocator::new(),
83            style: Storage::new(),
84            parents: Storage::new(),
85            children: Storage::new(),
86            measure: Storage::new(),
87            layout: Storage::new(),
88            layout_cache: Storage::new(),
89            is_dirty: Storage::new(),
90        }
91    }
92
93    fn allocate_node(&mut self) -> Node {
94        let local = self.nodes.allocate();
95        Node { instance: self.id, local }
96    }
97
98    pub fn new_leaf(&mut self, style: Style, measure: MeasureFunc) -> Node {
99        let node = self.allocate_node();
100
101        self.style.insert(node, style);
102        self.parents.insert(node, Vec::with_capacity(1));
103        self.children.insert(node, Vec::with_capacity(0));
104        self.measure.insert(node, Some(measure));
105        self.layout.insert(node, Layout::new());
106        self.layout_cache.insert(node, None);
107        self.is_dirty.insert(node, true);
108
109        node
110    }
111
112    pub fn new_node(&mut self, style: Style, children: Vec<Node>) -> Result<Node, Error> {
113        let node = self.allocate_node();
114
115        for child in &children {
116            self.parents.get_mut(*child)?.push(node);
117        }
118
119        self.style.insert(node, style);
120        self.parents.insert(node, Vec::with_capacity(1));
121        self.children.insert(node, children);
122        self.measure.insert(node, None);
123        self.layout.insert(node, Layout::new());
124        self.layout_cache.insert(node, None);
125        self.is_dirty.insert(node, true);
126
127        Ok(node)
128    }
129
130    pub fn set_measure(&mut self, node: Node, measure: Option<MeasureFunc>) -> Result<(), Error> {
131        *self.measure.get_mut(node)? = measure;
132        self.mark_dirty(node)?;
133        Ok(())
134    }
135
136    pub fn add_child(&mut self, node: Node, child: Node) -> Result<(), Error> {
137        self.parents.get_mut(child)?.push(node);
138        self.children.get_mut(node)?.push(child);
139        self.mark_dirty(node)
140    }
141
142    pub fn set_children(&mut self, node: Node, children: Vec<Node>) -> Result<(), Error> {
143        // Remove node as parent from all its current children.
144        for child in self.children.get(node)? {
145            self.parents.get_mut(*child)?.retain(|p| *p != node);
146        }
147
148        *self.children.get_mut(node)? = Vec::with_capacity(children.len());
149
150        // Build up relation node <-> child
151        for child in children {
152            self.parents.get_mut(child)?.push(node);
153            self.children.get_mut(node)?.push(child);
154        }
155
156        self.mark_dirty(node)
157    }
158
159    pub fn remove_child(&mut self, node: Node, child: Node) -> Result<Node, Error> {
160        match self.children(node)?.iter().position(|n| *n == child) {
161            Some(index) => self.remove_child_at_index(node, index),
162            None => Err(Error::InvalidNode(child)),
163        }
164    }
165
166    pub fn remove_child_at_index(&mut self, node: Node, index: usize) -> Result<Node, Error> {
167        let child = self.children.get_mut(node)?.remove(index);
168        self.parents.get_mut(child)?.retain(|p| *p != node);
169
170        self.mark_dirty(node)?;
171
172        Ok(child)
173    }
174
175    pub fn replace_child_at_index(&mut self, node: Node, index: usize, child: Node) -> Result<Node, Error> {
176        self.parents.get_mut(child)?.push(node);
177        let old_child = std::mem::replace(&mut self.children.get_mut(node)?[index], child);
178        self.parents.get_mut(old_child)?.retain(|p| *p != node);
179
180        self.mark_dirty(node)?;
181
182        Ok(old_child)
183    }
184
185    pub fn children(&self, node: Node) -> Result<Vec<Node>, Error> {
186        self.children.get(node).map(Clone::clone)
187    }
188
189    pub fn child_count(&self, node: Node) -> Result<usize, Error> {
190        self.children.get(node).map(Vec::len)
191    }
192
193    pub fn set_style(&mut self, node: Node, style: Style) -> Result<(), Error> {
194        *self.style.get_mut(node)? = style;
195        self.mark_dirty(node)
196    }
197
198    pub fn style(&self, node: Node) -> Result<&Style, Error> {
199        self.style.get(node)
200    }
201
202    pub fn layout(&self, node: Node) -> Result<&Layout, Error> {
203        self.layout.get(node)
204    }
205
206    pub fn mark_dirty(&mut self, node: Node) -> Result<(), Error> {
207        fn mark_dirty_impl(
208            node: Node,
209            layout_cache: &mut Storage<Option<Cache>>,
210            is_dirty: &mut Storage<bool>,
211            parents: &Storage<Vec<Node>>,
212        ) -> Result<(), Error> {
213            *layout_cache.get_mut(node)? = None;
214            *is_dirty.get_mut(node)? = true;
215
216            for parent in parents.get(node)? {
217                mark_dirty_impl(*parent, layout_cache, is_dirty, parents)?;
218            }
219
220            Ok(())
221        }
222
223        mark_dirty_impl(node, &mut self.layout_cache, &mut self.is_dirty, &self.parents)
224    }
225
226    pub fn dirty(&self, node: Node) -> Result<bool, Error> {
227        self.is_dirty.get(node).map(|v| *v)
228    }
229
230    pub fn compute_layout(&mut self, node: Node, size: Size<Number>) -> Result<(), Error> {
231        match self.layout.get(node) {
232            Ok(_) => self.compute(node, size).map_err(|err| Error::Measure(err)),
233            _ => Err(Error::InvalidNode(node)),
234        }
235    }
236}
237
238impl Drop for Stretch {
239    fn drop(&mut self) {
240        INSTANCE_ALLOCATOR.lock().unwrap().free(&[self.id]);
241    }
242}