Skip to main content

whisker_engine/
scene.rs

1//! Retained scene state and coalescing frame journal.
2
3use std::collections::{BTreeMap, HashMap};
4use std::error::Error;
5use std::fmt;
6use std::sync::Arc;
7
8use whisker_protocol::{
9    Accessibility, BackgroundLayer, BoxClip, BoxPaint, CommandId, Cursor, ElementTypeId,
10    FrameHeader, FrameMode, FramePacket, HitTestBehavior, LayoutGeometry, NodeId, Operation,
11    PointerId, PropertyId, ProtocolVersion, SurfaceId, TextContent, TextContentError,
12    TextStyleSnapshot, Transform, Visibility, VisualEffects, WhiskerValue,
13};
14#[cfg(test)]
15use whisker_protocol::{InputPoint, OverflowClip};
16
17mod hit_test;
18
19/// A retained logical node owned by a [`Scene`].
20#[derive(Clone, Debug, PartialEq)]
21pub struct SceneNode {
22    element_type: ElementTypeId,
23    parent: Option<NodeId>,
24    children: Vec<NodeId>,
25    layout: Option<LayoutGeometry>,
26    box_paint: Option<BoxPaint>,
27    background_layers: Vec<BackgroundLayer>,
28    visual_effects: VisualEffects,
29    clip: Option<BoxClip>,
30    transform: Option<Transform>,
31    opacity: Option<f32>,
32    visibility: Option<Visibility>,
33    z_order: Option<i32>,
34    text: Option<TextContent>,
35    text_style: Option<TextStyleSnapshot>,
36    accessibility: Option<Accessibility>,
37    properties: BTreeMap<PropertyId, WhiskerValue>,
38    event_mask: Option<u64>,
39    hit_test: Option<HitTestBehavior>,
40    cursor: Option<Cursor>,
41    host_scroll_offset: [f32; 2],
42}
43
44impl SceneNode {
45    fn new(element_type: ElementTypeId) -> Self {
46        Self {
47            element_type,
48            parent: None,
49            children: Vec::new(),
50            layout: None,
51            box_paint: None,
52            background_layers: Vec::new(),
53            visual_effects: VisualEffects::default(),
54            clip: None,
55            transform: None,
56            opacity: None,
57            visibility: None,
58            z_order: None,
59            text: None,
60            text_style: None,
61            accessibility: None,
62            properties: BTreeMap::new(),
63            event_mask: None,
64            hit_test: None,
65            cursor: None,
66            host_scroll_offset: [0.0; 2],
67        }
68    }
69
70    /// Returns the current explicitly set element properties.
71    pub fn properties(&self) -> &BTreeMap<PropertyId, WhiskerValue> {
72        &self.properties
73    }
74
75    /// Returns the registered element type.
76    pub const fn element_type(&self) -> ElementTypeId {
77        self.element_type
78    }
79
80    /// Returns the logical parent when attached.
81    pub const fn parent(&self) -> Option<NodeId> {
82        self.parent
83    }
84
85    /// Returns children in logical presentation order.
86    pub fn children(&self) -> &[NodeId] {
87        &self.children
88    }
89
90    /// Returns the retained border-box and content-box geometry.
91    pub const fn layout(&self) -> Option<LayoutGeometry> {
92        self.layout
93    }
94
95    /// Returns retained plain-text presentation when this is a text node.
96    pub const fn text(&self) -> Option<&TextContent> {
97        self.text.as_ref()
98    }
99
100    /// Returns the resolved inherited text style retained for native content.
101    pub const fn text_style(&self) -> Option<&TextStyleSnapshot> {
102        self.text_style.as_ref()
103    }
104
105    /// Returns the retained common accessibility semantics.
106    pub const fn accessibility(&self) -> Option<&Accessibility> {
107        self.accessibility.as_ref()
108    }
109
110    /// Returns retained background and border paint.
111    pub const fn box_paint(&self) -> Option<&BoxPaint> {
112        self.box_paint.as_ref()
113    }
114
115    /// Returns retained background image layers in front-to-back order.
116    pub fn background_layers(&self) -> &[BackgroundLayer] {
117        &self.background_layers
118    }
119
120    /// Returns retained visual effects.
121    pub const fn visual_effects(&self) -> &VisualEffects {
122        &self.visual_effects
123    }
124
125    /// Returns retained descendant overflow clipping.
126    pub const fn clip(&self) -> Option<BoxClip> {
127        self.clip
128    }
129
130    /// Returns the retained resolved transform matrix.
131    pub const fn transform(&self) -> Option<Transform> {
132        self.transform
133    }
134
135    /// Returns retained group opacity.
136    pub const fn opacity(&self) -> Option<f32> {
137        self.opacity
138    }
139
140    /// Returns retained paint visibility.
141    pub const fn visibility(&self) -> Option<Visibility> {
142        self.visibility
143    }
144
145    /// Returns retained sibling stacking key.
146    pub const fn z_order(&self) -> Option<i32> {
147        self.z_order
148    }
149
150    /// Returns retained event subscription bits.
151    pub const fn event_mask(&self) -> Option<u64> {
152        self.event_mask
153    }
154
155    /// Returns retained Host hit-test behavior.
156    pub const fn hit_test(&self) -> Option<HitTestBehavior> {
157        self.hit_test
158    }
159
160    /// Returns the retained resolved pointing-device cursor.
161    pub const fn cursor(&self) -> Option<&Cursor> {
162        self.cursor.as_ref()
163    }
164
165    /// Returns the latest Host-owned native scroll position.
166    pub const fn host_scroll_offset(&self) -> [f32; 2] {
167        self.host_scroll_offset
168    }
169}
170
171/// A rejected scene mutation or frame-lifecycle transition.
172#[derive(Clone, Debug, PartialEq)]
173pub enum SceneError {
174    /// A mutation or second preparation was attempted while a frame is pending.
175    FramePending,
176    /// Acceptance or discard was attempted without a prepared frame.
177    NoPendingFrame,
178    /// Renderer accepted a revision other than the prepared target.
179    AcceptedRevisionMismatch {
180        /// Prepared target revision.
181        expected: u64,
182        /// Revision reported by the receiver.
183        received: u64,
184    },
185    /// A node reference is not live in this scene.
186    UnknownNode {
187        /// Missing node.
188        node: NodeId,
189    },
190    /// An insertion tried to attach a node that already has a parent.
191    ChildAlreadyAttached {
192        /// Child being inserted.
193        child: NodeId,
194        /// Existing parent.
195        parent: NodeId,
196    },
197    /// A remove or move operation named a node outside the parent's direct children.
198    NotDirectChild {
199        /// Expected parent.
200        parent: NodeId,
201        /// Node that is not its direct child.
202        child: NodeId,
203    },
204    /// A child position exceeded the resulting child-list length.
205    ChildIndexOutOfBounds {
206        /// Parent whose list was addressed.
207        parent: NodeId,
208        /// Requested position.
209        index: u32,
210        /// Maximum accepted insertion position.
211        len: usize,
212    },
213    /// An insertion would introduce a parent cycle.
214    TreeCycle {
215        /// Requested parent.
216        parent: NodeId,
217        /// Requested child.
218        child: NodeId,
219    },
220    /// Opacity was non-finite or outside `0.0..=1.0`.
221    InvalidOpacity {
222        /// Invalid opacity.
223        opacity: f32,
224    },
225    /// Layout or transform contained NaN or infinity.
226    NonFiniteNumber,
227    /// Plain-text presentation contained invalid shaping inputs.
228    InvalidText {
229        /// Stable invalid-input category.
230        error: TextContentError,
231    },
232    /// Background or border paint contained an invalid value.
233    InvalidBoxPaint,
234    /// One or more retained background image layers were invalid.
235    InvalidBackgroundLayers,
236    /// One or more visual-effect values were invalid.
237    InvalidVisualEffects,
238    /// The scene cannot allocate another node identifier.
239    NodeIdExhausted,
240    /// The scene cannot advance its accepted revision.
241    RevisionExhausted,
242    /// The scene cannot allocate another diagnostic frame identifier.
243    FrameIdExhausted,
244    /// The scene cannot rotate to another recovery epoch.
245    SceneEpochExhausted,
246}
247
248impl fmt::Display for SceneError {
249    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250        write!(f, "Whisker scene error: {self:?}")
251    }
252}
253
254impl Error for SceneError {}
255
256#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
257enum DirtySlot {
258    Layout(NodeId),
259    BoxPaint(NodeId),
260    BackgroundLayers(NodeId),
261    VisualEffects(NodeId),
262    Clip(NodeId),
263    Transform(NodeId),
264    Opacity(NodeId),
265    Visibility(NodeId),
266    ZOrder(NodeId),
267    Text(NodeId),
268    TextStyle(NodeId),
269    Accessibility(NodeId),
270    Property(NodeId, PropertyId),
271    EventMask(NodeId),
272    HitTest(NodeId),
273    Cursor(NodeId),
274    Pointer(NodeId, PointerId),
275}
276
277#[derive(Clone, Debug, Default)]
278struct ChangeJournal {
279    operations: Vec<Operation>,
280    coalesced: HashMap<DirtySlot, usize>,
281}
282
283impl ChangeJournal {
284    fn push_barrier(&mut self, operation: Operation) {
285        self.coalesced.clear();
286        self.operations.push(operation);
287    }
288
289    fn push_coalesced(&mut self, slot: DirtySlot, operation: Operation) {
290        if let Some(index) = self.coalesced.get(&slot).copied() {
291            self.operations[index] = operation;
292        } else {
293            let index = self.operations.len();
294            self.operations.push(operation);
295            self.coalesced.insert(slot, index);
296        }
297    }
298
299    fn clear(&mut self) {
300        self.operations.clear();
301        self.coalesced.clear();
302    }
303}
304
305/// Host-independent retained scene for one surface.
306///
307/// The scene begins in snapshot mode. After a frame is prepared, mutations are
308/// rejected until the caller accepts or discards it. This makes clearing the
309/// journal on acceptance lossless without requiring a second concurrent dirty
310/// generation.
311#[derive(Clone, Debug)]
312pub struct Scene {
313    surface: SurfaceId,
314    protocol: ProtocolVersion,
315    scene_epoch: u32,
316    accepted_revision: u64,
317    next_node_id: u64,
318    next_frame_id: u64,
319    needs_snapshot: bool,
320    nodes: BTreeMap<NodeId, Arc<SceneNode>>,
321    pointer_captures: BTreeMap<PointerId, NodeId>,
322    journal: ChangeJournal,
323    pending: Option<FramePacket>,
324}
325
326impl Scene {
327    /// Creates an empty scene that will emit a snapshot on its first frame.
328    pub fn new(surface: SurfaceId) -> Self {
329        Self::with_protocol(surface, ProtocolVersion::CURRENT)
330    }
331
332    /// Creates an empty scene using the version selected with its Host.
333    pub fn with_protocol(surface: SurfaceId, protocol: ProtocolVersion) -> Self {
334        Self {
335            surface,
336            protocol,
337            scene_epoch: 1,
338            accepted_revision: 0,
339            next_node_id: 1,
340            next_frame_id: 1,
341            needs_snapshot: true,
342            nodes: BTreeMap::new(),
343            pointer_captures: BTreeMap::new(),
344            journal: ChangeJournal::default(),
345            pending: None,
346        }
347    }
348
349    /// Returns the destination surface.
350    pub const fn surface(&self) -> SurfaceId {
351        self.surface
352    }
353
354    /// Returns the current scene epoch.
355    pub const fn scene_epoch(&self) -> u32 {
356        self.scene_epoch
357    }
358
359    /// Returns the last renderer-accepted revision.
360    pub const fn accepted_revision(&self) -> u64 {
361        self.accepted_revision
362    }
363
364    /// Returns the number of live retained nodes.
365    pub fn node_count(&self) -> usize {
366        self.nodes.len()
367    }
368
369    /// Returns a retained node when it is live.
370    pub fn node(&self, node: NodeId) -> Option<&SceneNode> {
371        self.nodes.get(&node).map(Arc::as_ref)
372    }
373
374    /// Retains an immutable node snapshot without copying its content or geometry.
375    pub fn node_snapshot(&self, node: NodeId) -> Option<Arc<SceneNode>> {
376        self.nodes.get(&node).cloned()
377    }
378
379    /// Returns the node currently retaining one pointer capture.
380    pub fn pointer_capture_target(&self, pointer: PointerId) -> Option<NodeId> {
381        self.pointer_captures.get(&pointer).copied()
382    }
383
384    #[cfg(test)]
385    pub(crate) fn set_scene_epoch_for_tests(&mut self, scene_epoch: u32) {
386        self.scene_epoch = scene_epoch;
387    }
388
389    /// Returns whether a snapshot, mutation, command, or retry needs a frame.
390    pub fn has_pending_work(&self) -> bool {
391        self.pending.is_some() || self.needs_snapshot || !self.journal.operations.is_empty()
392    }
393
394    /// Returns whether a prepared frame is waiting for acceptance or discard.
395    pub fn has_prepared_frame(&self) -> bool {
396        self.pending.is_some()
397    }
398
399    /// Creates an unattached retained node and returns its epoch-unique ID.
400    pub fn create_node(&mut self, element_type: ElementTypeId) -> Result<NodeId, SceneError> {
401        self.ensure_mutable()?;
402        let node = NodeId::new(self.next_node_id).ok_or(SceneError::NodeIdExhausted)?;
403        self.next_node_id = self.next_node_id.checked_add(1).unwrap_or(0);
404        self.nodes
405            .insert(node, Arc::new(SceneNode::new(element_type)));
406        self.journal
407            .push_barrier(Operation::CreateNode { node, element_type });
408        Ok(node)
409    }
410
411    /// Deletes a node and its complete retained subtree.
412    pub fn delete_node(&mut self, node: NodeId) -> Result<(), SceneError> {
413        self.ensure_mutable()?;
414        let state = self.require_node(node)?.clone();
415        if let Some(parent) = state.parent {
416            self.nodes
417                .get_mut(&parent)
418                .map(Arc::make_mut)
419                .expect("attached parent remains live")
420                .children
421                .retain(|candidate| *candidate != node);
422        }
423        let mut pending = vec![node];
424        while let Some(current) = pending.pop() {
425            let removed = self
426                .nodes
427                .remove(&current)
428                .expect("retained subtree is internally complete");
429            pending.extend(removed.children.iter().copied());
430        }
431        self.pointer_captures
432            .retain(|_, target| self.nodes.contains_key(target));
433        self.journal.push_barrier(Operation::DeleteNode { node });
434        Ok(())
435    }
436
437    /// Attaches an unattached child at an index.
438    pub fn insert_child(
439        &mut self,
440        parent: NodeId,
441        child: NodeId,
442        index: u32,
443    ) -> Result<(), SceneError> {
444        self.ensure_mutable()?;
445        let len = self.require_node(parent)?.children.len();
446        let child_state = self.require_node(child)?;
447        if let Some(existing) = child_state.parent {
448            return Err(SceneError::ChildAlreadyAttached {
449                child,
450                parent: existing,
451            });
452        }
453        if parent == child || self.is_descendant(child, parent) {
454            return Err(SceneError::TreeCycle { parent, child });
455        }
456        let index = index as usize;
457        if index > len {
458            return Err(SceneError::ChildIndexOutOfBounds {
459                parent,
460                index: index as u32,
461                len,
462            });
463        }
464        self.nodes
465            .get_mut(&parent)
466            .map(Arc::make_mut)
467            .expect("parent checked above")
468            .children
469            .insert(index, child);
470        self.nodes
471            .get_mut(&child)
472            .map(Arc::make_mut)
473            .expect("child checked above")
474            .parent = Some(parent);
475        self.journal.push_barrier(Operation::InsertChild {
476            parent,
477            child,
478            index: index as u32,
479        });
480        Ok(())
481    }
482
483    /// Detaches a direct child without deleting it.
484    pub fn remove_child(&mut self, parent: NodeId, child: NodeId) -> Result<(), SceneError> {
485        self.ensure_mutable()?;
486        self.require_direct_child(parent, child)?;
487        let children = &mut self
488            .nodes
489            .get_mut(&parent)
490            .map(Arc::make_mut)
491            .expect("parent checked above")
492            .children;
493        let position = children
494            .iter()
495            .position(|candidate| *candidate == child)
496            .expect("parent link and child list agree");
497        children.remove(position);
498        self.nodes
499            .get_mut(&child)
500            .map(Arc::make_mut)
501            .expect("child checked above")
502            .parent = None;
503        self.journal
504            .push_barrier(Operation::RemoveChild { parent, child });
505        Ok(())
506    }
507
508    /// Moves a direct child within its current parent.
509    pub fn move_child(
510        &mut self,
511        parent: NodeId,
512        child: NodeId,
513        index: u32,
514    ) -> Result<(), SceneError> {
515        self.ensure_mutable()?;
516        self.require_direct_child(parent, child)?;
517        let children = &mut self
518            .nodes
519            .get_mut(&parent)
520            .map(Arc::make_mut)
521            .expect("parent checked above")
522            .children;
523        let old_index = children
524            .iter()
525            .position(|candidate| *candidate == child)
526            .expect("parent link and child list agree");
527        children.remove(old_index);
528        let index = index as usize;
529        if index > children.len() {
530            children.insert(old_index, child);
531            return Err(SceneError::ChildIndexOutOfBounds {
532                parent,
533                index: index as u32,
534                len: children.len() - 1,
535            });
536        }
537        children.insert(index, child);
538        self.journal.push_barrier(Operation::MoveChild {
539            parent,
540            child,
541            index: index as u32,
542        });
543        Ok(())
544    }
545
546    /// Sets resolved layout when it differs from retained state.
547    pub fn set_layout(
548        &mut self,
549        node: NodeId,
550        geometry: impl Into<LayoutGeometry>,
551    ) -> Result<(), SceneError> {
552        self.ensure_mutable()?;
553        let geometry = geometry.into();
554        if !geometry.is_valid() {
555            return Err(SceneError::NonFiniteNumber);
556        }
557        if self.require_node(node)?.layout == Some(geometry) {
558            return Ok(());
559        }
560        self.nodes
561            .get_mut(&node)
562            .map(Arc::make_mut)
563            .expect("node checked above")
564            .layout = Some(geometry);
565        self.journal.push_coalesced(
566            DirtySlot::Layout(node),
567            Operation::SetLayout { node, geometry },
568        );
569        Ok(())
570    }
571
572    /// Sets background and border paint when it differs from retained state.
573    pub fn set_box_paint(&mut self, node: NodeId, paint: BoxPaint) -> Result<(), SceneError> {
574        self.ensure_mutable()?;
575        if !paint.validate() {
576            return Err(SceneError::InvalidBoxPaint);
577        }
578        if self.require_node(node)?.box_paint.as_ref() == Some(&paint) {
579            return Ok(());
580        }
581        self.nodes
582            .get_mut(&node)
583            .map(Arc::make_mut)
584            .expect("node checked above")
585            .box_paint = Some(paint.clone());
586        self.journal.push_coalesced(
587            DirtySlot::BoxPaint(node),
588            Operation::SetBoxPaint { node, paint },
589        );
590        Ok(())
591    }
592
593    /// Sets the ordered background image layers when they differ from retained
594    /// state. An empty list clears every image while preserving box color.
595    pub fn set_background_layers(
596        &mut self,
597        node: NodeId,
598        layers: Vec<BackgroundLayer>,
599    ) -> Result<(), SceneError> {
600        self.ensure_mutable()?;
601        if !layers.iter().all(BackgroundLayer::validate) {
602            return Err(SceneError::InvalidBackgroundLayers);
603        }
604        if self.require_node(node)?.background_layers == layers {
605            return Ok(());
606        }
607        self.nodes
608            .get_mut(&node)
609            .map(Arc::make_mut)
610            .expect("node checked above")
611            .background_layers = layers.clone();
612        self.journal.push_coalesced(
613            DirtySlot::BackgroundLayers(node),
614            Operation::SetBackgroundLayers { node, layers },
615        );
616        Ok(())
617    }
618
619    /// Sets resolved visual effects when they differ from retained state.
620    pub fn set_visual_effects(
621        &mut self,
622        node: NodeId,
623        effects: VisualEffects,
624    ) -> Result<(), SceneError> {
625        self.ensure_mutable()?;
626        if !effects.validate() {
627            return Err(SceneError::InvalidVisualEffects);
628        }
629        if self.require_node(node)?.visual_effects == effects {
630            return Ok(());
631        }
632        self.nodes
633            .get_mut(&node)
634            .map(Arc::make_mut)
635            .expect("node checked above")
636            .visual_effects = effects.clone();
637        self.journal.push_coalesced(
638            DirtySlot::VisualEffects(node),
639            Operation::SetVisualEffects { node, effects },
640        );
641        Ok(())
642    }
643
644    /// Sets descendant overflow clipping when it differs from retained state.
645    pub fn set_clip(&mut self, node: NodeId, clip: BoxClip) -> Result<(), SceneError> {
646        self.ensure_mutable()?;
647        if self.require_node(node)?.clip == Some(clip) {
648            return Ok(());
649        }
650        self.nodes
651            .get_mut(&node)
652            .map(Arc::make_mut)
653            .expect("node checked above")
654            .clip = Some(clip);
655        self.journal
656            .push_coalesced(DirtySlot::Clip(node), Operation::SetClip { node, clip });
657        Ok(())
658    }
659
660    /// Sets a resolved transform when it differs from retained state.
661    pub fn set_transform(&mut self, node: NodeId, transform: Transform) -> Result<(), SceneError> {
662        self.ensure_mutable()?;
663        if !transform.0.into_iter().all(f32::is_finite) {
664            return Err(SceneError::NonFiniteNumber);
665        }
666        if self.require_node(node)?.transform == Some(transform) {
667            return Ok(());
668        }
669        self.nodes
670            .get_mut(&node)
671            .map(Arc::make_mut)
672            .expect("node checked above")
673            .transform = Some(transform);
674        self.journal.push_coalesced(
675            DirtySlot::Transform(node),
676            Operation::SetTransform { node, transform },
677        );
678        Ok(())
679    }
680
681    /// Sets resolved opacity when it differs from retained state.
682    pub fn set_opacity(&mut self, node: NodeId, opacity: f32) -> Result<(), SceneError> {
683        self.ensure_mutable()?;
684        if !opacity.is_finite() || !(0.0..=1.0).contains(&opacity) {
685            return Err(SceneError::InvalidOpacity { opacity });
686        }
687        if self.require_node(node)?.opacity == Some(opacity) {
688            return Ok(());
689        }
690        self.nodes
691            .get_mut(&node)
692            .map(Arc::make_mut)
693            .expect("node checked above")
694            .opacity = Some(opacity);
695        self.journal.push_coalesced(
696            DirtySlot::Opacity(node),
697            Operation::SetOpacity { node, opacity },
698        );
699        Ok(())
700    }
701
702    /// Sets resolved visibility when it differs from retained state.
703    pub fn set_visibility(
704        &mut self,
705        node: NodeId,
706        visibility: Visibility,
707    ) -> Result<(), SceneError> {
708        self.ensure_mutable()?;
709        if self.require_node(node)?.visibility == Some(visibility) {
710            return Ok(());
711        }
712        self.nodes
713            .get_mut(&node)
714            .map(Arc::make_mut)
715            .expect("node checked above")
716            .visibility = Some(visibility);
717        self.journal.push_coalesced(
718            DirtySlot::Visibility(node),
719            Operation::SetVisibility { node, visibility },
720        );
721        Ok(())
722    }
723
724    /// Sets resolved stacking order when it differs from retained state.
725    pub fn set_z_order(&mut self, node: NodeId, z_order: i32) -> Result<(), SceneError> {
726        self.ensure_mutable()?;
727        if self.require_node(node)?.z_order == Some(z_order) {
728            return Ok(());
729        }
730        self.nodes
731            .get_mut(&node)
732            .map(Arc::make_mut)
733            .expect("node checked above")
734            .z_order = Some(z_order);
735        self.journal.push_coalesced(
736            DirtySlot::ZOrder(node),
737            Operation::SetZOrder { node, z_order },
738        );
739        Ok(())
740    }
741
742    /// Sets plain-text presentation when it differs from retained state.
743    pub fn set_text(&mut self, node: NodeId, content: TextContent) -> Result<(), SceneError> {
744        self.ensure_mutable()?;
745        content
746            .validate()
747            .map_err(|error| SceneError::InvalidText { error })?;
748        if self.require_node(node)?.text.as_ref() == Some(&content) {
749            return Ok(());
750        }
751        self.nodes
752            .get_mut(&node)
753            .map(Arc::make_mut)
754            .expect("node checked above")
755            .text = Some(content.clone());
756        self.journal
757            .push_coalesced(DirtySlot::Text(node), Operation::SetText { node, content });
758        Ok(())
759    }
760
761    /// Sets a resolved inherited text-style snapshot when it differs from
762    /// retained state.
763    pub fn set_text_style(
764        &mut self,
765        node: NodeId,
766        style: TextStyleSnapshot,
767    ) -> Result<(), SceneError> {
768        self.ensure_mutable()?;
769        style
770            .validate()
771            .map_err(|error| SceneError::InvalidText { error })?;
772        if self.require_node(node)?.text_style.as_ref() == Some(&style) {
773            return Ok(());
774        }
775        self.nodes
776            .get_mut(&node)
777            .map(Arc::make_mut)
778            .expect("node checked above")
779            .text_style = Some(style.clone());
780        self.journal.push_coalesced(
781            DirtySlot::TextStyle(node),
782            Operation::SetTextStyle { node, style },
783        );
784        Ok(())
785    }
786
787    /// Sets a typed property when it differs from retained state.
788    pub fn set_property(
789        &mut self,
790        node: NodeId,
791        property: PropertyId,
792        value: WhiskerValue,
793    ) -> Result<(), SceneError> {
794        self.ensure_mutable()?;
795        if self.require_node(node)?.properties.get(&property) == Some(&value) {
796            return Ok(());
797        }
798        self.nodes
799            .get_mut(&node)
800            .map(Arc::make_mut)
801            .expect("node checked above")
802            .properties
803            .insert(property, value.clone());
804        self.journal.push_coalesced(
805            DirtySlot::Property(node, property),
806            Operation::SetProperty {
807                node,
808                property,
809                value,
810            },
811        );
812        Ok(())
813    }
814
815    /// Clears a typed property when it is present.
816    pub fn clear_property(&mut self, node: NodeId, property: PropertyId) -> Result<(), SceneError> {
817        self.ensure_mutable()?;
818        if self
819            .nodes
820            .get_mut(&node)
821            .map(Arc::make_mut)
822            .ok_or(SceneError::UnknownNode { node })?
823            .properties
824            .remove(&property)
825            .is_none()
826        {
827            return Ok(());
828        }
829        self.journal.push_coalesced(
830            DirtySlot::Property(node, property),
831            Operation::ClearProperty { node, property },
832        );
833        Ok(())
834    }
835
836    /// Sets a node's event subscription mask.
837    pub fn set_event_mask(&mut self, node: NodeId, event_mask: u64) -> Result<(), SceneError> {
838        self.ensure_mutable()?;
839        if self.require_node(node)?.event_mask == Some(event_mask) {
840            return Ok(());
841        }
842        self.nodes
843            .get_mut(&node)
844            .map(Arc::make_mut)
845            .expect("node checked above")
846            .event_mask = Some(event_mask);
847        self.journal.push_coalesced(
848            DirtySlot::EventMask(node),
849            Operation::SetEventMask { node, event_mask },
850        );
851        Ok(())
852    }
853
854    /// Replaces a node's common accessibility semantics.
855    pub fn set_accessibility(
856        &mut self,
857        node: NodeId,
858        accessibility: Accessibility,
859    ) -> Result<(), SceneError> {
860        self.ensure_mutable()?;
861        if self.require_node(node)?.accessibility.as_ref() == Some(&accessibility) {
862            return Ok(());
863        }
864        self.nodes
865            .get_mut(&node)
866            .map(Arc::make_mut)
867            .expect("node checked above")
868            .accessibility = Some(accessibility.clone());
869        self.journal.push_coalesced(
870            DirtySlot::Accessibility(node),
871            Operation::SetAccessibility {
872                node,
873                accessibility,
874            },
875        );
876        Ok(())
877    }
878
879    /// Sets a node's Host hit-test participation.
880    pub fn set_hit_test(
881        &mut self,
882        node: NodeId,
883        behavior: HitTestBehavior,
884    ) -> Result<(), SceneError> {
885        self.ensure_mutable()?;
886        if self.require_node(node)?.hit_test == Some(behavior) {
887            return Ok(());
888        }
889        self.nodes
890            .get_mut(&node)
891            .map(Arc::make_mut)
892            .expect("node checked above")
893            .hit_test = Some(behavior);
894        self.journal.push_coalesced(
895            DirtySlot::HitTest(node),
896            Operation::SetHitTest { node, behavior },
897        );
898        Ok(())
899    }
900
901    /// Updates transient Host-owned scroll state without producing a frame operation.
902    ///
903    /// Native scrolling advances independently of frame delivery. Retaining its
904    /// latest logical offset keeps Rust input routing aligned with the pixels the
905    /// Host currently presents while leaving Rust-authored layout unchanged.
906    pub fn update_host_scroll_offset(
907        &mut self,
908        node: NodeId,
909        offset: [f32; 2],
910    ) -> Result<(), SceneError> {
911        if !offset.into_iter().all(f32::is_finite) {
912            return Err(SceneError::NonFiniteNumber);
913        }
914        self.require_node(node)?;
915        self.nodes
916            .get_mut(&node)
917            .map(Arc::make_mut)
918            .expect("node checked above")
919            .host_scroll_offset = offset;
920        Ok(())
921    }
922
923    /// Sets a node's resolved pointing-device cursor.
924    pub fn set_cursor(&mut self, node: NodeId, cursor: Cursor) -> Result<(), SceneError> {
925        self.ensure_mutable()?;
926        if self.require_node(node)?.cursor.as_ref() == Some(&cursor) {
927            return Ok(());
928        }
929        self.nodes
930            .get_mut(&node)
931            .map(Arc::make_mut)
932            .expect("node checked above")
933            .cursor = Some(cursor.clone());
934        self.journal.push_coalesced(
935            DirtySlot::Cursor(node),
936            Operation::SetCursor { node, cursor },
937        );
938        Ok(())
939    }
940
941    /// Captures a pointer when it is not already captured by this node.
942    pub fn set_pointer_capture(
943        &mut self,
944        node: NodeId,
945        pointer: PointerId,
946    ) -> Result<(), SceneError> {
947        self.ensure_mutable()?;
948        self.require_node(node)?;
949        if self.pointer_captures.get(&pointer) == Some(&node) {
950            return Ok(());
951        }
952        self.pointer_captures.insert(pointer, node);
953        self.journal.push_coalesced(
954            DirtySlot::Pointer(node, pointer),
955            Operation::SetPointerCapture { node, pointer },
956        );
957        Ok(())
958    }
959
960    /// Releases a pointer when it is currently captured by this node.
961    pub fn release_pointer_capture(
962        &mut self,
963        node: NodeId,
964        pointer: PointerId,
965    ) -> Result<(), SceneError> {
966        self.ensure_mutable()?;
967        self.require_node(node)?;
968        if self.pointer_captures.get(&pointer) != Some(&node) {
969            return Ok(());
970        }
971        self.pointer_captures.remove(&pointer);
972        self.journal.push_coalesced(
973            DirtySlot::Pointer(node, pointer),
974            Operation::ReleasePointerCapture { node, pointer },
975        );
976        Ok(())
977    }
978
979    /// Releases every captured pointer.
980    pub fn release_pointer_captures(&mut self) -> Result<(), SceneError> {
981        self.ensure_mutable()?;
982        for (pointer, node) in std::mem::take(&mut self.pointer_captures) {
983            self.journal.push_coalesced(
984                DirtySlot::Pointer(node, pointer),
985                Operation::ReleasePointerCapture { node, pointer },
986            );
987        }
988        Ok(())
989    }
990
991    /// Queues an element command after preceding visual mutations.
992    pub fn invoke_command(
993        &mut self,
994        node: NodeId,
995        command: CommandId,
996        arguments: WhiskerValue,
997    ) -> Result<(), SceneError> {
998        self.ensure_mutable()?;
999        self.require_node(node)?;
1000        self.journal.push_barrier(Operation::InvokeCommand {
1001            node,
1002            command,
1003            arguments,
1004        });
1005        Ok(())
1006    }
1007
1008    /// Prepares the next snapshot or delta and keeps it pending.
1009    ///
1010    /// Returns `Ok(None)` when the accepted scene is idle. Repeated calls while
1011    /// a packet is pending return [`SceneError::FramePending`]; the caller must
1012    /// first accept or discard that packet.
1013    pub fn prepare_frame(
1014        &mut self,
1015        viewport_epoch: u32,
1016    ) -> Result<Option<&FramePacket>, SceneError> {
1017        if self.pending.is_some() {
1018            return Err(SceneError::FramePending);
1019        }
1020        if !self.needs_snapshot && self.journal.operations.is_empty() {
1021            return Ok(None);
1022        }
1023        let target_revision = self
1024            .accepted_revision
1025            .checked_add(1)
1026            .ok_or(SceneError::RevisionExhausted)?;
1027        let frame_id = self.next_frame_id;
1028        self.next_frame_id = self
1029            .next_frame_id
1030            .checked_add(1)
1031            .ok_or(SceneError::FrameIdExhausted)?;
1032        let mode = if self.needs_snapshot {
1033            FrameMode::Snapshot
1034        } else {
1035            FrameMode::Delta
1036        };
1037        let operations = if mode == FrameMode::Snapshot {
1038            self.snapshot_operations()
1039        } else {
1040            self.journal.operations.clone()
1041        };
1042        self.pending = Some(FramePacket {
1043            header: FrameHeader {
1044                version: self.protocol,
1045                surface: self.surface,
1046                scene_epoch: self.scene_epoch,
1047                frame_id,
1048                base_revision: if mode == FrameMode::Snapshot {
1049                    0
1050                } else {
1051                    self.accepted_revision
1052                },
1053                target_revision,
1054                viewport_epoch,
1055                mode,
1056            },
1057            operations,
1058        });
1059        Ok(self.pending.as_ref())
1060    }
1061
1062    /// Commits the pending packet after renderer acceptance.
1063    pub fn accept_pending(&mut self, revision: u64) -> Result<(), SceneError> {
1064        let expected = self
1065            .pending
1066            .as_ref()
1067            .ok_or(SceneError::NoPendingFrame)?
1068            .header
1069            .target_revision;
1070        if revision != expected {
1071            return Err(SceneError::AcceptedRevisionMismatch {
1072                expected,
1073                received: revision,
1074            });
1075        }
1076        self.accepted_revision = revision;
1077        self.pending = None;
1078        self.needs_snapshot = false;
1079        self.journal.clear();
1080        Ok(())
1081    }
1082
1083    /// Discards a prepared packet after a transport or renderer failure.
1084    ///
1085    /// Retained mutations remain dirty, so the next preparation retries the
1086    /// same semantic work with a new diagnostic frame ID.
1087    pub fn discard_pending(&mut self) -> Result<(), SceneError> {
1088        self.pending.take().ok_or(SceneError::NoPendingFrame)?;
1089        Ok(())
1090    }
1091
1092    /// Switches the next frame to a full snapshot with a new scene epoch.
1093    ///
1094    /// This is called after a renderer returns `NeedSnapshot`. Any pending
1095    /// delta is discarded, while retained state and queued commands remain.
1096    pub fn require_snapshot(&mut self) -> Result<(), SceneError> {
1097        self.pending = None;
1098        // A snapshot rebuilds the Host presentation from protocol state. Scroll
1099        // offsets are Host-owned transient state and are deliberately absent
1100        // from snapshot operations, so the rebuilt native views start at zero.
1101        // Reset the Rust mirror at the same recovery boundary to keep hit
1102        // testing aligned with the pixels the Host presents.
1103        for node in self.nodes.values_mut() {
1104            Arc::make_mut(node).host_scroll_offset = [0.0; 2];
1105        }
1106        if !self.needs_snapshot {
1107            self.scene_epoch = self
1108                .scene_epoch
1109                .checked_add(1)
1110                .ok_or(SceneError::SceneEpochExhausted)?;
1111            self.needs_snapshot = true;
1112        }
1113        Ok(())
1114    }
1115
1116    fn ensure_mutable(&self) -> Result<(), SceneError> {
1117        if self.pending.is_some() {
1118            Err(SceneError::FramePending)
1119        } else {
1120            Ok(())
1121        }
1122    }
1123
1124    fn require_node(&self, node: NodeId) -> Result<&SceneNode, SceneError> {
1125        self.nodes
1126            .get(&node)
1127            .map(Arc::as_ref)
1128            .ok_or(SceneError::UnknownNode { node })
1129    }
1130
1131    fn require_direct_child(&self, parent: NodeId, child: NodeId) -> Result<(), SceneError> {
1132        self.require_node(parent)?;
1133        let child_state = self.require_node(child)?;
1134        if child_state.parent != Some(parent) {
1135            return Err(SceneError::NotDirectChild { parent, child });
1136        }
1137        Ok(())
1138    }
1139
1140    fn is_descendant(&self, ancestor: NodeId, candidate: NodeId) -> bool {
1141        let mut cursor = Some(candidate);
1142        while let Some(node) = cursor {
1143            if node == ancestor {
1144                return true;
1145            }
1146            cursor = self.nodes.get(&node).and_then(|entry| entry.parent);
1147        }
1148        false
1149    }
1150
1151    fn snapshot_operations(&self) -> Vec<Operation> {
1152        let mut operations = Vec::new();
1153        let mut nodes: Vec<_> = self.nodes.iter().collect();
1154        nodes.sort_unstable_by_key(|(node, _)| node.get());
1155        for (node, state) in nodes.iter().copied() {
1156            operations.push(Operation::CreateNode {
1157                node: *node,
1158                element_type: state.element_type,
1159            });
1160        }
1161        for (parent, state) in nodes.iter().copied() {
1162            for (index, child) in state.children.iter().enumerate() {
1163                operations.push(Operation::InsertChild {
1164                    parent: *parent,
1165                    child: *child,
1166                    index: index as u32,
1167                });
1168            }
1169        }
1170        for (node, state) in nodes {
1171            if let Some(geometry) = state.layout {
1172                operations.push(Operation::SetLayout {
1173                    node: *node,
1174                    geometry,
1175                });
1176            }
1177            if let Some(paint) = &state.box_paint {
1178                operations.push(Operation::SetBoxPaint {
1179                    node: *node,
1180                    paint: paint.clone(),
1181                });
1182            }
1183            if !state.background_layers.is_empty() {
1184                operations.push(Operation::SetBackgroundLayers {
1185                    node: *node,
1186                    layers: state.background_layers.clone(),
1187                });
1188            }
1189            if state.visual_effects != VisualEffects::default() {
1190                operations.push(Operation::SetVisualEffects {
1191                    node: *node,
1192                    effects: state.visual_effects.clone(),
1193                });
1194            }
1195            if let Some(clip) = state.clip {
1196                operations.push(Operation::SetClip { node: *node, clip });
1197            }
1198            if let Some(transform) = state.transform {
1199                operations.push(Operation::SetTransform {
1200                    node: *node,
1201                    transform,
1202                });
1203            }
1204            if let Some(opacity) = state.opacity {
1205                operations.push(Operation::SetOpacity {
1206                    node: *node,
1207                    opacity,
1208                });
1209            }
1210            if let Some(visibility) = state.visibility {
1211                operations.push(Operation::SetVisibility {
1212                    node: *node,
1213                    visibility,
1214                });
1215            }
1216            if let Some(z_order) = state.z_order {
1217                operations.push(Operation::SetZOrder {
1218                    node: *node,
1219                    z_order,
1220                });
1221            }
1222            if let Some(content) = &state.text {
1223                operations.push(Operation::SetText {
1224                    node: *node,
1225                    content: content.clone(),
1226                });
1227            }
1228            if let Some(style) = &state.text_style {
1229                operations.push(Operation::SetTextStyle {
1230                    node: *node,
1231                    style: style.clone(),
1232                });
1233            }
1234            if let Some(accessibility) = &state.accessibility {
1235                operations.push(Operation::SetAccessibility {
1236                    node: *node,
1237                    accessibility: accessibility.clone(),
1238                });
1239            }
1240            for (property, value) in &state.properties {
1241                operations.push(Operation::SetProperty {
1242                    node: *node,
1243                    property: *property,
1244                    value: value.clone(),
1245                });
1246            }
1247            if let Some(event_mask) = state.event_mask {
1248                operations.push(Operation::SetEventMask {
1249                    node: *node,
1250                    event_mask,
1251                });
1252            }
1253            if let Some(behavior) = state.hit_test {
1254                operations.push(Operation::SetHitTest {
1255                    node: *node,
1256                    behavior,
1257                });
1258            }
1259            if let Some(cursor) = &state.cursor {
1260                operations.push(Operation::SetCursor {
1261                    node: *node,
1262                    cursor: cursor.clone(),
1263                });
1264            }
1265        }
1266        for (pointer, node) in &self.pointer_captures {
1267            operations.push(Operation::SetPointerCapture {
1268                node: *node,
1269                pointer: *pointer,
1270            });
1271        }
1272        operations.extend(self.journal.operations.iter().filter_map(|operation| {
1273            let Operation::InvokeCommand { node, .. } = operation else {
1274                return None;
1275            };
1276            self.nodes.contains_key(node).then(|| operation.clone())
1277        }));
1278        operations
1279    }
1280}
1281
1282#[cfg(test)]
1283mod tests {
1284    use super::*;
1285    use crate::{FrameSink, RecordingRenderer};
1286    use whisker_protocol::{
1287        ApplyResult, BackgroundAttachment, BackgroundSize, BlendMode, BorderLineStyle, ImageRepeat,
1288        LayoutRect, MeasureFontFamily, MeasureFontStyle, MeasureLineHeight, MeasureTextDirection,
1289        MeasureTextOverflow, MeasureTextWrap, PaintBox, PaintColor, PaintCorners, PaintEdges,
1290        PaintImage, PaintLengthPercentage, PaintPosition, ResourceId, TextContentError,
1291        TextMeasurePayload, TextMeasureStyle, TextStyleSnapshot, ValidationError,
1292    };
1293
1294    fn surface() -> SurfaceId {
1295        SurfaceId::new(1).expect("test surface")
1296    }
1297
1298    fn node(value: u64) -> NodeId {
1299        NodeId::new(value).expect("test node")
1300    }
1301
1302    fn element_type(value: u32) -> ElementTypeId {
1303        ElementTypeId::new(value).expect("test element type")
1304    }
1305
1306    fn property(value: u32) -> PropertyId {
1307        PropertyId::new(value).expect("test property")
1308    }
1309
1310    fn pointer(value: u64) -> PointerId {
1311        PointerId::new(value).expect("test pointer")
1312    }
1313
1314    fn command(value: u32) -> CommandId {
1315        CommandId::new(value).expect("test command")
1316    }
1317
1318    fn text_content(text: &str) -> TextContent {
1319        TextContent {
1320            paragraph: None,
1321            runs: Vec::new(),
1322            payload: TextMeasurePayload {
1323                runs: Vec::new(),
1324                attachments: Vec::new(),
1325                text: text.into(),
1326                style: TextMeasureStyle {
1327                    font_families: vec![MeasureFontFamily::System],
1328                    font_size: 14.0,
1329                    font_weight: 400,
1330                    font_style: MeasureFontStyle::Normal,
1331                    line_height: MeasureLineHeight::Normal,
1332                    letter_spacing: 0.0,
1333                    ..TextMeasureStyle::default()
1334                },
1335                locale: None,
1336                direction: MeasureTextDirection::Auto,
1337                alignment: whisker_protocol::MeasureTextAlignment::Start,
1338                indent: Default::default(),
1339                wrap: MeasureTextWrap::Wrap,
1340                word_break: Default::default(),
1341                max_lines: None,
1342                overflow: MeasureTextOverflow::Clip,
1343            },
1344            paint: whisker_protocol::TextPaint::default(),
1345            prepared_content: None,
1346        }
1347    }
1348
1349    fn box_paint(color: &str) -> BoxPaint {
1350        let zero = PaintLengthPercentage::default();
1351        BoxPaint {
1352            background_color: PaintColor::Named(color.into()),
1353            border_widths: PaintEdges {
1354                top: zero,
1355                right: zero,
1356                bottom: zero,
1357                left: zero,
1358            },
1359            border_colors: PaintEdges {
1360                top: PaintColor::default(),
1361                right: PaintColor::default(),
1362                bottom: PaintColor::default(),
1363                left: PaintColor::default(),
1364            },
1365            border_styles: PaintEdges {
1366                top: BorderLineStyle::None,
1367                right: BorderLineStyle::None,
1368                bottom: BorderLineStyle::None,
1369                left: BorderLineStyle::None,
1370            },
1371            border_radii: PaintCorners {
1372                top_left: whisker_protocol::PaintCornerRadius::circular(zero),
1373                top_right: whisker_protocol::PaintCornerRadius::circular(zero),
1374                bottom_right: whisker_protocol::PaintCornerRadius::circular(zero),
1375                bottom_left: whisker_protocol::PaintCornerRadius::circular(zero),
1376            },
1377        }
1378    }
1379
1380    fn resource_background(resource: u64) -> BackgroundLayer {
1381        BackgroundLayer {
1382            image: PaintImage::Resource(ResourceId::new(resource).unwrap()),
1383            position: PaintPosition::default(),
1384            size: BackgroundSize::Auto,
1385            repeat_x: ImageRepeat::Repeat,
1386            repeat_y: ImageRepeat::Repeat,
1387            origin: PaintBox::Padding,
1388            clip: PaintBox::Border,
1389            attachment: BackgroundAttachment::Scroll,
1390            blend_mode: BlendMode::Normal,
1391        }
1392    }
1393
1394    fn prepared(scene: &mut Scene) -> FramePacket {
1395        scene
1396            .prepare_frame(7)
1397            .expect("prepare frame")
1398            .expect("scene has work")
1399            .clone()
1400    }
1401
1402    fn present_and_accept(scene: &mut Scene, renderer: &mut RecordingRenderer) -> FramePacket {
1403        let packet = prepared(scene);
1404        let outcome = renderer.present(&packet).expect("valid engine packet");
1405        let revision = packet.header.target_revision;
1406        assert_eq!(outcome, ApplyResult::Accepted { revision });
1407        scene.accept_pending(revision).expect("matching acceptance");
1408        packet
1409    }
1410
1411    fn initialized_scene() -> (Scene, RecordingRenderer, NodeId, NodeId) {
1412        let mut scene = Scene::new(surface());
1413        let root = scene.create_node(element_type(1)).expect("create root");
1414        let child = scene.create_node(element_type(2)).expect("create child");
1415        scene.insert_child(root, child, 0).expect("attach child");
1416        let mut renderer = RecordingRenderer::new(surface());
1417        present_and_accept(&mut scene, &mut renderer);
1418        (scene, renderer, root, child)
1419    }
1420
1421    #[test]
1422    fn initial_snapshot_rebuilds_complete_retained_state() {
1423        let mut scene = Scene::new(surface());
1424        assert_eq!(scene.surface(), surface());
1425        assert_eq!(scene.scene_epoch(), 1);
1426        assert_eq!(scene.accepted_revision(), 0);
1427        assert!(scene.has_pending_work());
1428
1429        let root = scene.create_node(element_type(1)).expect("create root");
1430        let child = scene.create_node(element_type(2)).expect("create child");
1431        scene.insert_child(root, child, 0).expect("attach child");
1432        let rect = LayoutRect {
1433            x: 1.0,
1434            y: 2.0,
1435            width: 300.0,
1436            height: 200.0,
1437        };
1438        scene.set_layout(root, rect).expect("layout");
1439        let paint = box_paint("navy");
1440        scene.set_box_paint(root, paint.clone()).expect("box paint");
1441        let background = resource_background(9);
1442        scene
1443            .set_background_layers(root, vec![background.clone()])
1444            .expect("background layers");
1445        let effects = VisualEffects {
1446            backdrop_blur: Some(12.0),
1447            ..VisualEffects::default()
1448        };
1449        scene
1450            .set_visual_effects(root, effects.clone())
1451            .expect("visual effects");
1452        let clip = BoxClip {
1453            horizontal: OverflowClip::Hidden,
1454            vertical: OverflowClip::Visible,
1455        };
1456        scene.set_clip(root, clip).expect("clip");
1457        scene
1458            .set_transform(root, Transform::IDENTITY)
1459            .expect("transform");
1460        scene.set_opacity(root, 0.75).expect("opacity");
1461        scene
1462            .set_visibility(root, Visibility::Visible)
1463            .expect("visibility");
1464        scene.set_z_order(root, -1).expect("z order");
1465        let text = text_content("hello");
1466        scene.set_text(root, text.clone()).expect("text");
1467        let text_style = TextStyleSnapshot::from(&text);
1468        scene
1469            .set_text_style(root, text_style.clone())
1470            .expect("text style");
1471        let accessibility = Accessibility::new()
1472            .label("Greeting")
1473            .role(whisker_protocol::AccessibilityRole::Header);
1474        scene
1475            .set_accessibility(root, accessibility.clone())
1476            .expect("accessibility");
1477        scene
1478            .set_property(root, property(1), WhiskerValue::String("red".into()))
1479            .expect("property");
1480        scene.set_event_mask(root, 3).expect("event mask");
1481        scene
1482            .set_hit_test(root, HitTestBehavior::BoxOnly)
1483            .expect("hit test");
1484        let cursor = whisker_protocol::Cursor {
1485            resources: Vec::new(),
1486            fallback: whisker_protocol::CursorKeyword::Grab,
1487        };
1488        scene.set_cursor(root, cursor.clone()).expect("cursor");
1489        scene
1490            .set_pointer_capture(root, pointer(1))
1491            .expect("pointer capture");
1492        scene
1493            .invoke_command(root, command(1), WhiskerValue::Array(Vec::new()))
1494            .expect("command");
1495
1496        let root_state = scene.node(root).expect("root state");
1497        assert_eq!(root_state.element_type(), element_type(1));
1498        assert_eq!(root_state.parent(), None);
1499        assert_eq!(root_state.children(), &[child]);
1500        assert_eq!(root_state.layout(), Some(rect.into()));
1501        assert_eq!(root_state.text(), Some(&text));
1502        assert_eq!(root_state.text_style(), Some(&text_style));
1503        assert_eq!(root_state.accessibility(), Some(&accessibility));
1504        assert_eq!(root_state.box_paint(), Some(&paint));
1505        assert_eq!(root_state.visual_effects(), &effects);
1506        assert_eq!(root_state.clip(), Some(clip));
1507        assert_eq!(root_state.transform(), Some(Transform::IDENTITY));
1508        assert_eq!(root_state.opacity(), Some(0.75));
1509        assert_eq!(root_state.visibility(), Some(Visibility::Visible));
1510        assert_eq!(root_state.z_order(), Some(-1));
1511        assert_eq!(root_state.event_mask(), Some(3));
1512        assert_eq!(root_state.hit_test(), Some(HitTestBehavior::BoxOnly));
1513        assert_eq!(root_state.cursor(), Some(&cursor));
1514        assert_eq!(scene.node(child).expect("child state").parent(), Some(root));
1515        assert_eq!(scene.node_count(), 2);
1516
1517        let mut renderer = RecordingRenderer::new(surface());
1518        let packet = present_and_accept(&mut scene, &mut renderer);
1519        assert_eq!(packet.header.mode, FrameMode::Snapshot);
1520        assert_eq!(packet.header.base_revision, 0);
1521        assert_eq!(packet.header.target_revision, 1);
1522        assert_eq!(packet.header.viewport_epoch, 7);
1523        assert_eq!(renderer.projection().node_count(), 2);
1524        assert_eq!(scene.accepted_revision(), 1);
1525        assert!(packet.operations.iter().any(|operation| {
1526            matches!(
1527                operation,
1528                Operation::SetBackgroundLayers { node, layers }
1529                    if *node == root && layers == std::slice::from_ref(&background)
1530            )
1531        }));
1532        assert!(packet.operations.iter().any(|operation| {
1533            matches!(
1534                operation,
1535                Operation::SetCursor { node, cursor: actual }
1536                    if *node == root && actual == &cursor
1537            )
1538        }));
1539        assert!(packet.operations.iter().any(|operation| {
1540            matches!(
1541                operation,
1542                Operation::SetVisualEffects { node, effects: actual }
1543                    if *node == root && actual == &effects
1544            )
1545        }));
1546        assert!(packet.operations.iter().any(|operation| {
1547            matches!(
1548                operation,
1549                Operation::SetTextStyle { node, style }
1550                    if *node == root && style == &text_style
1551            )
1552        }));
1553        assert!(packet.operations.iter().any(|operation| {
1554            matches!(
1555                operation,
1556                Operation::SetAccessibility { node, accessibility: actual }
1557                    if *node == root && actual == &accessibility
1558            )
1559        }));
1560        assert!(!scene.has_pending_work());
1561        assert_eq!(scene.prepare_frame(8).expect("idle frame"), None);
1562    }
1563
1564    #[test]
1565    fn equal_values_are_idle_and_delta_values_coalesce_between_barriers() {
1566        let (mut scene, mut renderer, root, _) = initialized_scene();
1567        let first = LayoutRect {
1568            width: 10.0,
1569            height: 20.0,
1570            ..LayoutRect::default()
1571        };
1572        let second = LayoutRect {
1573            width: 30.0,
1574            height: 40.0,
1575            ..LayoutRect::default()
1576        };
1577        scene.set_layout(root, first).expect("first layout");
1578        scene.set_layout(root, second).expect("second layout");
1579        scene.set_layout(root, second).expect("equal layout");
1580        let first_paint = box_paint("red");
1581        let second_paint = box_paint("blue");
1582        scene
1583            .set_box_paint(root, first_paint)
1584            .expect("first box paint");
1585        scene
1586            .set_box_paint(root, second_paint.clone())
1587            .expect("coalesced box paint");
1588        scene
1589            .set_box_paint(root, second_paint)
1590            .expect("equal box paint");
1591        scene
1592            .set_background_layers(root, vec![resource_background(1)])
1593            .expect("first background");
1594        scene
1595            .set_background_layers(root, vec![resource_background(2)])
1596            .expect("coalesced background");
1597        scene
1598            .set_background_layers(root, vec![resource_background(2)])
1599            .expect("equal background");
1600        let effects = VisualEffects {
1601            backdrop_blur: Some(8.0),
1602            ..VisualEffects::default()
1603        };
1604        scene
1605            .set_visual_effects(root, effects.clone())
1606            .expect("visual effects");
1607        scene
1608            .set_visual_effects(root, effects)
1609            .expect("equal visual effects");
1610        let clip = BoxClip {
1611            horizontal: OverflowClip::Visible,
1612            vertical: OverflowClip::Hidden,
1613        };
1614        scene.set_clip(root, clip).expect("clip");
1615        scene.set_clip(root, clip).expect("equal clip");
1616        scene
1617            .set_transform(root, Transform::IDENTITY)
1618            .expect("transform");
1619        scene
1620            .set_transform(root, Transform::IDENTITY)
1621            .expect("equal transform");
1622        scene.set_opacity(root, 0.2).expect("first opacity");
1623        scene.set_opacity(root, 0.4).expect("coalesced opacity");
1624        scene.set_opacity(root, 0.4).expect("equal opacity");
1625        scene
1626            .set_visibility(root, Visibility::Hidden)
1627            .expect("visibility");
1628        scene
1629            .set_visibility(root, Visibility::Hidden)
1630            .expect("equal visibility");
1631        scene.set_z_order(root, 4).expect("z order");
1632        scene.set_z_order(root, 4).expect("equal z order");
1633        let text = text_content("updated");
1634        scene.set_text(root, text.clone()).expect("text");
1635        scene.set_text(root, text).expect("equal text");
1636        let mut first_text_style = TextStyleSnapshot::from(&text_content("first style"));
1637        let mut second_text_style = first_text_style.clone();
1638        first_text_style.paint.foreground = PaintColor::Named("red".into());
1639        second_text_style.paint.foreground = PaintColor::Named("blue".into());
1640        scene
1641            .set_text_style(root, first_text_style)
1642            .expect("first text style");
1643        scene
1644            .set_text_style(root, second_text_style.clone())
1645            .expect("coalesced text style");
1646        scene
1647            .set_text_style(root, second_text_style)
1648            .expect("equal text style");
1649        let accessibility = Accessibility::new().label("Updated");
1650        scene
1651            .set_accessibility(root, accessibility.clone())
1652            .expect("accessibility");
1653        scene
1654            .set_accessibility(root, accessibility)
1655            .expect("equal accessibility");
1656        scene
1657            .set_property(root, property(1), WhiskerValue::Int(1))
1658            .expect("first property");
1659        scene
1660            .set_property(root, property(1), WhiskerValue::Int(2))
1661            .expect("coalesced property");
1662        scene
1663            .set_property(root, property(1), WhiskerValue::Int(2))
1664            .expect("equal property");
1665        scene.set_event_mask(root, 7).expect("event mask");
1666        scene.set_event_mask(root, 7).expect("equal event mask");
1667        scene
1668            .set_hit_test(root, HitTestBehavior::DescendantsOnly)
1669            .expect("hit test");
1670        scene
1671            .set_hit_test(root, HitTestBehavior::DescendantsOnly)
1672            .expect("equal hit test");
1673        scene
1674            .set_pointer_capture(root, pointer(1))
1675            .expect("capture");
1676        scene
1677            .set_pointer_capture(root, pointer(1))
1678            .expect("equal capture");
1679
1680        scene
1681            .invoke_command(root, command(1), WhiskerValue::Null)
1682            .expect("barrier command");
1683        scene.set_opacity(root, 0.8).expect("post-barrier opacity");
1684
1685        let packet = present_and_accept(&mut scene, &mut renderer);
1686        assert_eq!(packet.header.mode, FrameMode::Delta);
1687        assert_eq!(packet.header.base_revision, 1);
1688        assert_eq!(packet.header.target_revision, 2);
1689        assert_eq!(
1690            packet
1691                .operations
1692                .iter()
1693                .filter(|operation| matches!(operation, Operation::SetLayout { .. }))
1694                .count(),
1695            1
1696        );
1697        assert_eq!(
1698            packet
1699                .operations
1700                .iter()
1701                .filter(|operation| matches!(operation, Operation::SetOpacity { .. }))
1702                .count(),
1703            2
1704        );
1705        assert!(!scene.has_pending_work());
1706    }
1707
1708    #[test]
1709    fn clear_and_pointer_release_coalesce_and_skip_absent_values() {
1710        let (mut scene, mut renderer, root, _) = initialized_scene();
1711        let property = property(1);
1712        let pointer = pointer(1);
1713        scene.clear_property(root, property).expect("absent clear");
1714        scene
1715            .release_pointer_capture(root, pointer)
1716            .expect("absent release");
1717        assert!(!scene.has_pending_work());
1718
1719        scene
1720            .set_property(root, property, WhiskerValue::Bool(true))
1721            .expect("set property");
1722        assert_eq!(
1723            scene.node(root).unwrap().properties().get(&property),
1724            Some(&WhiskerValue::Bool(true))
1725        );
1726        scene
1727            .clear_property(root, property)
1728            .expect("clear property");
1729        assert!(
1730            !scene
1731                .node(root)
1732                .unwrap()
1733                .properties()
1734                .contains_key(&property)
1735        );
1736        scene
1737            .set_pointer_capture(root, pointer)
1738            .expect("capture pointer");
1739        scene
1740            .release_pointer_capture(root, pointer)
1741            .expect("release pointer");
1742        let packet = present_and_accept(&mut scene, &mut renderer);
1743        assert_eq!(
1744            packet.operations,
1745            vec![
1746                Operation::ClearProperty {
1747                    node: root,
1748                    property,
1749                },
1750                Operation::ReleasePointerCapture {
1751                    node: root,
1752                    pointer,
1753                },
1754            ]
1755        );
1756    }
1757
1758    #[test]
1759    fn releasing_every_capture_reports_each_released_pointer() {
1760        let (mut scene, mut renderer, root, child) = initialized_scene();
1761        scene
1762            .set_pointer_capture(root, pointer(1))
1763            .expect("capture first");
1764        scene
1765            .set_pointer_capture(child, pointer(2))
1766            .expect("capture second");
1767        present_and_accept(&mut scene, &mut renderer);
1768
1769        scene.release_pointer_captures().expect("release all");
1770        assert_eq!(scene.pointer_capture_target(pointer(1)), None);
1771        assert_eq!(scene.pointer_capture_target(pointer(2)), None);
1772        let packet = present_and_accept(&mut scene, &mut renderer);
1773        assert_eq!(
1774            packet.operations,
1775            vec![
1776                Operation::ReleasePointerCapture {
1777                    node: root,
1778                    pointer: pointer(1),
1779                },
1780                Operation::ReleasePointerCapture {
1781                    node: child,
1782                    pointer: pointer(2),
1783                },
1784            ]
1785        );
1786    }
1787
1788    #[test]
1789    fn structural_delta_supports_move_remove_reinsert_and_subtree_delete() {
1790        let (mut scene, mut renderer, root, child) = initialized_scene();
1791        let sibling = scene.create_node(element_type(3)).expect("sibling");
1792        let grandchild = scene.create_node(element_type(4)).expect("grandchild");
1793        scene
1794            .insert_child(root, sibling, 1)
1795            .expect("insert sibling");
1796        scene.move_child(root, sibling, 0).expect("move sibling");
1797        scene.remove_child(root, child).expect("remove child");
1798        scene.insert_child(root, child, 1).expect("reinsert child");
1799        scene
1800            .insert_child(child, grandchild, 0)
1801            .expect("insert grandchild");
1802        let removed_pointer = pointer(41);
1803        let retained_pointer = pointer(42);
1804        scene
1805            .set_pointer_capture(grandchild, removed_pointer)
1806            .expect("capture removed descendant");
1807        scene
1808            .set_pointer_capture(sibling, retained_pointer)
1809            .expect("capture retained sibling");
1810        scene.delete_node(child).expect("delete attached subtree");
1811        assert_eq!(scene.node_count(), 2);
1812        assert_eq!(scene.node(root).expect("root").children(), &[sibling]);
1813        assert!(scene.node(child).is_none());
1814        assert!(scene.node(grandchild).is_none());
1815        assert_eq!(scene.pointer_capture_target(removed_pointer), None);
1816        assert_eq!(
1817            scene.pointer_capture_target(retained_pointer),
1818            Some(sibling)
1819        );
1820        present_and_accept(&mut scene, &mut renderer);
1821
1822        scene.delete_node(root).expect("delete unattached root");
1823        present_and_accept(&mut scene, &mut renderer);
1824        assert_eq!(scene.node_count(), 0);
1825        assert_eq!(renderer.projection().node_count(), 0);
1826    }
1827
1828    #[test]
1829    fn pending_frame_requires_explicit_accept_or_discard() {
1830        let (mut scene, _, root, _) = initialized_scene();
1831        scene.set_opacity(root, 0.5).expect("dirty scene");
1832        let first = prepared(&mut scene);
1833        assert!(scene.has_pending_work());
1834        assert_eq!(scene.prepare_frame(7), Err(SceneError::FramePending));
1835        assert_eq!(scene.set_opacity(root, 0.7), Err(SceneError::FramePending));
1836        assert_eq!(
1837            scene.set_text(root, text_content("pending")),
1838            Err(SceneError::FramePending)
1839        );
1840        assert_eq!(
1841            scene.set_text_style(
1842                root,
1843                TextStyleSnapshot::from(&text_content("pending style"))
1844            ),
1845            Err(SceneError::FramePending)
1846        );
1847        assert_eq!(
1848            scene.set_accessibility(root, Accessibility::new()),
1849            Err(SceneError::FramePending)
1850        );
1851        assert_eq!(
1852            scene.create_node(element_type(3)),
1853            Err(SceneError::FramePending)
1854        );
1855        assert_eq!(scene.delete_node(root), Err(SceneError::FramePending));
1856        assert_eq!(
1857            scene.release_pointer_captures(),
1858            Err(SceneError::FramePending)
1859        );
1860        assert_eq!(
1861            scene.insert_child(root, root, 0),
1862            Err(SceneError::FramePending)
1863        );
1864        assert_eq!(
1865            scene.remove_child(root, root),
1866            Err(SceneError::FramePending)
1867        );
1868        assert_eq!(
1869            scene.move_child(root, root, 0),
1870            Err(SceneError::FramePending)
1871        );
1872        assert_eq!(
1873            scene.set_layout(root, LayoutRect::default()),
1874            Err(SceneError::FramePending)
1875        );
1876        assert_eq!(
1877            scene.set_visual_effects(root, VisualEffects::default()),
1878            Err(SceneError::FramePending)
1879        );
1880        assert_eq!(
1881            scene.set_transform(root, Transform::IDENTITY),
1882            Err(SceneError::FramePending)
1883        );
1884        assert_eq!(
1885            scene.set_visibility(root, Visibility::Visible),
1886            Err(SceneError::FramePending)
1887        );
1888        assert_eq!(scene.set_z_order(root, 0), Err(SceneError::FramePending));
1889        assert_eq!(
1890            scene.set_property(root, property(1), WhiskerValue::Null),
1891            Err(SceneError::FramePending)
1892        );
1893        assert_eq!(
1894            scene.clear_property(root, property(1)),
1895            Err(SceneError::FramePending)
1896        );
1897        assert_eq!(scene.set_event_mask(root, 0), Err(SceneError::FramePending));
1898        assert_eq!(
1899            scene.set_hit_test(root, HitTestBehavior::Auto),
1900            Err(SceneError::FramePending)
1901        );
1902        assert_eq!(
1903            scene.set_pointer_capture(root, pointer(1)),
1904            Err(SceneError::FramePending)
1905        );
1906        assert_eq!(
1907            scene.release_pointer_capture(root, pointer(1)),
1908            Err(SceneError::FramePending)
1909        );
1910        assert_eq!(
1911            scene.invoke_command(root, command(1), WhiskerValue::Null),
1912            Err(SceneError::FramePending)
1913        );
1914        assert_eq!(
1915            scene.accept_pending(first.header.target_revision + 1),
1916            Err(SceneError::AcceptedRevisionMismatch {
1917                expected: first.header.target_revision,
1918                received: first.header.target_revision + 1,
1919            })
1920        );
1921        scene.discard_pending().expect("discard retry");
1922        assert_eq!(scene.discard_pending(), Err(SceneError::NoPendingFrame));
1923        let retry = prepared(&mut scene);
1924        assert_ne!(first.header.frame_id, retry.header.frame_id);
1925        assert_eq!(first.operations, retry.operations);
1926        scene
1927            .accept_pending(retry.header.target_revision)
1928            .expect("accept retry");
1929        assert_eq!(scene.accept_pending(3), Err(SceneError::NoPendingFrame));
1930    }
1931
1932    #[test]
1933    fn configured_protocol_version_is_written_to_every_frame() {
1934        let protocol = ProtocolVersion { major: 1, minor: 2 };
1935        let mut scene = Scene::with_protocol(surface(), protocol);
1936
1937        let packet = scene.prepare_frame(1).unwrap().unwrap();
1938
1939        assert_eq!(packet.header.version, protocol);
1940    }
1941
1942    #[test]
1943    fn snapshots_create_nodes_in_allocation_order() {
1944        let mut scene = Scene::new(surface());
1945        let expected: Vec<_> = (0..64)
1946            .map(|_| scene.create_node(element_type(1)).expect("node"))
1947            .collect();
1948        scene.set_opacity(expected[0], 0.5).expect("opacity");
1949
1950        let snapshot = prepared(&mut scene);
1951        let actual: Vec<_> = snapshot
1952            .operations
1953            .iter()
1954            .filter_map(|operation| match operation {
1955                Operation::CreateNode { node, .. } => Some(*node),
1956                _ => None,
1957            })
1958            .collect();
1959
1960        assert_eq!(actual, expected);
1961    }
1962
1963    #[test]
1964    fn need_snapshot_rotates_epoch_and_rebuilds_current_state() {
1965        let (mut scene, _, root, child) = initialized_scene();
1966        scene
1967            .update_host_scroll_offset(root, [0.0, 42.0])
1968            .expect("Host scroll state");
1969        scene.set_opacity(root, 0.5).expect("delta");
1970        let delta = prepared(&mut scene);
1971        let mut empty_renderer = RecordingRenderer::new(surface());
1972        assert_eq!(
1973            empty_renderer.present(&delta),
1974            Ok(ApplyResult::NeedSnapshot {
1975                receiver_revision: 0
1976            })
1977        );
1978
1979        scene.require_snapshot().expect("recovery snapshot");
1980        assert_eq!(scene.node(root).unwrap().host_scroll_offset(), [0.0; 2]);
1981        assert_eq!(scene.scene_epoch(), 2);
1982        scene.require_snapshot().expect("already snapshot mode");
1983        assert_eq!(scene.scene_epoch(), 2);
1984        let snapshot = prepared(&mut scene);
1985        assert_eq!(snapshot.header.mode, FrameMode::Snapshot);
1986        assert_eq!(snapshot.header.scene_epoch, 2);
1987        assert!(snapshot.operations.iter().any(
1988            |operation| matches!(operation, Operation::InsertChild { parent, child: value, .. } if *parent == root && *value == child)
1989        ));
1990        let outcome = empty_renderer
1991            .present(&snapshot)
1992            .expect("recovery snapshot accepted");
1993        let revision = snapshot.header.target_revision;
1994        assert_eq!(outcome, ApplyResult::Accepted { revision });
1995        scene.accept_pending(revision).expect("accept snapshot");
1996        assert_eq!(empty_renderer.projection().node_count(), 2);
1997    }
1998
1999    #[test]
2000    fn deleted_command_target_is_omitted_from_initial_snapshot() {
2001        let mut scene = Scene::new(surface());
2002        let doomed = scene.create_node(element_type(1)).expect("doomed node");
2003        scene
2004            .invoke_command(doomed, command(1), WhiskerValue::Null)
2005            .expect("queued command");
2006        scene.delete_node(doomed).expect("delete command target");
2007        let snapshot = prepared(&mut scene);
2008        assert!(snapshot.operations.is_empty());
2009    }
2010
2011    #[test]
2012    fn mutation_validation_preserves_the_retained_tree() {
2013        let (mut scene, _, root, child) = initialized_scene();
2014        let missing = node(99);
2015        let unattached = scene.create_node(element_type(3)).expect("unattached");
2016
2017        assert_eq!(
2018            scene.insert_child(missing, unattached, 0),
2019            Err(SceneError::UnknownNode { node: missing })
2020        );
2021        assert_eq!(
2022            scene.insert_child(root, missing, 0),
2023            Err(SceneError::UnknownNode { node: missing })
2024        );
2025        assert_eq!(
2026            scene.insert_child(root, child, 0),
2027            Err(SceneError::ChildAlreadyAttached {
2028                child,
2029                parent: root,
2030            })
2031        );
2032        assert_eq!(
2033            scene.insert_child(root, unattached, 2),
2034            Err(SceneError::ChildIndexOutOfBounds {
2035                parent: root,
2036                index: 2,
2037                len: 1,
2038            })
2039        );
2040        assert_eq!(
2041            scene.insert_child(unattached, unattached, 0),
2042            Err(SceneError::TreeCycle {
2043                parent: unattached,
2044                child: unattached,
2045            })
2046        );
2047        assert_eq!(
2048            scene.insert_child(child, root, 0),
2049            Err(SceneError::TreeCycle {
2050                parent: child,
2051                child: root,
2052            })
2053        );
2054        assert_eq!(
2055            scene.remove_child(root, unattached),
2056            Err(SceneError::NotDirectChild {
2057                parent: root,
2058                child: unattached,
2059            })
2060        );
2061        assert_eq!(
2062            scene.move_child(root, unattached, 0),
2063            Err(SceneError::NotDirectChild {
2064                parent: root,
2065                child: unattached,
2066            })
2067        );
2068        assert_eq!(
2069            scene.move_child(root, child, 1),
2070            Err(SceneError::ChildIndexOutOfBounds {
2071                parent: root,
2072                index: 1,
2073                len: 0,
2074            })
2075        );
2076        assert_eq!(scene.node(root).expect("root").children(), &[child]);
2077    }
2078
2079    #[test]
2080    fn unknown_nodes_are_rejected_by_every_mutation_family() {
2081        let (mut scene, _, _, _) = initialized_scene();
2082        let missing = node(99);
2083        let operations = [
2084            scene.delete_node(missing),
2085            scene.set_layout(missing, LayoutRect::default()),
2086            scene.set_box_paint(missing, box_paint("missing")),
2087            scene.set_visual_effects(missing, VisualEffects::default()),
2088            scene.set_clip(
2089                missing,
2090                BoxClip {
2091                    horizontal: OverflowClip::Visible,
2092                    vertical: OverflowClip::Visible,
2093                },
2094            ),
2095            scene.set_transform(missing, Transform::IDENTITY),
2096            scene.set_opacity(missing, 1.0),
2097            scene.set_visibility(missing, Visibility::Visible),
2098            scene.set_z_order(missing, 0),
2099            scene.set_text(missing, text_content("missing")),
2100            scene.set_text_style(
2101                missing,
2102                TextStyleSnapshot::from(&text_content("missing style")),
2103            ),
2104            scene.set_accessibility(missing, Accessibility::new()),
2105            scene.set_property(missing, property(1), WhiskerValue::Null),
2106            scene.clear_property(missing, property(1)),
2107            scene.set_event_mask(missing, 0),
2108            scene.set_hit_test(missing, HitTestBehavior::Auto),
2109            scene.set_pointer_capture(missing, pointer(1)),
2110            scene.release_pointer_capture(missing, pointer(1)),
2111            scene.invoke_command(missing, command(1), WhiskerValue::Null),
2112            scene.remove_child(missing, node(1)),
2113            scene.remove_child(node(1), missing),
2114        ];
2115        for outcome in operations {
2116            assert_eq!(outcome, Err(SceneError::UnknownNode { node: missing }));
2117        }
2118    }
2119
2120    #[test]
2121    fn numeric_and_result_validation_reject_invalid_values() {
2122        let (mut scene, _, root, _) = initialized_scene();
2123        let invalid_layout = LayoutRect {
2124            width: f32::NAN,
2125            ..LayoutRect::default()
2126        };
2127        assert_eq!(
2128            scene.set_layout(root, invalid_layout),
2129            Err(SceneError::NonFiniteNumber)
2130        );
2131        let mut invalid_paint = box_paint("invalid");
2132        invalid_paint.border_widths.top.length = -1.0;
2133        assert_eq!(
2134            scene.set_box_paint(root, invalid_paint),
2135            Err(SceneError::InvalidBoxPaint)
2136        );
2137        let invalid_effects = VisualEffects {
2138            backdrop_blur: Some(-1.0),
2139            ..VisualEffects::default()
2140        };
2141        assert_eq!(
2142            scene.set_visual_effects(root, invalid_effects),
2143            Err(SceneError::InvalidVisualEffects)
2144        );
2145        let mut invalid_text = text_content("invalid");
2146        invalid_text.payload.style.font_families.clear();
2147        assert_eq!(
2148            scene.set_text(root, invalid_text),
2149            Err(SceneError::InvalidText {
2150                error: TextContentError::InvalidMeasurement(
2151                    whisker_protocol::MeasurementPayloadError::InvalidFontFamily,
2152                ),
2153            })
2154        );
2155        let mut invalid_text_style = TextStyleSnapshot::from(&text_content("invalid style"));
2156        invalid_text_style.style.font_families.clear();
2157        assert_eq!(
2158            scene.set_text_style(root, invalid_text_style),
2159            Err(SceneError::InvalidText {
2160                error: TextContentError::InvalidMeasurement(
2161                    whisker_protocol::MeasurementPayloadError::InvalidFontFamily,
2162                ),
2163            })
2164        );
2165        let mut invalid_transform = Transform::IDENTITY;
2166        invalid_transform.0[0] = f32::INFINITY;
2167        assert_eq!(
2168            scene.set_transform(root, invalid_transform),
2169            Err(SceneError::NonFiniteNumber)
2170        );
2171        assert_eq!(
2172            scene.set_opacity(root, -0.1),
2173            Err(SceneError::InvalidOpacity { opacity: -0.1 })
2174        );
2175        let nan_error = scene.set_opacity(root, f32::NAN).expect_err("NaN opacity");
2176        assert_eq!(format!("{nan_error:?}"), "InvalidOpacity { opacity: NaN }");
2177
2178        assert!(
2179            SceneError::NonFiniteNumber
2180                .to_string()
2181                .starts_with("Whisker scene error:")
2182        );
2183        let as_error: &dyn Error = &SceneError::NonFiniteNumber;
2184        assert!(as_error.source().is_none());
2185    }
2186
2187    #[test]
2188    fn allocation_and_frame_counters_report_exhaustion() {
2189        let mut scene = Scene::new(surface());
2190        scene.next_node_id = 0;
2191        assert_eq!(
2192            scene.create_node(element_type(1)),
2193            Err(SceneError::NodeIdExhausted)
2194        );
2195
2196        let mut scene = Scene::new(surface());
2197        scene.accepted_revision = u64::MAX;
2198        assert_eq!(scene.prepare_frame(1), Err(SceneError::RevisionExhausted));
2199
2200        let mut scene = Scene::new(surface());
2201        scene.next_frame_id = u64::MAX;
2202        assert_eq!(scene.prepare_frame(1), Err(SceneError::FrameIdExhausted));
2203
2204        let (mut scene, _, _, _) = initialized_scene();
2205        scene.scene_epoch = u32::MAX;
2206        assert_eq!(
2207            scene.require_snapshot(),
2208            Err(SceneError::SceneEpochExhausted)
2209        );
2210    }
2211
2212    #[test]
2213    fn recording_renderer_surfaces_protocol_validation_failures() {
2214        let mut scene = Scene::new(surface());
2215        let packet = prepared(&mut scene);
2216        let mut wrong_renderer =
2217            RecordingRenderer::new(SurfaceId::new(2).expect("different recording surface"));
2218        assert_eq!(
2219            wrong_renderer.present(&packet),
2220            Err(ValidationError::SurfaceMismatch {
2221                expected: SurfaceId::new(2).expect("different recording surface"),
2222                received: surface(),
2223            })
2224        );
2225    }
2226
2227    #[test]
2228    fn hit_testing_respects_z_order_visibility_clip_and_pointer_capture() {
2229        let mut scene = Scene::new(surface());
2230        let root = scene.create_node(element_type(1)).unwrap();
2231        let back = scene.create_node(element_type(1)).unwrap();
2232        let front = scene.create_node(element_type(1)).unwrap();
2233        scene.insert_child(root, back, 0).unwrap();
2234        scene.insert_child(root, front, 1).unwrap();
2235        assert_eq!(
2236            scene.hit_test(root, InputPoint { x: 0.0, y: 0.0 }),
2237            Ok(None)
2238        );
2239        scene
2240            .set_layout(
2241                root,
2242                LayoutRect {
2243                    x: 0.0,
2244                    y: 0.0,
2245                    width: 100.0,
2246                    height: 100.0,
2247                },
2248            )
2249            .unwrap();
2250        for child in [back, front] {
2251            scene
2252                .set_layout(
2253                    child,
2254                    LayoutRect {
2255                        x: 0.0,
2256                        y: 0.0,
2257                        width: 50.0,
2258                        height: 50.0,
2259                    },
2260                )
2261                .unwrap();
2262        }
2263        scene.set_z_order(back, 1).unwrap();
2264        scene.set_z_order(front, 2).unwrap();
2265        let point = InputPoint { x: 10.0, y: 10.0 };
2266        assert_eq!(scene.hit_test(root, point), Ok(Some(front)));
2267        scene.set_z_order(back, 3).unwrap();
2268        assert_eq!(scene.hit_test(root, point), Ok(Some(back)));
2269        scene.set_z_order(back, 1).unwrap();
2270
2271        scene.set_hit_test(root, HitTestBehavior::BoxOnly).unwrap();
2272        assert_eq!(scene.hit_test(root, point), Ok(Some(root)));
2273        scene.set_hit_test(root, HitTestBehavior::Auto).unwrap();
2274
2275        scene.set_visibility(front, Visibility::Hidden).unwrap();
2276        assert_eq!(scene.hit_test(root, point), Ok(Some(back)));
2277        scene.set_hit_test(front, HitTestBehavior::None).unwrap();
2278        scene.set_visibility(front, Visibility::Visible).unwrap();
2279        assert_eq!(scene.hit_test(root, point), Ok(Some(back)));
2280        scene
2281            .set_hit_test(back, HitTestBehavior::DescendantsOnly)
2282            .unwrap();
2283        assert_eq!(scene.hit_test(root, point), Ok(Some(root)));
2284
2285        scene
2286            .set_layout(
2287                back,
2288                LayoutRect {
2289                    x: 120.0,
2290                    y: 0.0,
2291                    width: 50.0,
2292                    height: 50.0,
2293                },
2294            )
2295            .unwrap();
2296        scene.set_hit_test(back, HitTestBehavior::Auto).unwrap();
2297        scene
2298            .set_clip(
2299                root,
2300                BoxClip {
2301                    horizontal: OverflowClip::Hidden,
2302                    vertical: OverflowClip::Visible,
2303                },
2304            )
2305            .unwrap();
2306        let outside = InputPoint { x: 130.0, y: 10.0 };
2307        assert_eq!(scene.hit_test(root, outside), Ok(None));
2308        scene
2309            .set_clip(
2310                root,
2311                BoxClip {
2312                    horizontal: OverflowClip::Visible,
2313                    vertical: OverflowClip::Visible,
2314                },
2315            )
2316            .unwrap();
2317        assert_eq!(scene.hit_test(root, outside), Ok(Some(back)));
2318
2319        scene
2320            .set_layout(
2321                back,
2322                LayoutRect {
2323                    x: 0.0,
2324                    y: 120.0,
2325                    width: 50.0,
2326                    height: 50.0,
2327                },
2328            )
2329            .unwrap();
2330        scene
2331            .set_clip(
2332                root,
2333                BoxClip {
2334                    horizontal: OverflowClip::Visible,
2335                    vertical: OverflowClip::Hidden,
2336                },
2337            )
2338            .unwrap();
2339        assert_eq!(
2340            scene.hit_test(root, InputPoint { x: 10.0, y: 130.0 }),
2341            Ok(None)
2342        );
2343
2344        let pointer = pointer(9);
2345        scene.set_pointer_capture(back, pointer).unwrap();
2346        assert_eq!(scene.pointer_capture_target(pointer), Some(back));
2347        scene.release_pointer_capture(back, pointer).unwrap();
2348        assert_eq!(scene.pointer_capture_target(pointer), None);
2349        assert_eq!(
2350            scene.hit_test(node(999), point),
2351            Err(SceneError::UnknownNode { node: node(999) })
2352        );
2353    }
2354}