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
24pub struct ComponentTree {
26 tree: indextree::Arena<ComponentNode>,
28 metadatas: ComponentNodeMetaDatas,
30 node_queue: Vec<indextree::NodeId>,
32}
33
34impl Default for ComponentTree {
35 fn default() -> Self {
36 Self::new()
37 }
38}
39
40impl ComponentTree {
41 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 pub fn clear(&mut self) {
55 self.tree.clear();
56 self.metadatas.clear();
57 self.node_queue.clear();
58 }
59
60 pub fn get(&self, node_id: indextree::NodeId) -> Option<&ComponentNode> {
62 self.tree.get(node_id).map(|n| n.get())
63 }
64
65 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 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 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 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 pub fn pop_node(&mut self) {
98 self.node_queue.pop();
99 }
100
101 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 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 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 let current_cursor_position = cursor_position.map(|pos| {
182 let abs_pos = self
184 .metadatas
185 .get(&node_id)
186 .and_then(|m| m.abs_position)
187 .unwrap_or(PxPosition::ZERO);
188 pos - abs_pos
190 });
191 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 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 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
231fn 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 if let Some(mut entry) = metadatas.get_mut(&node_id) {
258 let rel_pos = match entry.rel_position {
260 Some(pos) => pos,
261 None if is_root => PxPosition::ZERO,
262 _ => return local_commands, };
264 let self_pos = start_pos + rel_pos;
265 entry.abs_position = Some(self_pos);
266
267 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 for cmd in entry.commands.drain(..) {
279 local_commands.push((cmd, size, self_pos));
280 }
281 }
282
283 let children: Vec<_> = node_id.children(tree).collect();
285 let child_results: Vec<Vec<_>> = children
286 .into_par_iter()
287 .map(|child| {
288 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 for child_cmds in child_results {
299 local_commands.extend(child_cmds);
300 }
301
302 local_commands
303}