tessera_ui/
component_tree.rs

1mod constraint;
2mod node;
3
4use std::{num::NonZero, sync::Arc, time::Instant};
5
6use log::debug;
7use parking_lot::RwLock;
8use rayon::prelude::*;
9
10use crate::{
11    ComputeResourceManager,
12    cursor::CursorEvent,
13    px::{PxPosition, PxSize},
14    renderer::Command,
15};
16
17pub use constraint::{Constraint, DimensionValue};
18pub use node::{
19    ComponentNode, ComponentNodeMetaData, ComponentNodeMetaDatas, ComponentNodeTree, ComputedData,
20    ImeRequest, MeasureFn, MeasurementError, StateHandlerFn, StateHandlerInput, WindowRequests,
21    measure_node, measure_nodes, place_node,
22};
23
24/// Respents a component tree
25pub struct ComponentTree {
26    /// We use indextree as the tree structure
27    tree: indextree::Arena<ComponentNode>,
28    /// Components' metadatas
29    metadatas: ComponentNodeMetaDatas,
30    /// Used to remember the current node
31    node_queue: Vec<indextree::NodeId>,
32}
33
34impl Default for ComponentTree {
35    fn default() -> Self {
36        Self::new()
37    }
38}
39
40impl ComponentTree {
41    /// Create a new ComponentTree
42    pub fn new() -> Self {
43        let tree = indextree::Arena::new();
44        let node_queue = Vec::new();
45        let metadatas = ComponentNodeMetaDatas::new();
46        Self {
47            tree,
48            node_queue,
49            metadatas,
50        }
51    }
52
53    /// Clear the component tree
54    pub fn clear(&mut self) {
55        self.tree.clear();
56        self.metadatas.clear();
57        self.node_queue.clear();
58    }
59
60    /// Get node by NodeId
61    pub fn get(&self, node_id: indextree::NodeId) -> Option<&ComponentNode> {
62        self.tree.get(node_id).map(|n| n.get())
63    }
64
65    /// Get mutable node by NodeId
66    pub fn get_mut(&mut self, node_id: indextree::NodeId) -> Option<&mut ComponentNode> {
67        self.tree.get_mut(node_id).map(|n| n.get_mut())
68    }
69
70    /// Get current node
71    pub fn current_node(&self) -> Option<&ComponentNode> {
72        self.node_queue
73            .last()
74            .and_then(|node_id| self.get(*node_id))
75    }
76
77    /// Get mutable current node
78    pub fn current_node_mut(&mut self) -> Option<&mut ComponentNode> {
79        let node_id = self.node_queue.last()?;
80        self.get_mut(*node_id)
81    }
82
83    /// Add a new node to the tree
84    /// Nodes now store their intrinsic constraints in their metadata.
85    /// The `node_component` itself primarily holds the measure_fn.
86    pub fn add_node(&mut self, node_component: ComponentNode) {
87        let new_node_id = self.tree.new_node(node_component);
88        if let Some(current_node_id) = self.node_queue.last_mut() {
89            current_node_id.append(new_node_id, &mut self.tree);
90        }
91        let metadata = ComponentNodeMetaData::none();
92        self.metadatas.insert(new_node_id, metadata);
93        self.node_queue.push(new_node_id);
94    }
95
96    /// Pop the last node from the queue
97    pub fn pop_node(&mut self) {
98        self.node_queue.pop();
99    }
100
101    /// Compute the ComponentTree into a list of rendering commands
102    ///
103    /// This method processes the component tree through three main phases:
104    /// 1. **Measure Phase**: Calculate sizes and positions for all components
105    /// 2. **Command Generation**: Extract draw commands from component metadata
106    /// 3. **State Handling**: Process user interactions and events
107    ///
108    /// Returns a tuple of (commands, window_requests) where commands contain
109    /// the rendering instructions with their associated sizes and positions.
110    pub fn compute(
111        &mut self,
112        screen_size: PxSize,
113        cursor_position: Option<PxPosition>,
114        mut cursor_events: Vec<CursorEvent>,
115        mut keyboard_events: Vec<winit::event::KeyEvent>,
116        mut ime_events: Vec<winit::event::Ime>,
117        compute_resource_manager: Arc<RwLock<ComputeResourceManager>>,
118        gpu: &wgpu::Device,
119    ) -> (Vec<(Command, PxSize, PxPosition)>, WindowRequests) {
120        let Some(root_node) = self.tree.get_node_id_at(NonZero::new(1).unwrap()) else {
121            return (vec![], WindowRequests::default());
122        };
123        let screen_constraint = Constraint::new(
124            DimensionValue::Fixed(screen_size.width),
125            DimensionValue::Fixed(screen_size.height),
126        );
127
128        let measure_timer = Instant::now();
129        debug!("Start measuring the component tree...");
130
131        // Call measure_node with &self.tree and &self.metadatas
132        // Handle the Result from measure_node
133        match measure_node(
134            root_node,
135            &screen_constraint,
136            &self.tree,
137            &self.metadatas,
138            compute_resource_manager,
139            gpu,
140        ) {
141            Ok(_root_computed_data) => {
142                debug!("Component tree measured in {:?}", measure_timer.elapsed());
143            }
144            Err(e) => {
145                panic!(
146                    "Root node ({root_node:?}) measurement failed: {e:?}. Aborting draw command computation."
147                );
148            }
149        }
150
151        let compute_draw_timer = Instant::now();
152        debug!("Start computing draw commands...");
153        // compute_draw_commands_parallel expects &ComponentNodeTree and &ComponentNodeMetaDatas
154        // It also uses get_mut on metadatas internally, which is fine for DashMap with &self.
155        let commands = compute_draw_commands_parallel(root_node, &self.tree, &self.metadatas);
156        debug!(
157            "Draw commands computed in {:?}, total commands: {}",
158            compute_draw_timer.elapsed(),
159            commands.len()
160        );
161
162        let state_handler_timer = Instant::now();
163        let mut window_requests = WindowRequests::default();
164        debug!("Start executing state handlers...");
165        for node_id in root_node
166            .reverse_traverse(&self.tree)
167            .filter_map(|edge| match edge {
168                indextree::NodeEdge::Start(id) => Some(id),
169                indextree::NodeEdge::End(_) => None,
170            })
171        {
172            let Some(state_handler) = self
173                .tree
174                .get(node_id)
175                .and_then(|n| n.get().state_handler_fn.as_ref())
176            else {
177                continue;
178            };
179
180            // Compute the relative cursor position for the current node, if available
181            let current_cursor_position = cursor_position.map(|pos| {
182                // Get the absolute position of the current node
183                let abs_pos = self
184                    .metadatas
185                    .get(&node_id)
186                    .and_then(|m| m.abs_position)
187                    .unwrap_or(PxPosition::ZERO);
188                // Calculate the relative position
189                pos - abs_pos
190            });
191            // Get the computed_data for the current node
192            let computed_data_option = self.metadatas.get(&node_id).and_then(|m| m.computed_data);
193
194            if let Some(node_computed_data) = computed_data_option {
195                // Check if computed_data exists
196                let input = StateHandlerInput {
197                    node_id,
198                    computed_data: node_computed_data,
199                    cursor_position: current_cursor_position,
200                    cursor_events: &mut cursor_events,
201                    keyboard_events: &mut keyboard_events,
202                    requests: &mut window_requests,
203                    ime_events: &mut ime_events,
204                };
205                state_handler(input);
206                // if state_handler set ime request, it's position must be None, and we set it here
207                if let Some(ref mut ime_request) = window_requests.ime_request
208                    && ime_request.position.is_none()
209                {
210                    ime_request.position = Some(
211                        self.metadatas
212                            .get(&node_id)
213                            .and_then(|m| m.abs_position)
214                            .unwrap(),
215                    )
216                }
217            } else {
218                log::warn!(
219                    "Computed data not found for node {node_id:?} during state handler execution."
220                );
221            }
222        }
223        debug!(
224            "State handlers executed in {:?}",
225            state_handler_timer.elapsed()
226        );
227        (commands, window_requests)
228    }
229}
230
231/// Parallel computation of draw commands from the component tree
232///
233/// This function traverses the component tree and extracts rendering commands
234/// from each node's metadata. It uses parallel processing for better performance
235/// when dealing with large component trees.
236///
237/// The function maintains thread-safety by using DashMap's concurrent access
238/// capabilities, allowing multiple threads to safely read and modify metadata.
239fn compute_draw_commands_parallel(
240    node_id: indextree::NodeId,
241    tree: &ComponentNodeTree,
242    metadatas: &ComponentNodeMetaDatas,
243) -> Vec<(Command, PxSize, PxPosition)> {
244    compute_draw_commands_inner_parallel(PxPosition::ZERO, true, node_id, tree, metadatas)
245}
246
247fn compute_draw_commands_inner_parallel(
248    start_pos: PxPosition,
249    is_root: bool,
250    node_id: indextree::NodeId,
251    tree: &ComponentNodeTree,
252    metadatas: &ComponentNodeMetaDatas,
253) -> Vec<(Command, PxSize, PxPosition)> {
254    let mut local_commands = Vec::new();
255
256    // Process current node's metadata and extract its rendering commands
257    if let Some(mut entry) = metadatas.get_mut(&node_id) {
258        // Calculate absolute position: root nodes start at origin, others use relative positioning
259        let rel_pos = match entry.rel_position {
260            Some(pos) => pos,
261            None if is_root => PxPosition::ZERO,
262            _ => return local_commands, // Skip nodes without position data
263        };
264        let self_pos = start_pos + rel_pos;
265        entry.abs_position = Some(self_pos);
266
267        // Extract size from computed data, defaulting to zero if unavailable
268        let size = entry
269            .computed_data
270            .map(|d| PxSize {
271                width: d.width,
272                height: d.height,
273            })
274            .unwrap_or_default();
275
276        // Drain all commands from this node and add them to the output
277        // Note: Commands are now stored directly as Command enum instead of boxed trait objects
278        for cmd in entry.commands.drain(..) {
279            local_commands.push((cmd, size, self_pos));
280        }
281    }
282
283    // Process all child nodes in parallel for better performance
284    let children: Vec<_> = node_id.children(tree).collect();
285    let child_results: Vec<Vec<_>> = children
286        .into_par_iter()
287        .map(|child| {
288            // Use current node's absolute position as starting point for children
289            let self_pos = metadatas
290                .get(&node_id)
291                .and_then(|m| m.abs_position)
292                .unwrap_or(start_pos);
293            compute_draw_commands_inner_parallel(self_pos, false, child, tree, metadatas)
294        })
295        .collect();
296
297    // Flatten all child commands into the local command list
298    for child_cmds in child_results {
299        local_commands.extend(child_cmds);
300    }
301
302    local_commands
303}