tessera_ui/component_tree/node.rs
1use std::{
2 collections::HashMap,
3 ops::{Add, AddAssign},
4 sync::Arc,
5 time::Instant,
6};
7
8use dashmap::DashMap;
9use indextree::NodeId;
10use log::debug;
11use parking_lot::RwLock;
12use rayon::prelude::*;
13use winit::window::CursorIcon;
14
15use crate::{
16 ComputeCommand, ComputeResourceManager, DrawCommand, Px,
17 cursor::CursorEvent,
18 px::{PxPosition, PxSize},
19 renderer::Command,
20};
21
22use super::constraint::{Constraint, DimensionValue};
23
24/// A ComponentNode is a node in the component tree.
25/// It represents all information about a component.
26pub struct ComponentNode {
27 /// Component function's name, for debugging purposes.
28 pub fn_name: String,
29 /// Describes the component in layout.
30 /// None means using default measure policy which places children at the top-left corner
31 /// of the parent node, with no offset.
32 pub measure_fn: Option<Box<MeasureFn>>,
33 /// Describes the state handler for the component.
34 /// This is used to handle state changes.
35 pub state_handler_fn: Option<Box<StateHandlerFn>>,
36}
37
38/// Contains metadata of the component node.
39#[derive(Default)]
40pub struct ComponentNodeMetaData {
41 /// The computed data (size) of the node.
42 /// None if the node is not computed yet.
43 pub computed_data: Option<ComputedData>,
44 /// The node's start position, relative to its parent.
45 /// None if the node is not placed yet.
46 pub rel_position: Option<PxPosition>,
47 /// The node's start position, relative to the root window.
48 /// This will be computed during drawing command's generation.
49 /// None if the node is not drawn yet.
50 pub abs_position: Option<PxPosition>,
51 /// Commands associated with this node.
52 ///
53 /// This stores both draw and compute commands in a unified vector using the
54 /// new `Command` enum. Commands are collected during the measure phase and
55 /// executed during rendering. The order of commands in this vector determines
56 /// their execution order.
57 pub(crate) commands: Vec<Command>,
58}
59
60impl ComponentNodeMetaData {
61 /// Creates a new `ComponentNodeMetaData` with default values.
62 pub fn none() -> Self {
63 Self {
64 computed_data: None,
65 rel_position: None,
66 abs_position: None,
67 commands: Vec::new(),
68 }
69 }
70
71 /// Pushes a draw command to the node's metadata.
72 ///
73 /// Draw commands are responsible for rendering visual content (shapes, text, images).
74 /// This method wraps the command in the unified `Command::Draw` variant and adds it
75 /// to the command queue. Commands are executed in the order they are added.
76 ///
77 /// # Example
78 /// ```rust,ignore
79 /// metadata.push_draw_command(ShapeCommand::Rect {
80 /// color: [1.0, 0.0, 0.0, 1.0],
81 /// corner_radius: 8.0,
82 /// shadow: None,
83 /// });
84 /// ```
85 pub fn push_draw_command(&mut self, command: impl DrawCommand + 'static) {
86 let command = Box::new(command);
87 let command = command as Box<dyn DrawCommand>;
88 let command = Command::Draw(command);
89 self.commands.push(command);
90 }
91
92 /// Pushes a compute command to the node's metadata.
93 ///
94 /// Compute commands perform GPU computation tasks (post-processing effects,
95 /// complex calculations). This method wraps the command in the unified
96 /// `Command::Compute` variant and adds it to the command queue.
97 ///
98 /// # Example
99 /// ```rust,ignore
100 /// metadata.push_compute_command(BlurCommand {
101 /// radius: 5.0,
102 /// sigma: 2.0,
103 /// });
104 /// ```
105 pub fn push_compute_command(&mut self, command: impl ComputeCommand + 'static) {
106 let command = Box::new(command);
107 let command = command as Box<dyn ComputeCommand>;
108 let command = Command::Compute(command);
109 self.commands.push(command);
110 }
111}
112
113/// A tree of component nodes, using `indextree::Arena` for storage.
114pub type ComponentNodeTree = indextree::Arena<ComponentNode>;
115/// Contains all component nodes' metadatas, using a thread-safe `DashMap`.
116pub type ComponentNodeMetaDatas = DashMap<NodeId, ComponentNodeMetaData>;
117
118/// Represents errors that can occur during node measurement.
119#[derive(Debug, Clone, PartialEq)]
120pub enum MeasurementError {
121 /// Indicates that the specified node was not found in the component tree.
122 NodeNotFoundInTree,
123 /// Indicates that metadata for the specified node was not found (currently not a primary error source in measure_node).
124 NodeNotFoundInMeta,
125 /// Indicates that the custom measure function (`MeasureFn`) for a node failed.
126 /// Contains a string detailing the failure.
127 MeasureFnFailed(String),
128 /// Indicates that the measurement of a child node failed during a parent's layout calculation (e.g., in `DEFAULT_LAYOUT_DESC`).
129 /// Contains the `NodeId` of the child that failed.
130 ChildMeasurementFailed(NodeId),
131}
132
133/// A `MeasureFn` is a function that takes an input `Constraint` and its children nodes,
134/// finishes placementing inside, and returns its size (`ComputedData`) or an error.
135pub type MeasureFn =
136 dyn Fn(&MeasureInput<'_>) -> Result<ComputedData, MeasurementError> + Send + Sync;
137
138/// Input for the measure function (`MeasureFn`).
139pub struct MeasureInput<'a> {
140 /// The `NodeId` of the current node being measured.
141 pub current_node_id: indextree::NodeId,
142 /// The component tree containing all nodes.
143 pub tree: &'a ComponentNodeTree,
144 /// The effective constraint for this node, merged with its parent's constraint.
145 pub parent_constraint: &'a Constraint,
146 /// The children nodes of the current node.
147 pub children_ids: &'a [indextree::NodeId],
148 /// Metadata for all component nodes, used to access cached data and constraints.
149 pub metadatas: &'a ComponentNodeMetaDatas,
150 /// Compute resources manager
151 pub compute_resource_manager: Arc<RwLock<ComputeResourceManager>>,
152 /// Gpu device
153 pub gpu: &'a wgpu::Device,
154}
155
156/// A `StateHandlerFn` is a function that handles state changes for a component.
157///
158/// The rule of execution order is:
159///
160/// 1. Children's state handlers are executed earlier than parent's.
161/// 2. Newer components' state handlers are executed earlier than older ones.
162///
163/// Acutally, rule 2 includes rule 1, because a newer component is always a child of an older component :)
164pub type StateHandlerFn = dyn Fn(StateHandlerInput) + Send + Sync;
165
166/// Input for the state handler function (`StateHandlerFn`).
167///
168/// Note that you can modify the `cursor_events` and `keyboard_events` vectors
169/// for exmaple block some keyboard events or cursor events to prevent them from propagating
170/// to parent components and older brother components.
171pub struct StateHandlerInput<'a> {
172 /// The `NodeId` of the component node that this state handler is for.
173 /// Usually used to access the component's metadata.
174 pub node_id: indextree::NodeId,
175 /// The size of the component node, computed during the measure stage.
176 pub computed_data: ComputedData,
177 /// The position of the cursor, if available.
178 /// Relative to the root position of the component.
179 pub cursor_position: Option<PxPosition>,
180 /// Cursor events from the event loop, if any.
181 pub cursor_events: &'a mut Vec<CursorEvent>,
182 /// Keyboard events from the event loop, if any.
183 pub keyboard_events: &'a mut Vec<winit::event::KeyEvent>,
184 /// IME events from the event loop, if any.
185 pub ime_events: &'a mut Vec<winit::event::Ime>,
186 /// A context for making requests to the window for the current frame.
187 pub requests: &'a mut WindowRequests,
188}
189
190/// A collection of requests that components can make to the windowing system for the current frame.
191/// This struct's lifecycle is confined to a single `compute` pass.
192#[derive(Default, Debug)]
193pub struct WindowRequests {
194 /// The cursor icon requested by a component. If multiple components request a cursor,
195 /// the last one to make a request in a frame "wins", since it's executed later.
196 pub cursor_icon: CursorIcon,
197 /// An Input Method Editor (IME) request.
198 /// If multiple components request IME, the one from the "newer" component (which is
199 /// processed later in the state handling pass) will overwrite previous requests.
200 pub ime_request: Option<ImeRequest>,
201}
202
203/// A request to the windowing system to open an Input Method Editor (IME).
204/// This is typically used for text input components.
205#[derive(Debug)]
206pub struct ImeRequest {
207 /// The size of the area where the IME is requested.
208 pub size: PxSize,
209 /// The absolute position where the IME should be placed.
210 /// This is set internally by the component tree during the compute pass.
211 pub(crate) position: Option<PxPosition>, // should be setted in tessera node tree compute
212}
213
214impl ImeRequest {
215 pub fn new(size: PxSize) -> Self {
216 Self {
217 size,
218 position: None, // Position will be set during the compute phase
219 }
220 }
221}
222
223/// Measures a single node recursively, returning its size or an error.
224///
225/// See [`measure_nodes`] for concurrent measurement of multiple nodes.
226/// Which is very recommended for most cases. You should only use this function
227/// when your're very sure that you only need to measure a single node.
228pub fn measure_node(
229 node_id: NodeId,
230 parent_constraint: &Constraint,
231 tree: &ComponentNodeTree,
232 component_node_metadatas: &ComponentNodeMetaDatas,
233 compute_resource_manager: Arc<RwLock<ComputeResourceManager>>,
234 gpu: &wgpu::Device,
235) -> Result<ComputedData, MeasurementError> {
236 let node_data_ref = tree
237 .get(node_id)
238 .ok_or(MeasurementError::NodeNotFoundInTree)?;
239 let node_data = node_data_ref.get();
240
241 let children: Vec<_> = node_id.children(tree).collect(); // No .as_ref() needed for &Arena
242 let timer = Instant::now();
243
244 debug!(
245 "Measuring node {} with {} children, parent constraint: {:?}",
246 node_data.fn_name,
247 children.len(),
248 parent_constraint
249 );
250
251 let size = if let Some(measure_fn) = &node_data.measure_fn {
252 measure_fn(&MeasureInput {
253 current_node_id: node_id,
254 tree,
255 parent_constraint,
256 children_ids: &children,
257 metadatas: component_node_metadatas,
258 compute_resource_manager,
259 gpu,
260 })
261 } else {
262 DEFAULT_LAYOUT_DESC(&MeasureInput {
263 current_node_id: node_id,
264 tree,
265 parent_constraint,
266 children_ids: &children,
267 metadatas: component_node_metadatas,
268 compute_resource_manager,
269 gpu,
270 })
271 }?;
272
273 debug!(
274 "Measured node {} in {:?} with size {:?}",
275 node_data.fn_name,
276 timer.elapsed(),
277 size
278 );
279
280 let mut metadata = component_node_metadatas.entry(node_id).or_default();
281 metadata.computed_data = Some(size);
282
283 Ok(size)
284}
285
286/// Places a node at the specified relative position within its parent.
287pub fn place_node(
288 node: indextree::NodeId,
289 rel_position: PxPosition,
290 component_node_metadatas: &ComponentNodeMetaDatas,
291) {
292 component_node_metadatas
293 .entry(node)
294 .or_default()
295 .rel_position = Some(rel_position);
296}
297
298/// A default layout descriptor (`MeasureFn`) that places children at the top-left corner ([0,0])
299/// of the parent node with no offset. Children are measured concurrently using `measure_nodes`.
300pub const DEFAULT_LAYOUT_DESC: &MeasureFn = &|input| {
301 if input.children_ids.is_empty() {
302 // If there are no children, the size depends on the parent_constraint
303 // For Fixed, it's the fixed size. For Wrap/Fill, it's typically 0 if no content.
304 // This part might need refinement based on how min constraints in Wrap/Fill should behave for empty nodes.
305 // For now, returning ZERO, assuming intrinsic size of an empty node is zero before min constraints are applied.
306 // The actual min size enforcement happens when the parent (or this node itself if it has intrinsic min)
307 // considers its own DimensionValue.
308 return Ok(ComputedData::min_from_constraint(input.parent_constraint));
309 }
310
311 let nodes_to_measure: Vec<(NodeId, Constraint)> = input
312 .children_ids
313 .iter()
314 .map(|&child_id| (child_id, *input.parent_constraint)) // Children inherit parent's effective constraint
315 .collect();
316
317 let children_results_map = measure_nodes(
318 nodes_to_measure,
319 input.tree,
320 input.metadatas,
321 input.compute_resource_manager.clone(),
322 input.gpu,
323 );
324
325 let mut aggregate_size = ComputedData::ZERO;
326 let mut first_error: Option<MeasurementError> = None;
327 let mut successful_children_data = Vec::new();
328
329 for &child_id in input.children_ids {
330 match children_results_map.get(&child_id) {
331 Some(Ok(child_size)) => {
332 successful_children_data.push((child_id, *child_size));
333 }
334 Some(Err(e)) => {
335 debug!(
336 "Child node {child_id:?} measurement failed for parent {:?}: {e:?}",
337 input.current_node_id
338 );
339 if first_error.is_none() {
340 first_error = Some(MeasurementError::ChildMeasurementFailed(child_id));
341 }
342 }
343 None => {
344 debug!(
345 "Child node {child_id:?} was not found in measure_nodes results for parent {:?}",
346 input.current_node_id
347 );
348 if first_error.is_none() {
349 first_error = Some(MeasurementError::MeasureFnFailed(format!(
350 "Result for child {child_id:?} missing"
351 )));
352 }
353 }
354 }
355 }
356
357 if let Some(error) = first_error {
358 return Err(error);
359 }
360 if successful_children_data.is_empty() && !input.children_ids.is_empty() {
361 // This case should ideally be caught by first_error if all children failed.
362 // If it's reached, it implies some logic issue.
363 return Err(MeasurementError::MeasureFnFailed(
364 "All children failed to measure or results missing in DEFAULT_LAYOUT_DESC".to_string(),
365 ));
366 }
367
368 // For default layout (stacking), the aggregate size is the max of children's sizes.
369 for (child_id, child_size) in successful_children_data {
370 aggregate_size = aggregate_size.max(child_size);
371 place_node(child_id, PxPosition::ZERO, input.metadatas); // All children at [0,0] for simple stacking
372 }
373
374 // The aggregate_size is based on children. Now apply current node's own constraints.
375 // If current node is Fixed, its size is fixed.
376 // If current node is Wrap, its size is aggregate_size (clamped by its own min/max).
377 // If current node is Fill, its size is aggregate_size (clamped by its own min/max, and parent's available space if parent was Fill).
378 // This final clamping/adjustment based on `parent_constraint` should ideally happen
379 // when `ComputedData` is returned from `measure_node` itself, or by the caller of `measure_node`.
380 // For DEFAULT_LAYOUT_DESC, it should return the size required by its children,
381 // and then `measure_node` will finalize it based on `parent_constraint`.
382
383 // Let's refine: DEFAULT_LAYOUT_DESC should calculate the "natural" size based on children.
384 // Then, `measure_node` (or its caller) would apply the `parent_constraint` to this natural size.
385 // However, `measure_node` currently directly returns the result of `DEFAULT_LAYOUT_DESC` or custom `measure_fn`.
386 // So, `DEFAULT_LAYOUT_DESC` itself needs to consider `parent_constraint` for its final size.
387
388 let mut final_width = aggregate_size.width;
389 let mut final_height = aggregate_size.height;
390
391 match input.parent_constraint.width {
392 DimensionValue::Fixed(w) => final_width = w,
393 DimensionValue::Wrap { min, max } => {
394 if let Some(min_w) = min {
395 final_width = final_width.max(min_w);
396 }
397 if let Some(max_w) = max {
398 final_width = final_width.min(max_w);
399 }
400 }
401 DimensionValue::Fill { min, max } => {
402 // Fill behaves like wrap for default layout unless children expand
403 if let Some(min_w) = min {
404 final_width = final_width.max(min_w);
405 }
406 if let Some(max_w) = max {
407 final_width = final_width.min(max_w);
408 }
409 // If parent was Fill, this node would have gotten a Fill constraint too.
410 // The actual "filling" happens because children might be Fill.
411 // If children are not Fill, this node wraps them.
412 }
413 }
414 match input.parent_constraint.height {
415 DimensionValue::Fixed(h) => final_height = h,
416 DimensionValue::Wrap { min, max } => {
417 if let Some(min_h) = min {
418 final_height = final_height.max(min_h);
419 }
420 if let Some(max_h) = max {
421 final_height = final_height.min(max_h);
422 }
423 }
424 DimensionValue::Fill { min, max } => {
425 if let Some(min_h) = min {
426 final_height = final_height.max(min_h);
427 }
428 if let Some(max_h) = max {
429 final_height = final_height.min(max_h);
430 }
431 }
432 }
433 Ok(ComputedData {
434 width: final_width,
435 height: final_height,
436 })
437};
438
439/// Concurrently measures multiple nodes using Rayon for parallelism.
440pub fn measure_nodes(
441 nodes_to_measure: Vec<(NodeId, Constraint)>,
442 tree: &ComponentNodeTree,
443 component_node_metadatas: &ComponentNodeMetaDatas,
444 compute_resource_manager: Arc<RwLock<ComputeResourceManager>>,
445 gpu: &wgpu::Device,
446) -> HashMap<NodeId, Result<ComputedData, MeasurementError>> {
447 if nodes_to_measure.is_empty() {
448 return HashMap::new();
449 }
450 nodes_to_measure
451 .into_par_iter()
452 .map(|(node_id, parent_constraint)| {
453 let result = measure_node(
454 node_id,
455 &parent_constraint,
456 tree,
457 component_node_metadatas,
458 compute_resource_manager.clone(),
459 gpu,
460 );
461 (node_id, result)
462 })
463 .collect::<HashMap<NodeId, Result<ComputedData, MeasurementError>>>()
464}
465
466/// Layout information computed at the measure stage, representing the size of a node.
467#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
468pub struct ComputedData {
469 pub width: Px,
470 pub height: Px,
471}
472
473impl Add for ComputedData {
474 type Output = Self;
475 fn add(self, rhs: Self) -> Self::Output {
476 Self {
477 width: self.width + rhs.width,
478 height: self.height + rhs.height,
479 }
480 }
481}
482
483impl AddAssign for ComputedData {
484 fn add_assign(&mut self, rhs: Self) {
485 *self = *self + rhs;
486 }
487}
488
489impl ComputedData {
490 pub const ZERO: Self = Self {
491 width: Px(0),
492 height: Px(0),
493 };
494
495 /// Calculates a "minimum" size based on a constraint.
496 /// For Fixed, it's the fixed value. For Wrap/Fill, it's their 'min' if Some, else 0.
497 pub fn min_from_constraint(constraint: &Constraint) -> Self {
498 let width = match constraint.width {
499 DimensionValue::Fixed(w) => w,
500 DimensionValue::Wrap { min, .. } => min.unwrap_or(Px(0)),
501 DimensionValue::Fill { min, .. } => min.unwrap_or(Px(0)),
502 };
503 let height = match constraint.height {
504 DimensionValue::Fixed(h) => h,
505 DimensionValue::Wrap { min, .. } => min.unwrap_or(Px(0)),
506 DimensionValue::Fill { min, .. } => min.unwrap_or(Px(0)),
507 };
508 Self { width, height }
509 }
510
511 pub fn min(self, rhs: Self) -> Self {
512 Self {
513 width: self.width.min(rhs.width),
514 height: self.height.min(rhs.height),
515 }
516 }
517
518 pub fn max(self, rhs: Self) -> Self {
519 Self {
520 width: self.width.max(rhs.width),
521 height: self.height.max(rhs.height),
522 }
523 }
524}