Skip to main content

glory_render/
memory.rs

1//! Reference semantics for adapters. This interpreter performs no layout/paint.
2//! It stores live objects and one generation watermark per allocated slot.
3//! Child sequences separately bound their unread numeric prefixes.
4
5use std::collections::HashMap;
6
7use crate::*;
8
9mod children;
10pub use children::Children;
11mod submission;
12pub use submission::Submission;
13
14/// Current live Layer facets, including hidden/detached declarations. Physical
15/// hosts may open fewer; this shared admission bound prevents late host failure.
16pub const MAX_LAYERS: usize = 1024;
17
18fn layer(descriptor: DescriptorView<'_>) -> bool {
19    descriptor
20        .semantics
21        .as_ref()
22        .is_some_and(|s| s.layer.is_some())
23}
24
25#[derive(Clone, Debug)]
26pub struct Node {
27    pub descriptor: LiveDescriptor,
28    pub parent: Option<NodeId>,
29    pub children: Children,
30    pub placed: bool,
31    pub suspended: bool,
32    // Logical adjacency, including suspended siblings. No historical identities.
33    next: Option<NodeId>,
34    clipboard: Option<Box<crate::clipboard::Requests>>,
35    files: Option<Box<crate::files::state::State>>,
36    swipe: Option<Box<crate::swipe::State>>,
37}
38
39/// A proposed child of a logical parent. New descriptors have no identity or
40/// descendants yet; existing ranges include their suspended descendants.
41/// This borrowed view is for validation, never a snapshot or host-tree lookup.
42#[derive(Clone, Copy, Debug)]
43pub enum Subtree<'a> {
44    New(DescriptorView<'a>),
45    Plan(&'a Plan),
46    Existing(NodeId),
47}
48
49#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
50pub struct Stats {
51    pub created: u64,
52    pub patched: u64,
53    pub placed: u64,
54    pub suspended: u64,
55    pub disposed: u64,
56}
57
58#[derive(Debug)]
59pub struct Memory {
60    runtime: RuntimeId,
61    nodes: NodeMap<Node>,
62    names: HashMap<SemanticId, NodeId>,
63    generations: HashMap<u32, (u32, bool)>,
64    roots: Children,
65    inputs: Vec<Input>,
66    receipt: Receipt,
67    stats: Stats,
68    layers: usize,
69    pub(crate) focus_scopes: std::collections::BTreeMap<NodeId, usize>,
70}
71
72/// One validated field update. Its descriptor is a borrowed view of the staged
73/// value; the inverse contains only the replaced field. Drop rolls it back,
74/// including on unwinding. No stats/watermark advance until commit.
75#[must_use = "commit the prepared patch, or drop it to restore the original"]
76pub struct PreparedPatch<'a> {
77    tree: &'a mut Memory,
78    id: NodeId,
79    inverse: Option<Patch>,
80    fields_before: u8,
81    focus_size: Option<usize>,
82}
83impl PreparedPatch<'_> {
84    pub fn descriptor(&self) -> DescriptorView<'_> {
85        self.tree.nodes[&self.id].descriptor.view()
86    }
87    /// Inverse field patch, with Keep preserved and Clear materialized as Set.
88    pub fn previous(&self) -> &Patch {
89        self.inverse.as_ref().expect("uncommitted patch")
90    }
91    fn accept(&mut self) {
92        if matches!(self.inverse, Some(Patch::Semantics(_)))
93            && let Some(capture) = self
94                .descriptor()
95                .semantics
96                .as_ref()
97                .and_then(|s| s.swipe_capture)
98        {
99            let target = self
100                .tree
101                .nodes
102                .get_mut(&self.id)
103                .expect("prepared swipe node");
104            if let Some(state) = target.swipe.as_mut() {
105                state.revision = capture.revision;
106            } else {
107                target.swipe = Some(crate::swipe::State::new(capture));
108            }
109        }
110        if let Some(Patch::Semantics(Change::Set(old))) = &self.inverse {
111            let before = old.as_ref().is_some_and(|s| s.focus_scope.is_some());
112            let after = crate::focus_scope::declared(self.descriptor());
113            if after && !before {
114                self.tree
115                    .focus_scopes
116                    .insert(self.id, self.focus_size.expect("validated FocusScope size"));
117            } else if before && !after {
118                self.tree.focus_scopes.remove(&self.id);
119            }
120        }
121        if let Some(Patch::File {
122            configuration: Change::Set(previous),
123            revision,
124        }) = &self.inverse
125        {
126            let Props::File(current) = self.descriptor().props else {
127                unreachable!()
128            };
129            if (**previous != current.configuration || *revision != current.revision)
130                && let Some(state) = self
131                    .tree
132                    .nodes
133                    .get_mut(&self.id)
134                    .expect("prepared file node")
135                    .files
136                    .as_mut()
137            {
138                state.clear();
139            }
140        }
141        if let Some(Patch::Semantics(Change::Set(previous))) = &self.inverse {
142            let before = previous.as_ref().and_then(|s| s.clipboard.as_ref());
143            let after = self
144                .descriptor()
145                .semantics
146                .as_ref()
147                .and_then(|s| s.clipboard.as_ref());
148            if before != after
149                && let Some(requests) = self
150                    .tree
151                    .nodes
152                    .get_mut(&self.id)
153                    .and_then(|n| n.clipboard.as_mut())
154            {
155                requests.cancel();
156            }
157        }
158        if let Some(Patch::Semantics(Change::Set(old))) = &self.inverse {
159            let old = old.as_ref().is_some_and(|s| s.layer.is_some());
160            let new = layer(self.descriptor());
161            self.tree.layers = self.tree.layers + usize::from(new) - usize::from(old);
162        }
163        if let Some(Patch::Semantics(Change::Set(old))) = &self.inverse {
164            let old = old.as_ref().and_then(|s| s.id.as_ref());
165            let new = self.descriptor().semantic_id();
166            if old != new {
167                let old = old.cloned();
168                let new = new.cloned();
169                if let Some(old) = old {
170                    self.tree.names.remove(&old);
171                }
172                if let Some(new) = new {
173                    self.tree.names.insert(new, self.id);
174                }
175            }
176        }
177        self.inverse = None;
178        self.tree.stats.patched += 1;
179    }
180    /// Accept exactly one mutation, using the same watermark as Render::apply.
181    pub fn commit(mut self) -> Receipt {
182        self.accept();
183        self.tree.receipt.applied += 1;
184        self.tree.receipt
185    }
186}
187impl Drop for PreparedPatch<'_> {
188    fn drop(&mut self) {
189        if let Some(mut inverse) = self.inverse.take() {
190            // The exclusive Memory borrow prevents disposal or replacement of
191            // this node. Undo swaps only built-in field values, not user code.
192            self.tree
193                .nodes
194                .get_mut(&self.id)
195                .expect("prepared node is live")
196                .descriptor
197                .swap_patch(&mut inverse)
198                .expect("validated inverse");
199            self.tree
200                .nodes
201                .get_mut(&self.id)
202                .expect("prepared node")
203                .descriptor
204                .restore_fields(self.fields_before);
205        }
206    }
207}
208
209impl Memory {
210    pub fn file_pending(&self, node: NodeId, request: u64, revision: u64) -> Result<bool, Error> {
211        let node = self.node(node)?;
212        Ok(node
213            .files
214            .as_ref()
215            .is_some_and(|state| state.pending(request, revision))
216            && matches!(node.descriptor.view().props,Props::File(props) if props.revision==revision))
217    }
218    pub fn validate_file_action(&self, action: Action) -> Result<(), Error> {
219        if !matches!(
220            action,
221            Action::PickFiles { .. } | Action::ClearFiles { .. } | Action::RemoveFile(_)
222        ) {
223            return Ok(());
224        }
225        let node = action.node();
226        action.validate_target(&self.node(node)?.descriptor)?;
227        if matches!(action, Action::PickFiles { .. } | Action::RemoveFile(_))
228            && (!self.active(node) || !self.enabled(node) || self.inert(node))
229        {
230            return Err(Error::Unsupported(
231                "file control is inactive, disabled or inert",
232            ));
233        }
234        if let Action::RemoveFile(file) = action {
235            self.selected_file(file)?;
236        }
237        Ok(())
238    }
239    pub fn admit_file_action(&mut self, action: Action) -> Result<(), Error> {
240        self.validate_file_action(action)?;
241        match action {
242            Action::PickFiles {
243                node,
244                revision,
245                request,
246            } => self.admit_file_picker(node, revision, request),
247            Action::ClearFiles { node, revision } => self.clear_files(node, revision),
248            Action::RemoveFile(file) => self.remove_file(file),
249            _ => Ok(()),
250        }
251    }
252
253    pub fn next_file_request(&self, node: NodeId) -> Result<u64, Error> {
254        self.node(node)?
255            .files
256            .as_ref()
257            .map_or(Ok(1), |state| state.next_request())
258    }
259    pub fn admit_file_picker(
260        &mut self,
261        node: NodeId,
262        revision: u64,
263        request: u64,
264    ) -> Result<(), Error> {
265        let Props::File(props) = self.node(node)?.descriptor.view().props else {
266            return Err(Error::Unsupported("file picker requires a File control"));
267        };
268        if revision != props.revision {
269            return Err(Error::InputRevision {
270                current: props.revision,
271                incoming: revision,
272            });
273        }
274        if !self.active(node) || !self.enabled(node) || self.inert(node) {
275            return Err(Error::Unsupported(
276                "file picker is inactive, disabled or inert",
277            ));
278        }
279        self.nodes
280            .get_mut(&node)
281            .expect("validated file node")
282            .files
283            .get_or_insert_with(Default::default)
284            .admit(request, revision)
285    }
286    pub fn validate_file_event(
287        &self,
288        node: NodeId,
289        document: FileDocumentId,
290        event: &FileEvent,
291    ) -> Result<bool, Error> {
292        let target = self.node(node)?;
293        let Props::File(props) = target.descriptor.view().props else {
294            return Err(Error::InvalidEvent("file event requires a File control"));
295        };
296        if matches!(&event.outcome, FileOutcome::Selected(_))
297            && (!self.active(node) || !self.enabled(node) || self.inert(node))
298        {
299            return Ok(false);
300        }
301        match target.files.as_ref() {
302            Some(state) => state.validate_event(node, props, document, event),
303            None => {
304                crate::files::state::State::default().validate_event(node, props, document, event)
305            }
306        }
307    }
308    pub fn finish_files(
309        &mut self,
310        node: NodeId,
311        document: FileDocumentId,
312        event: &FileEvent,
313    ) -> Result<bool, Error> {
314        if !self.validate_file_event(node, document, event)? {
315            return Ok(false);
316        }
317        let target = self.nodes.get_mut(&node).expect("validated file node");
318        let Props::File(props) = target.descriptor.view().props else {
319            unreachable!()
320        };
321        target
322            .files
323            .get_or_insert_with(Default::default)
324            .observe(node, props, document, event)
325    }
326    pub fn selected_file(&self, token: FileToken) -> Result<&FileInfo, Error> {
327        token.validate()?;
328        let target = self.node(token.node)?;
329        let Props::File(props) = target.descriptor.view().props else {
330            return Err(Error::Unsupported("file token requires a File control"));
331        };
332        if props.revision != token.revision {
333            return Err(Error::Unsupported(
334                "file token belongs to a retired configuration",
335            ));
336        }
337        target
338            .files
339            .as_ref()
340            .ok_or(Error::Unsupported("file token is not selected"))?
341            .file(token)
342    }
343    pub fn clear_files(&mut self, node: NodeId, revision: u64) -> Result<(), Error> {
344        let target = self.node(node)?;
345        let Props::File(props) = target.descriptor.view().props else {
346            return Err(Error::Unsupported("clear files requires a File control"));
347        };
348        if revision != props.revision {
349            return Err(Error::InputRevision {
350                current: props.revision,
351                incoming: revision,
352            });
353        }
354        if let Some(state) = self
355            .nodes
356            .get_mut(&node)
357            .expect("validated file node")
358            .files
359            .as_mut()
360        {
361            state.clear();
362        }
363        Ok(())
364    }
365    pub fn remove_file(&mut self, token: FileToken) -> Result<(), Error> {
366        self.selected_file(token)?;
367        self.nodes
368            .get_mut(&token.node)
369            .expect("validated file node")
370            .files
371            .as_mut()
372            .expect("validated selection")
373            .remove(token)
374    }
375    /// Numeric identity belongs to this live NodeId, even if the source facet
376    /// is cleared and declared again. Merely reading it does not reserve it.
377    pub fn next_clipboard_request(&self, node: NodeId) -> Result<u64, Error> {
378        self.node(node)?
379            .clipboard
380            .as_ref()
381            .map_or(Ok(1), |state| state.next())
382    }
383    pub fn clipboard_pending(
384        &self,
385        node: NodeId,
386        request: u64,
387        revision: u64,
388    ) -> Result<bool, Error> {
389        let node = self.node(node)?;
390        Ok(node
391            .clipboard
392            .as_ref()
393            .is_some_and(|state| state.matches(request, revision))
394            && node
395                .descriptor
396                .view()
397                .semantics
398                .as_ref()
399                .and_then(|s| s.clipboard.as_ref())
400                .is_some_and(|source| source.revision == revision))
401    }
402    pub fn validate_clipboard_action(&self, action: Action) -> Result<(), Error> {
403        if !matches!(action, Action::CopyText { .. }) {
404            return Ok(());
405        }
406        let node = action.node();
407        action.validate_target(&self.node(node)?.descriptor)?;
408        if !self.active(node) || !self.enabled(node) || self.inert(node) {
409            return Err(Error::Unsupported(
410                "clipboard source is inactive, disabled or inert",
411            ));
412        }
413        Ok(())
414    }
415    /// Shared request admission. Call after capability checks, immediately
416    /// before queuing/performing the host action. No payload or callback cache.
417    pub fn admit_clipboard(&mut self, action: Action) -> Result<(), Error> {
418        let Action::CopyText {
419            node,
420            revision,
421            request,
422        } = action
423        else {
424            return Ok(());
425        };
426        self.validate_clipboard_action(action)?;
427        self.nodes
428            .get_mut(&node)
429            .expect("validated node")
430            .clipboard
431            .get_or_insert_with(Default::default)
432            .admit(request, revision)
433    }
434    /// First terminal delivery consumes the current pending numeric request.
435    pub fn finish_clipboard(
436        &mut self,
437        node: NodeId,
438        request: u64,
439        revision: u64,
440    ) -> Result<bool, Error> {
441        self.node(node)?;
442        self.nodes
443            .get_mut(&node)
444            .expect("validated node")
445            .clipboard
446            .as_mut()
447            .ok_or(Error::InvalidEvent(
448                "clipboard completion names an unadmitted request",
449            ))?
450            .observe(request, revision)
451    }
452    pub fn cancel_clipboard(&mut self, node: NodeId) -> Result<(), Error> {
453        self.node(node)?;
454        if let Some(state) = self
455            .nodes
456            .get_mut(&node)
457            .expect("validated node")
458            .clipboard
459            .as_mut()
460        {
461            state.cancel()
462        }
463        Ok(())
464    }
465    pub fn new(runtime: RuntimeId) -> Self {
466        Self {
467            runtime,
468            nodes: NodeMap::default(),
469            names: HashMap::new(),
470            generations: HashMap::new(),
471            roots: Children::default(),
472            inputs: Vec::new(),
473            receipt: Receipt::default(),
474            stats: Stats::default(),
475            layers: 0,
476            focus_scopes: std::collections::BTreeMap::new(),
477        }
478    }
479
480    pub fn node(&self, id: NodeId) -> Result<&Node, Error> {
481        self.check_runtime(id)?;
482        self.nodes.get(&id).ok_or(Error::NodeGone(id))
483    }
484
485    /// Resolve a symbolic relation to its live identity in O(1), without owning
486    /// the target or retaining names after disposal.
487    pub fn named(&self, name: &SemanticId) -> Option<NodeId> {
488        self.names.get(name).copied()
489    }
490
491    /// Nearest explicit collection boundary of a registered trigger. Walk only
492    /// semantic ancestors; never infer membership for descendant editors.
493    pub fn navigation(&self, id: NodeId) -> Option<(NodeId, Orientation)> {
494        let node = self.node(id).ok()?;
495        if !node.descriptor.view().semantics.as_ref()?.navigation_item {
496            return None;
497        }
498        let mut parent = node.parent;
499        while let Some(id) = parent {
500            let node = self.node(id).ok()?;
501            if let Some(axis) = node
502                .descriptor
503                .view()
504                .semantics
505                .as_ref()
506                .and_then(|s| s.navigation)
507            {
508                return Some((id, axis));
509            }
510            parent = node.parent;
511        }
512        None
513    }
514
515    fn validate_name<'a>(
516        &self,
517        descriptor: impl Into<DescriptorView<'a>>,
518        own: Option<NodeId>,
519    ) -> Result<(), Error> {
520        let descriptor = descriptor.into();
521        self.validate_choice_reference(descriptor)?;
522        if let Some(name) = descriptor.view().semantic_id()
523            && self.names.get(name).is_some_and(|id| Some(*id) != own)
524        {
525            return Err(Error::InvalidProps("duplicate semantic id"));
526        }
527        Ok(())
528    }
529
530    pub fn roots(&self) -> &[NodeId] {
531        &self.roots
532    }
533    pub fn len(&self) -> usize {
534        self.nodes.len()
535    }
536    pub fn is_empty(&self) -> bool {
537        self.nodes.is_empty()
538    }
539    pub fn retained_slots(&self) -> usize {
540        self.generations.len()
541    }
542    /// Numeric current declaration count; no source or historical layer scan.
543    pub fn layers(&self) -> usize {
544        self.layers
545    }
546    fn admit_layers(&self, additional: usize) -> Result<(), Error> {
547        if additional > MAX_LAYERS - self.layers {
548            return Err(Error::InvalidProps("live Layer budget exceeded"));
549        }
550        Ok(())
551    }
552    pub fn stats(&self) -> Stats {
553        self.stats
554    }
555    /// Accepted operation watermark, without forcing observation or layout.
556    pub fn receipt(&self) -> Receipt {
557        self.receipt
558    }
559
560    /// Prepare against this validated/canonical live tree without cloning the
561    /// descriptor or scanning unrelated payloads. The guard can be inspected by
562    /// a lowering adapter, then committed, or dropped if adapter checks fail.
563    pub fn prepare_patch(&mut self, id: NodeId, patch: &Patch) -> Result<PreparedPatch<'_>, Error> {
564        self.node(id)?;
565        if let Patch::Semantics(Change::Set(next)) = patch
566            && let Some(capture) = next.as_ref().and_then(|s| s.swipe_capture)
567        {
568            let target = &self.nodes[&id];
569            if target
570                .descriptor
571                .view()
572                .semantics
573                .as_ref()
574                .is_none_or(|s| s.swipe_capture.is_none())
575                && let Some(history) = &target.swipe
576                && capture.revision <= history.revision
577            {
578                return Err(Error::InvalidProps(
579                    "reactivating swipe capture must advance its node watermark",
580                ));
581            }
582        }
583        let fields_before = self.nodes[&id].descriptor.field_mask();
584        let mut inverse = patch.clone();
585        self.nodes
586            .get_mut(&id)
587            .expect("validated node")
588            .descriptor
589            .patch_live(&mut inverse)?;
590        let mut prepared = PreparedPatch {
591            tree: self,
592            id,
593            inverse: Some(inverse),
594            fields_before,
595            focus_size: None,
596        };
597        if matches!(prepared.previous(), Patch::Semantics(Change::Set(old)) if !old.as_ref().is_some_and(|s| s.focus_scope.is_some()))
598            && crate::focus_scope::declared(prepared.descriptor())
599        {
600            prepared.tree.admit_focus_scopes(1)?;
601            prepared.focus_size = Some(
602                prepared
603                    .tree
604                    .scope_subtree_size(id, crate::MAX_FOCUS_SCOPE_NODES)?,
605            );
606        }
607        if matches!(prepared.previous(), Patch::Semantics(Change::Set(old)) if !old.as_ref().is_some_and(|s| s.layer.is_some()))
608            && layer(prepared.descriptor())
609        {
610            prepared.tree.admit_layers(1)?;
611        }
612        if matches!(patch, Patch::Role(_))
613            && prepared.descriptor().role == Some(Role::Separator)
614            && !prepared.tree.nodes[&id].children.is_empty()
615        {
616            return Err(Error::InvalidProps(
617                "passive separators cannot contain children",
618            ));
619        }
620        if matches!(patch, Patch::Role(_))
621            && matches!(
622                prepared.descriptor().role,
623                Some(Role::Tooltip | Role::ProgressBar | Role::Slider)
624            )
625        {
626            for child in prepared.tree.nodes[&id].children.iter().copied() {
627                prepared
628                    .tree
629                    .validate_child(Subtree::Existing(child), Some(id))?;
630            }
631        }
632        if matches!(patch, Patch::Semantics(_) | Patch::Role(_)) {
633            let descriptor = prepared.descriptor();
634            prepared.tree.validate_choice_patch(id)?;
635            let role_transition = matches!(prepared.previous(), Patch::Role(Change::Set(old)) if *old == Some(Role::Listbox) || descriptor.role == Some(Role::Listbox));
636            let changed_owner = matches!(prepared.previous(), Patch::Semantics(Change::Set(previous)) if previous.as_ref().and_then(|s| s.id.as_ref()) != descriptor.semantic_id());
637            if role_transition || descriptor.role == Some(Role::Listbox) && changed_owner {
638                prepared.tree.validate_choice_contents(id)?;
639            }
640        }
641        if matches!(patch, Patch::Semantics(_)) {
642            if let Patch::Semantics(Change::Set(previous)) = prepared.previous()
643                && previous.as_ref().and_then(|s| s.document_part)
644                    != prepared.descriptor().document_part()
645            {
646                return Err(Error::InvalidProps("live document structure cannot change"));
647            }
648            prepared
649                .tree
650                .validate_name(prepared.descriptor(), Some(id))?;
651            if let Patch::Semantics(Change::Set(previous)) = prepared.previous()
652                && previous.as_ref().and_then(|s| s.field_part)
653                    != prepared.descriptor().field_part()
654            {
655                // Structural transitions must also validate existing content.
656                // State/association updates never scan the child collection.
657                if prepared.descriptor().field_part() == Some(crate::FieldPart::Form) {
658                    let mut pending: Vec<_> =
659                        prepared.tree.nodes[&id].children.iter().copied().collect();
660                    while let Some(child) = pending.pop() {
661                        let node = &prepared.tree.nodes[&child];
662                        if node.descriptor.view().field_part() == Some(crate::FieldPart::Form) {
663                            return Err(Error::InvalidPlacement("forms cannot be nested"));
664                        }
665                        pending.extend(node.children.iter().copied());
666                    }
667                }
668                for child in prepared.tree.nodes[&id].children.iter().copied() {
669                    prepared
670                        .tree
671                        .validate_child(Subtree::Existing(child), Some(id))?;
672                }
673            }
674        }
675        // Updating a controlled input's value and revision leaves its placement
676        // constraints unchanged. patch_live has already checked the input write.
677        if !matches!(
678            patch,
679            Patch::Text(_) | Patch::Label(_) | Patch::Classes(_) | Patch::Value { .. }
680        ) {
681            prepared.tree.validate_child_inner(
682                Subtree::Existing(id),
683                prepared.tree.nodes[&id].parent,
684                false,
685            )?;
686        }
687        Ok(prepared)
688    }
689
690    /// Suspension is inherited, but each node retains its own logical owner
691    /// and order. Disposing a parent also destroys its suspended children.
692    pub fn active(&self, id: NodeId) -> bool {
693        Self::active_in(&self.nodes, id)
694    }
695    /// Resolve one current named anchor and its ancestry. Missing or late-bound
696    /// relations remain valid configuration, but cannot open a physical layer.
697    pub fn layer_anchor_live(&self, id: NodeId) -> bool {
698        Self::layer_anchor_live_in(&self.nodes, &self.names, id)
699    }
700    fn layer_anchor_live_in(
701        nodes: &NodeMap<Node>,
702        names: &HashMap<SemanticId, NodeId>,
703        id: NodeId,
704    ) -> bool {
705        let Some(node) = nodes.get(&id) else {
706            return false;
707        };
708        let Some(anchor) = (|| {
709            node.descriptor
710                .view()
711                .semantics
712                .as_ref()?
713                .layer
714                .as_ref()?
715                .anchor
716                .as_ref()
717        })() else {
718            return true;
719        };
720        let Some(anchor) = names.get(anchor).copied() else {
721            return false;
722        };
723        if !Self::active_in(nodes, anchor)
724            || Self::inert_in(nodes, anchor)
725            || !nodes
726                .get(&anchor)
727                .is_some_and(|node| !matches!(node.descriptor.view().props, crate::Props::Group))
728        {
729            return false;
730        }
731        let mut cursor = Some(anchor);
732        while let Some(id) = cursor {
733            let Some(node) = nodes.get(&id) else {
734                return false;
735            };
736            if node.descriptor.view().style.display == Some(crate::style::Display::None) {
737                return false;
738            }
739            cursor = node.parent;
740        }
741        true
742    }
743    /// Logical group disabling also applies before a host has committed markup.
744    /// No source scan: only the live target and its ancestors are inspected.
745    pub fn enabled(&self, id: NodeId) -> bool {
746        Self::enabled_in(&self.nodes, id)
747    }
748    fn enabled_in(nodes: &NodeMap<Node>, id: NodeId) -> bool {
749        let mut cursor = Some(id);
750        while let Some(id) = cursor {
751            let Some(node) = nodes.get(&id) else {
752                return false;
753            };
754            if !node.descriptor.view().props.enabled()
755                || node.descriptor.view().semantics.as_ref().is_some_and(|s| {
756                    s.inert
757                        || matches!(
758                            s.field_part,
759                            Some(crate::FieldPart::Fieldset | crate::FieldPart::Form)
760                        ) && s.disabled
761                        || (s.splitter.is_some()
762                            || s.slider.is_some()
763                            || s.context_menu.is_some()
764                            || s.drag_capture.is_some()
765                            || s.swipe_capture.is_some()
766                            || matches!(
767                                node.descriptor.view().role,
768                                Some(
769                                    crate::Role::Menubar
770                                        | crate::Role::Tree
771                                        | crate::Role::TreeItem
772                                )
773                            ))
774                            && s.disabled
775                })
776            {
777                return false;
778            }
779            cursor = node.parent;
780        }
781        true
782    }
783
784    fn active_in(nodes: &NodeMap<Node>, id: NodeId) -> bool {
785        let mut cursor = Some(id);
786        while let Some(id) = cursor {
787            let Some(node) = nodes.get(&id) else {
788                return false;
789            };
790            if !node.placed || node.suspended || node.descriptor.view().hidden() {
791                return false;
792            }
793            cursor = node.parent;
794        }
795        true
796    }
797
798    /// Current semantic ancestry only; inert keeps layout, owners and queries.
799    pub fn inert(&self, id: NodeId) -> bool {
800        Self::inert_in(&self.nodes, id)
801    }
802    fn inert_in(nodes: &NodeMap<Node>, id: NodeId) -> bool {
803        let mut cursor = Some(id);
804        while let Some(id) = cursor {
805            let Some(node) = nodes.get(&id) else {
806                return false;
807            };
808            if node
809                .descriptor
810                .view()
811                .semantics
812                .as_ref()
813                .is_some_and(|s| s.inert)
814            {
815                return true;
816            }
817            cursor = node.parent;
818        }
819        false
820    }
821
822    fn prune_events(&mut self) {
823        let nodes = &self.nodes;
824        let names = &self.names;
825        let runtime = self.runtime;
826        self.inputs.retain(|input| {
827            !matches!(input, Input::Event { node, event } if (!Self::active_in(nodes, *node) && !event.is_terminal_loss()) || !Self::event_in(nodes, runtime, *node, event).unwrap_or(false) || matches!(event, Event::Dismiss(DismissReason::AnchorLost)) && Self::layer_anchor_live_in(nodes,names,*node))
828        });
829    }
830
831    /// False means an embedded origin was retired or is no longer active.
832    /// Malformed live origins/payloads are errors; no callback or mutation runs.
833    pub fn validate_event(&self, id: NodeId, event: &Event) -> Result<bool, Error> {
834        if !Self::event_in(&self.nodes, self.runtime, id, event)? {
835            return Ok(false);
836        }
837        if let Event::Clipboard {
838            request, revision, ..
839        } = event
840        {
841            event.validate_payload(id, &self.node(id)?.descriptor)?;
842            let Some(requests) = self.node(id)?.clipboard.as_ref() else {
843                return Err(Error::InvalidEvent(
844                    "clipboard completion names an unadmitted request",
845                ));
846            };
847            requests.validate(*request)?;
848            return Ok(requests.matches(*request, *revision));
849        }
850        if matches!(event, Event::Dismiss(crate::DismissReason::AnchorLost)) {
851            event.validate_payload(id, &self.node(id)?.descriptor)?;
852            return Ok(self.active(id) && !self.layer_anchor_live(id));
853        }
854        if matches!(
855            event,
856            Event::Choice {
857                command: crate::ChoiceCommand::RemoveLast,
858                ..
859            }
860        ) {
861            let owner = self
862                .node(id)?
863                .descriptor
864                .view()
865                .semantics
866                .as_ref()
867                .and_then(|value| value.controls.as_ref())
868                .and_then(|name| self.named(name));
869            let Some(owner) = owner else { return Ok(false) };
870            let owner = self.node(owner)?.descriptor.view();
871            if owner.role != Some(crate::Role::Listbox)
872                || !owner
873                    .semantics
874                    .as_ref()
875                    .is_some_and(|value| value.listbox_multiple)
876            {
877                return Err(Error::InvalidEvent(
878                    "remove-last requires its live multiple listbox",
879                ));
880            }
881        }
882        Ok(true)
883    }
884
885    fn event_in(
886        nodes: &NodeMap<Node>,
887        runtime: RuntimeId,
888        id: NodeId,
889        event: &Event,
890    ) -> Result<bool, Error> {
891        let get = |id: NodeId| {
892            if id.runtime() != runtime {
893                return Err(Error::ForeignRuntime);
894            }
895            nodes.get(&id).ok_or(Error::NodeGone(id))
896        };
897        let target = get(id)?;
898        if matches!(event, Event::Menu { .. })
899            && let Some(owner) = target
900                .descriptor
901                .view()
902                .semantics
903                .as_ref()
904                .and_then(|s| s.menu_search.as_ref())
905        {
906            event.validate_payload(id, &target.descriptor)?;
907            if !Self::active_in(nodes, id)
908                || !Self::enabled_in(nodes, id)
909                || Self::inert_in(nodes, id)
910            {
911                return Ok(false);
912            }
913            let mut cursor = target.parent;
914            let mut matching = false;
915            while let Some(parent) = cursor {
916                let node = get(parent)?;
917                if node.descriptor.view().role == Some(crate::Role::Menu) {
918                    matching = node.descriptor.view().semantic_id() == Some(owner);
919                    break;
920                }
921                cursor = node.parent;
922            }
923            if !matching {
924                return Ok(false);
925            }
926        }
927        if let Event::Clipboard {
928            request, revision, ..
929        } = event
930        {
931            let state = target.clipboard.as_ref().ok_or(Error::InvalidEvent(
932                "clipboard completion names an unadmitted request",
933            ))?;
934            state.validate(*request)?;
935            let Some(source) = target
936                .descriptor
937                .view()
938                .semantics
939                .as_ref()
940                .and_then(|s| s.clipboard.as_ref())
941            else {
942                return Ok(false);
943            };
944            if *revision < source.revision {
945                return Ok(false);
946            }
947            event.validate_payload(id, &target.descriptor)?;
948            return Ok(state.matches(*request, *revision));
949        }
950        if let Event::PresenceComplete { revision } = event {
951            event.validate_payload(id, &target.descriptor)?;
952            if target
953                .descriptor
954                .view()
955                .semantics
956                .as_ref()
957                .and_then(|s| s.presence.as_ref())
958                .is_some_and(|config| *revision < config.revision)
959            {
960                return Ok(false);
961            }
962        }
963        if let Event::CollapseComplete { revision } = event {
964            event.validate_payload(id, &target.descriptor)?;
965            if target
966                .descriptor
967                .view()
968                .semantics
969                .as_ref()
970                .and_then(|s| s.collapse.as_ref())
971                .is_some_and(|config| *revision < config.revision)
972            {
973                return Ok(false);
974            }
975        }
976        let interactive = || {
977            !event.is_user_interaction()
978                || !(Self::inert_in(nodes, id)
979                    || event
980                        .origin()
981                        .filter(|origin| *origin != id)
982                        .is_some_and(|origin| Self::inert_in(nodes, origin)))
983        };
984        if let Event::RichEdit(snapshot) | Event::RichSelection(snapshot) = event {
985            let Props::RichEditor(editor) = target.descriptor.view().props else {
986                return Err(Error::InvalidEvent("rich input requires its RichEditor"));
987            };
988            event.validate_payload(id, &target.descriptor)?;
989            if snapshot.revision < editor.revision {
990                return Ok(false);
991            }
992            if matches!(event, Event::RichEdit(_)) && target.descriptor.view().readonly() {
993                return Err(Error::InvalidEvent(
994                    "readonly rich document cannot be edited",
995                ));
996            }
997            return Ok(Self::active_in(nodes, id) && Self::enabled_in(nodes, id) && interactive());
998        }
999        if let Event::RichCommand { revision, .. } | Event::RichRejected { revision } = event {
1000            event.validate_payload(id, &target.descriptor)?;
1001            let current = match target.descriptor.view().props {
1002                Props::RichEditor(editor) => editor.revision,
1003                Props::Input(input) => input.revision,
1004                _ => unreachable!(),
1005            };
1006            return Ok(*revision == current
1007                && Self::active_in(nodes, id)
1008                && Self::enabled_in(nodes, id)
1009                && interactive()
1010                && (!matches!(event, Event::RichCommand { .. })
1011                    || !target.descriptor.view().readonly()));
1012        }
1013        if let Event::Swipe {
1014            from,
1015            x,
1016            y,
1017            revision,
1018            ..
1019        } = event
1020        {
1021            if from.runtime() != id.runtime() {
1022                return Err(Error::ForeignRuntime);
1023            }
1024            if *from != id || !x.is_finite() || !y.is_finite() {
1025                return Err(Error::InvalidEvent(
1026                    "swipe requires its exact finite boxed origin",
1027                ));
1028            }
1029            let capture = target
1030                .descriptor
1031                .view()
1032                .semantics
1033                .as_ref()
1034                .and_then(|s| s.swipe_capture);
1035            let Some(capture) = capture else {
1036                if target
1037                    .swipe
1038                    .as_ref()
1039                    .is_some_and(|state| *revision <= state.revision)
1040                {
1041                    return Ok(false);
1042                }
1043                return Err(Error::InvalidEvent("swipe target has no active capture"));
1044            };
1045            event.validate_payload(id, &target.descriptor)?;
1046            let mut visible = true;
1047            let mut cursor = Some(id);
1048            while let Some(id) = cursor {
1049                let node = get(id)?;
1050                let view = node.descriptor.view();
1051                if view.hidden() || view.style.display == Some(crate::style::Display::None) {
1052                    visible = false;
1053                    break;
1054                }
1055                cursor = node.parent;
1056            }
1057            return Ok(*revision == capture.revision
1058                && (Self::active_in(nodes, id) || event.is_terminal_loss())
1059                && (Self::enabled_in(nodes, id) || event.is_terminal_loss())
1060                && (visible || event.is_terminal_loss())
1061                && interactive());
1062        }
1063        if let Event::TreeNavigate { from, .. } = event {
1064            let source = match get(*from) {
1065                Ok(source) => source,
1066                Err(Error::NodeGone(_)) => return Ok(false),
1067                Err(error) => return Err(error),
1068            };
1069            event.validate_payload(id, &target.descriptor)?;
1070            let descriptor = source.descriptor.view();
1071            if descriptor.role != Some(crate::Role::TreeItem)
1072                || !matches!(descriptor.props, Props::View)
1073                || descriptor
1074                    .semantics
1075                    .as_ref()
1076                    .is_none_or(|s| s.tree_item.is_none())
1077            {
1078                return Err(Error::InvalidEvent(
1079                    "tree command origin must be a declared TreeItem",
1080                ));
1081            }
1082            if !Self::active_in(nodes, *from)
1083                || !Self::active_in(nodes, id)
1084                || !Self::enabled_in(nodes, *from)
1085                || !Self::enabled_in(nodes, id)
1086            {
1087                return Ok(false);
1088            }
1089            let mut cursor = source.parent;
1090            while let Some(current) = cursor {
1091                let ancestor = get(current)?;
1092                if ancestor.descriptor.view().role == Some(crate::Role::Tree) {
1093                    return if current == id {
1094                        Ok(interactive())
1095                    } else {
1096                        Err(Error::InvalidEvent("tree origin belongs to a nearer Tree"))
1097                    };
1098                }
1099                cursor = ancestor.parent;
1100            }
1101            return Err(Error::InvalidEvent("tree origin is outside its target"));
1102        }
1103        if let Event::GridNavigate { from, .. } = event {
1104            let source = match get(*from) {
1105                Ok(source) => source,
1106                Err(Error::NodeGone(_)) => return Ok(false),
1107                Err(error) => return Err(error),
1108            };
1109            event.validate_payload(id, &target.descriptor)?;
1110            if !matches!(source.descriptor.view().props, Props::Button(_)) {
1111                return Err(Error::InvalidEvent("grid origin must be a physical Button"));
1112            }
1113            if !Self::active_in(nodes, *from)
1114                || !Self::active_in(nodes, id)
1115                || !Self::enabled_in(nodes, *from)
1116            {
1117                return Ok(false);
1118            }
1119            let mut cursor = source.parent;
1120            while let Some(current) = cursor {
1121                let ancestor = get(current)?;
1122                if ancestor.descriptor.view().role == Some(crate::Role::Grid) {
1123                    return if current == id {
1124                        Ok(interactive())
1125                    } else {
1126                        Err(Error::InvalidEvent("grid origin belongs to a nearer Grid"))
1127                    };
1128                }
1129                cursor = ancestor.parent;
1130            }
1131            return Err(Error::InvalidEvent("grid origin is outside its target"));
1132        }
1133        if let Event::Sheet { revision, .. } = event {
1134            event.validate_payload(id, &target.descriptor)?;
1135            if target
1136                .descriptor
1137                .view()
1138                .semantics
1139                .as_ref()
1140                .and_then(|s| s.layer.as_ref())
1141                .and_then(|l| l.sheet.as_ref())
1142                .is_some_and(|sheet| *revision < sheet.revision)
1143            {
1144                return Ok(false);
1145            }
1146        }
1147        if let Event::PlotPointer { .. } = event {
1148            event.validate_payload(id, &target.descriptor)?;
1149            return Ok((event.is_terminal_loss()
1150                || (Self::active_in(nodes, id) && Self::enabled_in(nodes, id)))
1151                && interactive());
1152        }
1153        if let Event::Pointer { related, .. } | Event::PointerWithin { related, .. } = event {
1154            event.validate_payload(id, &target.descriptor)?;
1155            if let Some(related) = related {
1156                let source = match get(*related) {
1157                    Ok(node) => node,
1158                    Err(Error::NodeGone(_)) => return Ok(false),
1159                    Err(error) => return Err(error),
1160                };
1161                if matches!(source.descriptor.view().props, Props::Group) {
1162                    return Err(Error::InvalidEvent(
1163                        "pointer related origin has no physical box",
1164                    ));
1165                }
1166                if !Self::active_in(nodes, *related) {
1167                    return Ok(false);
1168                }
1169                let mut cursor = Some(*related);
1170                while let Some(current) = cursor {
1171                    if current == id {
1172                        return Ok(false);
1173                    }
1174                    cursor = nodes.get(&current).and_then(|node| node.parent);
1175                }
1176            }
1177            if matches!(event, Event::Pointer { .. }) {
1178                return Ok(
1179                    (Self::active_in(nodes, id) || event.is_terminal_loss()) && interactive()
1180                );
1181            }
1182        }
1183        if let Event::Submit {
1184            submitter: Some(submitter),
1185        } = event
1186        {
1187            event.validate_payload(id, &target.descriptor)?;
1188            let source = match get(*submitter) {
1189                Ok(source) => source,
1190                Err(Error::NodeGone(_)) => return Ok(false),
1191                Err(error) => return Err(error),
1192            };
1193            if source
1194                .descriptor
1195                .view()
1196                .semantics
1197                .as_ref()
1198                .and_then(|s| s.form_action)
1199                != Some(crate::FormAction::Submit)
1200            {
1201                return Err(Error::InvalidEvent(
1202                    "submit origin requires a submit button",
1203                ));
1204            }
1205            if !source.descriptor.view().activation_enabled() || !Self::active_in(nodes, *submitter)
1206            {
1207                return Ok(false);
1208            }
1209        }
1210        if target.descriptor.view().readonly()
1211            && matches!(
1212                event,
1213                Event::ValueChanged { .. }
1214                    | Event::InputEdit(_)
1215                    | Event::Commit { .. }
1216                    | Event::CheckedChanged(_)
1217                    | Event::SelectChanged { .. }
1218                    | Event::Range { .. }
1219                    | Event::Spin { .. }
1220                    | Event::Drag {
1221                        phase: crate::DragPhase::Start
1222                            | crate::DragPhase::Move
1223                            | crate::DragPhase::Drop,
1224                        ..
1225                    }
1226            )
1227        {
1228            event.validate_payload(id, &target.descriptor)?;
1229            return Ok(false);
1230        }
1231        if let Event::Drag { from, phase, .. } = event {
1232            event.validate_payload(id, &target.descriptor)?;
1233            let source = match get(*from) {
1234                Ok(source) => source,
1235                Err(Error::NodeGone(_)) => return Ok(false),
1236                Err(error) => return Err(error),
1237            };
1238            EventKind::Drag.validate_target(&source.descriptor)?;
1239            return Ok(
1240                (Self::active_in(nodes, *from) || *phase == crate::DragPhase::Cancel)
1241                    && interactive(),
1242            );
1243        }
1244        // Navigation's explicit origin must be exactly the target, even if a
1245        // mismatched embedded identity has already been retired.
1246        if let Event::NavigationPanel { command, .. } = event {
1247            let mut cursor = Some(id);
1248            let mut inside = false;
1249            while let Some(current) = cursor {
1250                let node = get(current)?;
1251                if node
1252                    .descriptor
1253                    .view()
1254                    .semantics
1255                    .as_ref()
1256                    .and_then(|s| s.navigation_panel)
1257                    == Some(crate::NavigationPanel::Content)
1258                {
1259                    inside = true;
1260                    break;
1261                }
1262                cursor = node.parent;
1263            }
1264            if matches!(
1265                command,
1266                crate::NavigationPanelCommand::Close | crate::NavigationPanelCommand::Open
1267            ) && !inside
1268                || matches!(
1269                    command,
1270                    crate::NavigationPanelCommand::First | crate::NavigationPanelCommand::Last
1271                ) && inside
1272            {
1273                return Err(Error::InvalidEvent(
1274                    "navigation panel command disagrees with its mounted content level",
1275                ));
1276            }
1277        }
1278        if matches!(
1279            event,
1280            Event::Navigate { .. }
1281                | Event::Keyboard { .. }
1282                | Event::Palette { .. }
1283                | Event::ScrollKeyboard { .. }
1284                | Event::Range { .. }
1285                | Event::Spin { .. }
1286                | Event::Typeahead { .. }
1287                | Event::Menu { .. }
1288                | Event::NavigationPanel { .. }
1289                | Event::Choice { .. }
1290                | Event::Tags { .. }
1291        ) {
1292            event.validate_payload(id, &target.descriptor)?;
1293            return Ok(interactive()
1294                && (!matches!(event, Event::Palette { .. }) || Self::active_in(nodes, id)));
1295        }
1296        if let Some(origin) = event.origin() {
1297            let source = match get(origin) {
1298                Ok(node) => node,
1299                Err(Error::NodeGone(_)) => return Ok(false),
1300                Err(error) => return Err(error),
1301            };
1302            if matches!(source.descriptor.view().props, Props::Group) {
1303                return Err(Error::InvalidEvent("event origin has no physical box"));
1304            }
1305            if matches!(event, Event::ContextMenu { .. }) {
1306                if !Self::active_in(nodes, origin) {
1307                    return Ok(false);
1308                }
1309                if target
1310                    .descriptor
1311                    .view()
1312                    .semantics
1313                    .as_ref()
1314                    .and_then(|s| s.context_menu)
1315                    == Some(crate::ContextEditPolicy::Native)
1316                    && matches!(
1317                        source.descriptor.view().props,
1318                        Props::Input(_) | Props::Select(_)
1319                    )
1320                {
1321                    return Ok(false);
1322                }
1323            }
1324            if matches!(event, Event::Anchor { .. }) && origin == id {
1325                return Err(Error::InvalidEvent("anchor must originate in a descendant"));
1326            }
1327            let mut cursor = Some(origin);
1328            while cursor != Some(id) {
1329                if matches!(event, Event::ContextMenu { .. })
1330                    && cursor.and_then(|id| nodes.get(&id)).is_some_and(|node| {
1331                        node.descriptor
1332                            .view()
1333                            .semantics
1334                            .as_ref()
1335                            .is_some_and(|s| s.context_menu.is_some())
1336                    })
1337                {
1338                    return Err(Error::InvalidEvent(
1339                        "context origin belongs to a nearer region",
1340                    ));
1341                }
1342                if matches!(event, Event::Submit { .. })
1343                    && cursor.and_then(|id| nodes.get(&id)).is_some_and(|node| {
1344                        node.descriptor.view().field_part() == Some(crate::FieldPart::Fieldset)
1345                            && node
1346                                .descriptor
1347                                .view()
1348                                .semantics
1349                                .as_ref()
1350                                .is_some_and(|s| s.disabled)
1351                    })
1352                {
1353                    return Ok(false);
1354                }
1355                cursor = cursor
1356                    .and_then(|id| nodes.get(&id))
1357                    .and_then(|node| node.parent);
1358                if cursor.is_none() {
1359                    return Err(Error::InvalidEvent("event origin is outside its target"));
1360                }
1361            }
1362            if !Self::active_in(nodes, origin) && !event.is_terminal_loss() {
1363                return Ok(false);
1364            }
1365        }
1366        event.validate_payload(id, &target.descriptor)?;
1367        Ok(interactive())
1368    }
1369
1370    pub fn push_event(&mut self, id: NodeId, event: Event) -> Result<(), Error> {
1371        let node = self.node(id)?;
1372        if matches!(event, Event::Activate) && !node.descriptor.view().activation_enabled() {
1373            return Err(Error::InvalidProps("activation is disabled"));
1374        }
1375        if !self.validate_event(id, &event)? {
1376            return Ok(());
1377        }
1378        if !self.active(id) && !event.is_terminal_loss() {
1379            return Err(Error::InvalidPlacement("event target is not active"));
1380        }
1381        if matches!(
1382            event,
1383            Event::Activate
1384                | Event::Submit { .. }
1385                | Event::Reset
1386                | Event::Keyboard { .. }
1387                | Event::Palette { .. }
1388                | Event::ScrollKeyboard { .. }
1389                | Event::Range { .. }
1390                | Event::Spin { .. }
1391                | Event::Typeahead { .. }
1392                | Event::Menu { .. }
1393                | Event::NavigationPanel { .. }
1394                | Event::Choice { .. }
1395                | Event::Tags { .. }
1396                | Event::ContextMenu { .. }
1397                | Event::Drag {
1398                    phase: crate::DragPhase::Start
1399                        | crate::DragPhase::Move
1400                        | crate::DragPhase::Drop,
1401                    ..
1402                }
1403                | Event::CheckedChanged(_)
1404                | Event::SelectChanged { .. }
1405                | Event::ValueChanged { .. }
1406                | Event::Commit { .. }
1407        ) && !self.enabled(id)
1408        {
1409            return Err(Error::InvalidProps(
1410                "disabled control cannot receive user edits or activation",
1411            ));
1412        }
1413        self.inputs.push(Input::Event { node: id, event });
1414        Ok(())
1415    }
1416
1417    fn check_runtime(&self, id: NodeId) -> Result<(), Error> {
1418        if id.runtime() == self.runtime {
1419            Ok(())
1420        } else {
1421            Err(Error::ForeignRuntime)
1422        }
1423    }
1424
1425    fn unlink(&mut self, id: NodeId) {
1426        let node = &self.nodes[&id];
1427        if !node.placed {
1428            return;
1429        }
1430        let next = node.next;
1431        let siblings = if let Some(parent) = node.parent {
1432            &mut self
1433                .nodes
1434                .get_mut(&parent)
1435                .expect("validated parent")
1436                .children
1437        } else {
1438            &mut self.roots
1439        };
1440        let previous = siblings.remove_id(id);
1441        if let Some(previous) = previous {
1442            self.nodes
1443                .get_mut(&previous)
1444                .expect("previous sibling")
1445                .next = next;
1446        }
1447    }
1448
1449    /// Next logical sibling of a placed node, including suspended siblings.
1450    /// Identity validation precedes the constant-time adjacency lookup.
1451    pub fn next_sibling(&self, id: NodeId) -> Result<Option<NodeId>, Error> {
1452        let node = self.node(id)?;
1453        Ok(node.placed.then_some(node.next).flatten())
1454    }
1455
1456    /// Check a proposed parent/child relation without allocating identities or
1457    /// modifying state. Ordinary moves visit ancestors only; only restricted
1458    /// interactive/button contexts require examining the child's live subtree.
1459    pub fn validate_child(&self, child: Subtree<'_>, parent: Option<NodeId>) -> Result<(), Error> {
1460        self.validate_child_inner(child, parent, true)
1461    }
1462
1463    fn validate_child_inner(
1464        &self,
1465        child: Subtree<'_>,
1466        parent: Option<NodeId>,
1467        choice: bool,
1468    ) -> Result<(), Error> {
1469        let descriptor = match child {
1470            Subtree::New(d) => d,
1471            Subtree::Plan(plan) => plan.nodes()[0].descriptor.view(),
1472            Subtree::Existing(id) => self.node(id)?.descriptor.view(),
1473        };
1474        if let Some(parent) = parent
1475            && self.node(parent)?.descriptor.view().role == Some(Role::Separator)
1476        {
1477            return Err(Error::InvalidProps(
1478                "passive separators cannot contain children",
1479            ));
1480        }
1481        self.validate_document_placement(child, parent)?;
1482        if choice {
1483            self.validate_choice_child(child, parent)?;
1484        }
1485        if descriptor.field_part() == Some(crate::FieldPart::Legend)
1486            && parent.and_then(|id| self.node(id).ok()).is_none_or(|node| {
1487                node.descriptor.view().field_part() != Some(crate::FieldPart::Fieldset)
1488            })
1489        {
1490            return Err(Error::InvalidPlacement(
1491                "legend requires a direct fieldset parent",
1492            ));
1493        }
1494        if let Subtree::Existing(id) = child {
1495            self.node(id)?;
1496        }
1497        let mut cursor = parent;
1498        let mut interactive_ancestor = false;
1499        let mut button_ancestor = false;
1500        let mut form_ancestor = false;
1501        let mut tooltip_ancestor = false;
1502        while let Some(ancestor) = cursor {
1503            if matches!(child, Subtree::Existing(id) if ancestor == id) {
1504                return Err(Error::InvalidPlacement("tree cycle"));
1505            }
1506            let node = self.node(ancestor)?;
1507            if cursor == parent && !node.descriptor.view().props.accepts_children() {
1508                return Err(Error::InvalidProps("leaf widget cannot contain children"));
1509            }
1510            interactive_ancestor |= node.descriptor.view().props.interactive()
1511                || matches!(
1512                    node.descriptor.view().field_part(),
1513                    Some(crate::FieldPart::Label | crate::FieldPart::Legend)
1514                );
1515            button_ancestor |= matches!(
1516                node.descriptor.view().props,
1517                Props::Button(_) | Props::File(_)
1518            );
1519            form_ancestor |= node.descriptor.view().field_part() == Some(crate::FieldPart::Form);
1520            tooltip_ancestor |= matches!(
1521                node.descriptor.view().role,
1522                Some(Role::Tooltip | Role::ProgressBar | Role::Slider)
1523            );
1524            cursor = node.parent;
1525        }
1526        // Most placements (including ordinary list moves) need no subtree scan.
1527        self.validate_focus_child(child, parent)?;
1528        if let Subtree::New(descriptor) = child {
1529            self.validate_name(descriptor, None)?;
1530        }
1531        if let Subtree::Plan(plan) = child {
1532            for &index in plan.semantic_nodes() {
1533                self.validate_name(&plan.nodes()[index].descriptor, None)?;
1534            }
1535        }
1536        match child {
1537            Subtree::New(descriptor) => self.admit_layers(usize::from(layer(descriptor)))?,
1538            Subtree::Plan(plan) => self.admit_layers(plan.layers())?,
1539            Subtree::Existing(_) => {}
1540        }
1541        if form_ancestor && descriptor.field_part() == Some(crate::FieldPart::Form) {
1542            return Err(Error::InvalidPlacement("forms cannot be nested"));
1543        }
1544        // A same-parent property update/reorder cannot introduce a new nested
1545        // form. Only a changed ancestor context needs the moved live subtree.
1546        let form_scan = form_ancestor
1547            && match child {
1548                Subtree::Existing(id) => self.node(id)?.parent != parent,
1549                _ => true,
1550            };
1551        if !interactive_ancestor && !button_ancestor && !form_scan && !tooltip_ancestor {
1552            return Ok(());
1553        }
1554        let check = |descriptor: DescriptorView<'_>| {
1555            if form_scan && descriptor.field_part() == Some(crate::FieldPart::Form) {
1556                return Err(Error::InvalidPlacement("forms cannot be nested"));
1557            }
1558            crate::plan::validate_context(
1559                descriptor,
1560                interactive_ancestor,
1561                button_ancestor,
1562                tooltip_ancestor,
1563            )
1564        };
1565        match child {
1566            Subtree::New(descriptor) => check(descriptor)?,
1567            Subtree::Plan(plan) => {
1568                for node in plan.nodes() {
1569                    check(node.descriptor.view())?;
1570                }
1571            }
1572            Subtree::Existing(id) => {
1573                let mut pending = vec![id];
1574                while let Some(id) = pending.pop() {
1575                    let node = self.node(id)?;
1576                    check(node.descriptor.view())?;
1577                    pending.extend(node.children.iter().copied());
1578                }
1579            }
1580        }
1581        Ok(())
1582    }
1583
1584    fn validate_document_placement(
1585        &self,
1586        child: Subtree<'_>,
1587        parent: Option<NodeId>,
1588    ) -> Result<(), Error> {
1589        let mut boxed_parent = parent;
1590        while let Some(id) = boxed_parent {
1591            let node = self.node(id)?;
1592            if !matches!(node.descriptor.view().props, Props::Group) {
1593                break;
1594            }
1595            boxed_parent = node.parent;
1596        }
1597        let parent = boxed_parent
1598            .map(|id| self.node(id).map(|node| node.descriptor.view()))
1599            .transpose()?;
1600        let check = |descriptor: DescriptorView<'_>| {
1601            crate::document::validate_child(descriptor, parent, false)
1602        };
1603        match child {
1604            Subtree::New(descriptor) => check(descriptor)?,
1605            Subtree::Existing(id) => {
1606                // Only transparent ranges change the physical parent of their
1607                // contents. Stop at boxed nodes; never scan business sources.
1608                let node = self.node(id)?;
1609                check(node.descriptor.view())?;
1610                if matches!(node.descriptor.view().props, Props::Group) {
1611                    let mut pending = node.children.iter().copied().collect::<Vec<_>>();
1612                    while let Some(id) = pending.pop() {
1613                        let node = self.node(id)?;
1614                        check(node.descriptor.view())?;
1615                        if matches!(node.descriptor.view().props, Props::Group) {
1616                            pending.extend(node.children.iter().copied());
1617                        }
1618                    }
1619                }
1620            }
1621            Subtree::Plan(plan) => {
1622                for &index in plan.document_roots() {
1623                    check(plan.nodes()[index].descriptor.view())?;
1624                }
1625            }
1626        }
1627        Ok(())
1628    }
1629
1630    /// Read-only validation shared by App staging and direct reference apply.
1631    pub fn validate_placement(
1632        &self,
1633        id: NodeId,
1634        parent: Option<NodeId>,
1635        before: Option<NodeId>,
1636        resume: bool,
1637    ) -> Result<(), Error> {
1638        let node = self.node(id)?;
1639        if resume != node.suspended {
1640            return Err(Error::InvalidPlacement(
1641                "use Resume for suspended nodes and Place otherwise",
1642            ));
1643        }
1644        self.validate_child(Subtree::Existing(id), parent)?;
1645        if let Some(before) = before {
1646            let sibling = self.node(before)?;
1647            if before == id || !sibling.placed || sibling.parent != parent {
1648                return Err(Error::InvalidPlacement(
1649                    "before must be a different child of the target parent",
1650                ));
1651            }
1652        }
1653        Ok(())
1654    }
1655
1656    fn place(
1657        &mut self,
1658        id: NodeId,
1659        parent: Option<NodeId>,
1660        before: Option<NodeId>,
1661        resume: bool,
1662    ) -> Result<(), Error> {
1663        self.validate_placement(id, parent, before, resume)?;
1664        let focus_movement = self.scope_movement(id, parent)?;
1665        self.unlink(id);
1666        let siblings = if let Some(parent) = parent {
1667            &mut self
1668                .nodes
1669                .get_mut(&parent)
1670                .expect("validated parent")
1671                .children
1672        } else {
1673            &mut self.roots
1674        };
1675        let previous = siblings.insert_before(id, before);
1676        if let Some(previous) = previous {
1677            self.nodes
1678                .get_mut(&previous)
1679                .expect("previous sibling")
1680                .next = Some(id);
1681        }
1682        let node = self.nodes.get_mut(&id).expect("validated node");
1683        node.next = before;
1684        node.parent = parent;
1685        node.placed = true;
1686        node.suspended = false;
1687        if let Some(movement) = focus_movement {
1688            movement.commit(self);
1689        }
1690        self.stats.placed += 1;
1691        Ok(())
1692    }
1693
1694    fn apply_one(&mut self, mutation: &Mutation) -> Result<(), Error> {
1695        match mutation {
1696            Mutation::CreatePlan { plan, ids } => {
1697                if ids.len() != plan.nodes().len() {
1698                    return Err(Error::InvalidProps("plan identity count"));
1699                }
1700                // Strict slot order proves uniqueness for the whole batch.
1701                // Fresh/recycled runs need no temporary hash allocation. An
1702                // arbitrary caller still gets the original per-slot checks.
1703                let ordered = ids.windows(2).all(|pair| pair[0].slot() < pair[1].slot())
1704                    || ids.windows(2).all(|pair| pair[0].slot() > pair[1].slot());
1705                let mut slots =
1706                    (!ordered).then(|| std::collections::HashSet::with_capacity(ids.len()));
1707                for (index, (id, node)) in ids.iter().zip(plan.nodes()).enumerate() {
1708                    self.check_runtime(*id)?;
1709                    if slots.as_mut().is_some_and(|slots| !slots.insert(id.slot())) {
1710                        return Err(Error::InvalidPlacement("duplicate plan slot"));
1711                    }
1712                    if self.nodes.contains_key(id) {
1713                        return Err(Error::DuplicateNode(*id));
1714                    }
1715                    if let Some((generation, live)) = self.generations.get(&id.slot()) {
1716                        if *live {
1717                            return Err(Error::InvalidPlacement("slot is still occupied"));
1718                        }
1719                        if *generation >= id.generation() {
1720                            return Err(Error::StaleNode(*id));
1721                        }
1722                    }
1723                    if plan.facts(index).live_names {
1724                        self.validate_name(&node.descriptor, None)?;
1725                    }
1726                }
1727                self.admit_layers(plan.layers())?;
1728                self.admit_focus_scopes(plan.focus_scopes())?;
1729                for (index, node) in plan.nodes().iter().enumerate() {
1730                    // The immutable declaration checked content/topology once;
1731                    // the complete identity/name check above precedes mutation.
1732                    // Fresh nodes need no unlink, ancestor walk or temporary Box.
1733                    let id = ids[index];
1734                    let descriptor = LiveDescriptor::plan(plan, index);
1735                    let facts = plan.facts(index);
1736                    self.layers += usize::from(facts.layer);
1737                    if facts.focus_nodes != 0 {
1738                        self.focus_scopes.insert(id, usize::from(facts.focus_nodes));
1739                    }
1740                    if let Some(name) = descriptor.view().semantic_id() {
1741                        self.names.insert(name.clone(), id);
1742                    }
1743                    self.generations.insert(id.slot(), (id.generation(), true));
1744                    let swipe = descriptor
1745                        .view()
1746                        .semantics
1747                        .as_ref()
1748                        .and_then(|s| s.swipe_capture)
1749                        .map(crate::swipe::State::new);
1750                    self.nodes.insert(
1751                        id,
1752                        Node {
1753                            descriptor,
1754                            parent: node.parent.map(|parent| ids[parent]),
1755                            children: Children::default(),
1756                            placed: node.parent.is_some(),
1757                            suspended: false,
1758                            next: None,
1759                            clipboard: None,
1760                            files: None,
1761                            swipe,
1762                        },
1763                    );
1764                    self.stats.created += 1;
1765                    if let Some(parent) = node.parent {
1766                        let siblings = &mut self
1767                            .nodes
1768                            .get_mut(&ids[parent])
1769                            .expect("plan parent")
1770                            .children;
1771                        let previous = siblings.last().copied();
1772                        siblings.insert_before(id, None);
1773                        if let Some(previous) = previous {
1774                            self.nodes.get_mut(&previous).expect("plan sibling").next = Some(id);
1775                        }
1776                        self.stats.placed += 1;
1777                    }
1778                }
1779            }
1780            Mutation::Create { id, node } => {
1781                self.check_runtime(*id)?;
1782                node.validate()?;
1783                if self.nodes.contains_key(id) {
1784                    return Err(Error::DuplicateNode(*id));
1785                }
1786                if let Some((generation, live)) = self.generations.get(&id.slot()) {
1787                    if *live {
1788                        return Err(Error::InvalidPlacement("slot is still occupied"));
1789                    }
1790                    if *generation >= id.generation() {
1791                        return Err(Error::StaleNode(*id));
1792                    }
1793                }
1794                let mut descriptor = node.as_ref().clone();
1795                self.validate_name(node.as_ref(), None)?;
1796                self.admit_layers(usize::from(layer(node.view())))?;
1797                self.admit_focus_scopes(usize::from(crate::focus_scope::declared(node.view())))?;
1798                descriptor.normalize_input()?;
1799                self.layers += usize::from(layer(descriptor.view()));
1800                if crate::focus_scope::declared(descriptor.view()) {
1801                    self.focus_scopes.insert(*id, 1);
1802                }
1803                if let Some(name) = descriptor.view().semantic_id() {
1804                    self.names.insert(name.clone(), *id);
1805                }
1806                self.generations.insert(id.slot(), (id.generation(), true));
1807                let swipe = descriptor
1808                    .view()
1809                    .semantics
1810                    .as_ref()
1811                    .and_then(|s| s.swipe_capture)
1812                    .map(crate::swipe::State::new);
1813                self.nodes.insert(
1814                    *id,
1815                    Node {
1816                        descriptor: LiveDescriptor::owned(descriptor),
1817                        parent: None,
1818                        children: Children::default(),
1819                        placed: false,
1820                        suspended: false,
1821                        next: None,
1822                        clipboard: None,
1823                        files: None,
1824                        swipe,
1825                    },
1826                );
1827                self.stats.created += 1;
1828            }
1829            Mutation::Patch { id, patch } => {
1830                self.prepare_patch(*id, patch)?.accept();
1831            }
1832            Mutation::Place { id, parent, before } => self.place(*id, *parent, *before, false)?,
1833            Mutation::Resume { id, parent, before } => self.place(*id, *parent, *before, true)?,
1834            Mutation::Suspend { id } => {
1835                let node = self.node(*id)?;
1836                if !node.placed || node.suspended {
1837                    return Err(Error::InvalidPlacement(
1838                        "only placed active ranges can be suspended",
1839                    ));
1840                }
1841                self.nodes.get_mut(id).expect("validated node").suspended = true;
1842                self.prune_events();
1843                self.stats.suspended += 1;
1844            }
1845            Mutation::Dispose { id } => self.retire(*id, None)?,
1846        }
1847        Ok(())
1848    }
1849
1850    /// Apply one Dispose and return its retired identities in traversal order.
1851    /// Adapters use the removal itself to reclaim their identity-indexed state,
1852    /// instead of first walking the same subtree to build a second inventory.
1853    /// Includes detached/suspended descendants; rejection preserves the receipt.
1854    pub fn dispose(&mut self, id: NodeId) -> Result<(Receipt, Vec<NodeId>), Error> {
1855        let mut retired = Vec::new();
1856        self.retire(id, Some(&mut retired))?;
1857        self.receipt.applied += 1;
1858        Ok((self.receipt, retired))
1859    }
1860
1861    fn retire(&mut self, id: NodeId, mut retired: Option<&mut Vec<NodeId>>) -> Result<(), Error> {
1862        let parent = self.node(id)?.parent;
1863        let focus_ancestors = self.scope_ancestors(parent)?;
1864        self.unlink(id);
1865        let mut pending = vec![id];
1866        let mut focus_removed = 0usize;
1867        while let Some(id) = pending.pop() {
1868            let node = self.nodes.remove(&id).expect("owned subtree");
1869            self.focus_scopes.remove(&id);
1870            focus_removed += 1;
1871            self.layers -= usize::from(layer(node.descriptor.view()));
1872            if let Some(name) = node.descriptor.view().semantic_id() {
1873                self.names.remove(name);
1874            }
1875            self.generations
1876                .get_mut(&id.slot())
1877                .expect("known identity")
1878                .1 = false;
1879            pending.extend(node.children);
1880            self.stats.disposed += 1;
1881            if let Some(retired) = &mut retired {
1882                retired.push(id);
1883            }
1884        }
1885        for root in focus_ancestors {
1886            *self
1887                .focus_scopes
1888                .get_mut(&root)
1889                .expect("surviving scope ancestor") -= focus_removed;
1890        }
1891        // Pending native/browser events carry identities too. Do not deliver
1892        // an event whose target was destroyed by this operation.
1893        self.prune_events();
1894        Ok(())
1895    }
1896}
1897
1898impl Render for Memory {
1899    fn supports_plot_pointer(&self) -> bool {
1900        true
1901    }
1902    fn listen(&mut self, node: NodeId, kind: EventKind, enabled: bool) -> Result<(), Error> {
1903        let descriptor = self.node(node)?.descriptor.view();
1904        if enabled {
1905            kind.validate_target(descriptor)?;
1906        }
1907        Ok(())
1908    }
1909    fn action(&mut self, action: Action) -> Result<(), Error> {
1910        action.validate_target(&self.node(action.node())?.descriptor)?;
1911        self.validate_clipboard_action(action)?;
1912        Err(Error::Unsupported(
1913            "headless reference interpreter has no physical actions",
1914        ))
1915    }
1916    fn needs_observe(&self) -> bool {
1917        !self.inputs.is_empty()
1918    }
1919    fn style_profile(&self) -> style::Profile {
1920        style::Profile::RECORD
1921    }
1922    fn capabilities(&self) -> Capabilities {
1923        Capabilities::default()
1924    }
1925
1926    fn apply(&mut self, mutations: &[Mutation]) -> Result<Receipt, Error> {
1927        for mutation in mutations {
1928            self.apply_one(mutation)?;
1929            self.receipt.applied += 1;
1930        }
1931        Ok(self.receipt)
1932    }
1933
1934    fn request(&mut self, query: Query, token: QueryToken) -> Result<(), Error> {
1935        let result = query
1936            .validate_target(&self.node(query.node())?.descriptor)
1937            .and(Err(Error::Unsupported(
1938                "headless reference interpreter has no platform geometry, selection or focus",
1939            )));
1940        self.inputs.push(Input::Response {
1941            token,
1942            applied: self.receipt.applied,
1943            result,
1944        });
1945        Ok(())
1946    }
1947
1948    fn drain(&mut self, inputs: &mut Vec<Input>) {
1949        self.prune_events();
1950        inputs.append(&mut self.inputs);
1951    }
1952}