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        if !matches!(patch, Patch::Text(_) | Patch::Label(_) | Patch::Classes(_)) {
676            prepared.tree.validate_child_inner(
677                Subtree::Existing(id),
678                prepared.tree.nodes[&id].parent,
679                false,
680            )?;
681        }
682        Ok(prepared)
683    }
684
685    /// Suspension is inherited, but each node retains its own logical owner
686    /// and order. Disposing a parent also destroys its suspended children.
687    pub fn active(&self, id: NodeId) -> bool {
688        Self::active_in(&self.nodes, id)
689    }
690    /// Resolve one current named anchor and its ancestry. Missing or late-bound
691    /// relations remain valid configuration, but cannot open a physical layer.
692    pub fn layer_anchor_live(&self, id: NodeId) -> bool {
693        Self::layer_anchor_live_in(&self.nodes, &self.names, id)
694    }
695    fn layer_anchor_live_in(
696        nodes: &NodeMap<Node>,
697        names: &HashMap<SemanticId, NodeId>,
698        id: NodeId,
699    ) -> bool {
700        let Some(node) = nodes.get(&id) else {
701            return false;
702        };
703        let Some(anchor) = (|| {
704            node.descriptor
705                .view()
706                .semantics
707                .as_ref()?
708                .layer
709                .as_ref()?
710                .anchor
711                .as_ref()
712        })() else {
713            return true;
714        };
715        let Some(anchor) = names.get(anchor).copied() else {
716            return false;
717        };
718        if !Self::active_in(nodes, anchor)
719            || Self::inert_in(nodes, anchor)
720            || !nodes
721                .get(&anchor)
722                .is_some_and(|node| !matches!(node.descriptor.view().props, crate::Props::Group))
723        {
724            return false;
725        }
726        let mut cursor = Some(anchor);
727        while let Some(id) = cursor {
728            let Some(node) = nodes.get(&id) else {
729                return false;
730            };
731            if node.descriptor.view().style.display == Some(crate::style::Display::None) {
732                return false;
733            }
734            cursor = node.parent;
735        }
736        true
737    }
738    /// Logical group disabling also applies before a host has committed markup.
739    /// No source scan: only the live target and its ancestors are inspected.
740    pub fn enabled(&self, id: NodeId) -> bool {
741        Self::enabled_in(&self.nodes, id)
742    }
743    fn enabled_in(nodes: &NodeMap<Node>, id: NodeId) -> bool {
744        let mut cursor = Some(id);
745        while let Some(id) = cursor {
746            let Some(node) = nodes.get(&id) else {
747                return false;
748            };
749            if !node.descriptor.view().props.enabled()
750                || node.descriptor.view().semantics.as_ref().is_some_and(|s| {
751                    s.inert
752                        || matches!(
753                            s.field_part,
754                            Some(crate::FieldPart::Fieldset | crate::FieldPart::Form)
755                        ) && s.disabled
756                        || (s.splitter.is_some()
757                            || s.slider.is_some()
758                            || s.context_menu.is_some()
759                            || s.drag_capture.is_some()
760                            || s.swipe_capture.is_some()
761                            || matches!(
762                                node.descriptor.view().role,
763                                Some(
764                                    crate::Role::Menubar
765                                        | crate::Role::Tree
766                                        | crate::Role::TreeItem
767                                )
768                            ))
769                            && s.disabled
770                })
771            {
772                return false;
773            }
774            cursor = node.parent;
775        }
776        true
777    }
778
779    fn active_in(nodes: &NodeMap<Node>, id: NodeId) -> bool {
780        let mut cursor = Some(id);
781        while let Some(id) = cursor {
782            let Some(node) = nodes.get(&id) else {
783                return false;
784            };
785            if !node.placed || node.suspended || node.descriptor.view().hidden() {
786                return false;
787            }
788            cursor = node.parent;
789        }
790        true
791    }
792
793    /// Current semantic ancestry only; inert keeps layout, owners and queries.
794    pub fn inert(&self, id: NodeId) -> bool {
795        Self::inert_in(&self.nodes, id)
796    }
797    fn inert_in(nodes: &NodeMap<Node>, id: NodeId) -> bool {
798        let mut cursor = Some(id);
799        while let Some(id) = cursor {
800            let Some(node) = nodes.get(&id) else {
801                return false;
802            };
803            if node
804                .descriptor
805                .view()
806                .semantics
807                .as_ref()
808                .is_some_and(|s| s.inert)
809            {
810                return true;
811            }
812            cursor = node.parent;
813        }
814        false
815    }
816
817    fn prune_events(&mut self) {
818        let nodes = &self.nodes;
819        let names = &self.names;
820        let runtime = self.runtime;
821        self.inputs.retain(|input| {
822            !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))
823        });
824    }
825
826    /// False means an embedded origin was retired or is no longer active.
827    /// Malformed live origins/payloads are errors; no callback or mutation runs.
828    pub fn validate_event(&self, id: NodeId, event: &Event) -> Result<bool, Error> {
829        if !Self::event_in(&self.nodes, self.runtime, id, event)? {
830            return Ok(false);
831        }
832        if let Event::Clipboard {
833            request, revision, ..
834        } = event
835        {
836            event.validate_payload(id, &self.node(id)?.descriptor)?;
837            let Some(requests) = self.node(id)?.clipboard.as_ref() else {
838                return Err(Error::InvalidEvent(
839                    "clipboard completion names an unadmitted request",
840                ));
841            };
842            requests.validate(*request)?;
843            return Ok(requests.matches(*request, *revision));
844        }
845        if matches!(event, Event::Dismiss(crate::DismissReason::AnchorLost)) {
846            event.validate_payload(id, &self.node(id)?.descriptor)?;
847            return Ok(self.active(id) && !self.layer_anchor_live(id));
848        }
849        if matches!(
850            event,
851            Event::Choice {
852                command: crate::ChoiceCommand::RemoveLast,
853                ..
854            }
855        ) {
856            let owner = self
857                .node(id)?
858                .descriptor
859                .view()
860                .semantics
861                .as_ref()
862                .and_then(|value| value.controls.as_ref())
863                .and_then(|name| self.named(name));
864            let Some(owner) = owner else { return Ok(false) };
865            let owner = self.node(owner)?.descriptor.view();
866            if owner.role != Some(crate::Role::Listbox)
867                || !owner
868                    .semantics
869                    .as_ref()
870                    .is_some_and(|value| value.listbox_multiple)
871            {
872                return Err(Error::InvalidEvent(
873                    "remove-last requires its live multiple listbox",
874                ));
875            }
876        }
877        Ok(true)
878    }
879
880    fn event_in(
881        nodes: &NodeMap<Node>,
882        runtime: RuntimeId,
883        id: NodeId,
884        event: &Event,
885    ) -> Result<bool, Error> {
886        let get = |id: NodeId| {
887            if id.runtime() != runtime {
888                return Err(Error::ForeignRuntime);
889            }
890            nodes.get(&id).ok_or(Error::NodeGone(id))
891        };
892        let target = get(id)?;
893        if let Event::Clipboard {
894            request, revision, ..
895        } = event
896        {
897            let state = target.clipboard.as_ref().ok_or(Error::InvalidEvent(
898                "clipboard completion names an unadmitted request",
899            ))?;
900            state.validate(*request)?;
901            let Some(source) = target
902                .descriptor
903                .view()
904                .semantics
905                .as_ref()
906                .and_then(|s| s.clipboard.as_ref())
907            else {
908                return Ok(false);
909            };
910            if *revision < source.revision {
911                return Ok(false);
912            }
913            event.validate_payload(id, &target.descriptor)?;
914            return Ok(state.matches(*request, *revision));
915        }
916        if let Event::CollapseComplete { revision } = event {
917            event.validate_payload(id, &target.descriptor)?;
918            if target
919                .descriptor
920                .view()
921                .semantics
922                .as_ref()
923                .and_then(|s| s.collapse.as_ref())
924                .is_some_and(|config| *revision < config.revision)
925            {
926                return Ok(false);
927            }
928        }
929        let interactive = || {
930            !event.is_user_interaction()
931                || !(Self::inert_in(nodes, id)
932                    || event
933                        .origin()
934                        .filter(|origin| *origin != id)
935                        .is_some_and(|origin| Self::inert_in(nodes, origin)))
936        };
937        if let Event::RichEdit(snapshot) | Event::RichSelection(snapshot) = event {
938            let Props::RichEditor(editor) = target.descriptor.view().props else {
939                return Err(Error::InvalidEvent("rich input requires its RichEditor"));
940            };
941            event.validate_payload(id, &target.descriptor)?;
942            if snapshot.revision < editor.revision {
943                return Ok(false);
944            }
945            if matches!(event, Event::RichEdit(_)) && target.descriptor.view().readonly() {
946                return Err(Error::InvalidEvent(
947                    "readonly rich document cannot be edited",
948                ));
949            }
950            return Ok(Self::active_in(nodes, id) && Self::enabled_in(nodes, id) && interactive());
951        }
952        if let Event::RichCommand { revision, .. } | Event::RichRejected { revision } = event {
953            event.validate_payload(id, &target.descriptor)?;
954            let Props::RichEditor(editor) = target.descriptor.view().props else {
955                unreachable!()
956            };
957            return Ok(*revision == editor.revision
958                && Self::active_in(nodes, id)
959                && Self::enabled_in(nodes, id)
960                && interactive()
961                && (!matches!(event, Event::RichCommand { .. })
962                    || !target.descriptor.view().readonly()));
963        }
964        if let Event::Swipe {
965            from,
966            x,
967            y,
968            revision,
969            ..
970        } = event
971        {
972            if from.runtime() != id.runtime() {
973                return Err(Error::ForeignRuntime);
974            }
975            if *from != id || !x.is_finite() || !y.is_finite() {
976                return Err(Error::InvalidEvent(
977                    "swipe requires its exact finite boxed origin",
978                ));
979            }
980            let capture = target
981                .descriptor
982                .view()
983                .semantics
984                .as_ref()
985                .and_then(|s| s.swipe_capture);
986            let Some(capture) = capture else {
987                if target
988                    .swipe
989                    .as_ref()
990                    .is_some_and(|state| *revision <= state.revision)
991                {
992                    return Ok(false);
993                }
994                return Err(Error::InvalidEvent("swipe target has no active capture"));
995            };
996            event.validate_payload(id, &target.descriptor)?;
997            let mut visible = true;
998            let mut cursor = Some(id);
999            while let Some(id) = cursor {
1000                let node = get(id)?;
1001                let view = node.descriptor.view();
1002                if view.hidden() || view.style.display == Some(crate::style::Display::None) {
1003                    visible = false;
1004                    break;
1005                }
1006                cursor = node.parent;
1007            }
1008            return Ok(*revision == capture.revision
1009                && (Self::active_in(nodes, id) || event.is_terminal_loss())
1010                && (Self::enabled_in(nodes, id) || event.is_terminal_loss())
1011                && (visible || event.is_terminal_loss())
1012                && interactive());
1013        }
1014        if let Event::TreeNavigate { from, .. } = event {
1015            let source = match get(*from) {
1016                Ok(source) => source,
1017                Err(Error::NodeGone(_)) => return Ok(false),
1018                Err(error) => return Err(error),
1019            };
1020            event.validate_payload(id, &target.descriptor)?;
1021            let descriptor = source.descriptor.view();
1022            if descriptor.role != Some(crate::Role::TreeItem)
1023                || !matches!(descriptor.props, Props::View)
1024                || descriptor
1025                    .semantics
1026                    .as_ref()
1027                    .is_none_or(|s| s.tree_item.is_none())
1028            {
1029                return Err(Error::InvalidEvent(
1030                    "tree command origin must be a declared TreeItem",
1031                ));
1032            }
1033            if !Self::active_in(nodes, *from)
1034                || !Self::active_in(nodes, id)
1035                || !Self::enabled_in(nodes, *from)
1036                || !Self::enabled_in(nodes, id)
1037            {
1038                return Ok(false);
1039            }
1040            let mut cursor = source.parent;
1041            while let Some(current) = cursor {
1042                let ancestor = get(current)?;
1043                if ancestor.descriptor.view().role == Some(crate::Role::Tree) {
1044                    return if current == id {
1045                        Ok(interactive())
1046                    } else {
1047                        Err(Error::InvalidEvent("tree origin belongs to a nearer Tree"))
1048                    };
1049                }
1050                cursor = ancestor.parent;
1051            }
1052            return Err(Error::InvalidEvent("tree origin is outside its target"));
1053        }
1054        if let Event::GridNavigate { from, .. } = event {
1055            let source = match get(*from) {
1056                Ok(source) => source,
1057                Err(Error::NodeGone(_)) => return Ok(false),
1058                Err(error) => return Err(error),
1059            };
1060            event.validate_payload(id, &target.descriptor)?;
1061            if !matches!(source.descriptor.view().props, Props::Button(_)) {
1062                return Err(Error::InvalidEvent("grid origin must be a physical Button"));
1063            }
1064            if !Self::active_in(nodes, *from)
1065                || !Self::active_in(nodes, id)
1066                || !Self::enabled_in(nodes, *from)
1067            {
1068                return Ok(false);
1069            }
1070            let mut cursor = source.parent;
1071            while let Some(current) = cursor {
1072                let ancestor = get(current)?;
1073                if ancestor.descriptor.view().role == Some(crate::Role::Grid) {
1074                    return if current == id {
1075                        Ok(interactive())
1076                    } else {
1077                        Err(Error::InvalidEvent("grid origin belongs to a nearer Grid"))
1078                    };
1079                }
1080                cursor = ancestor.parent;
1081            }
1082            return Err(Error::InvalidEvent("grid origin is outside its target"));
1083        }
1084        if let Event::Sheet { revision, .. } = event {
1085            event.validate_payload(id, &target.descriptor)?;
1086            if target
1087                .descriptor
1088                .view()
1089                .semantics
1090                .as_ref()
1091                .and_then(|s| s.layer.as_ref())
1092                .and_then(|l| l.sheet.as_ref())
1093                .is_some_and(|sheet| *revision < sheet.revision)
1094            {
1095                return Ok(false);
1096            }
1097        }
1098        if let Event::Pointer { related, .. } | Event::PointerWithin { related, .. } = event {
1099            event.validate_payload(id, &target.descriptor)?;
1100            if let Some(related) = related {
1101                let source = match get(*related) {
1102                    Ok(node) => node,
1103                    Err(Error::NodeGone(_)) => return Ok(false),
1104                    Err(error) => return Err(error),
1105                };
1106                if matches!(source.descriptor.view().props, Props::Group) {
1107                    return Err(Error::InvalidEvent(
1108                        "pointer related origin has no physical box",
1109                    ));
1110                }
1111                if !Self::active_in(nodes, *related) {
1112                    return Ok(false);
1113                }
1114                let mut cursor = Some(*related);
1115                while let Some(current) = cursor {
1116                    if current == id {
1117                        return Ok(false);
1118                    }
1119                    cursor = nodes.get(&current).and_then(|node| node.parent);
1120                }
1121            }
1122            if matches!(event, Event::Pointer { .. }) {
1123                return Ok(
1124                    (Self::active_in(nodes, id) || event.is_terminal_loss()) && interactive()
1125                );
1126            }
1127        }
1128        if let Event::Submit {
1129            submitter: Some(submitter),
1130        } = event
1131        {
1132            event.validate_payload(id, &target.descriptor)?;
1133            let source = match get(*submitter) {
1134                Ok(source) => source,
1135                Err(Error::NodeGone(_)) => return Ok(false),
1136                Err(error) => return Err(error),
1137            };
1138            if source
1139                .descriptor
1140                .view()
1141                .semantics
1142                .as_ref()
1143                .and_then(|s| s.form_action)
1144                != Some(crate::FormAction::Submit)
1145            {
1146                return Err(Error::InvalidEvent(
1147                    "submit origin requires a submit button",
1148                ));
1149            }
1150            if !source.descriptor.view().activation_enabled() || !Self::active_in(nodes, *submitter)
1151            {
1152                return Ok(false);
1153            }
1154        }
1155        if target.descriptor.view().readonly()
1156            && matches!(
1157                event,
1158                Event::ValueChanged { .. }
1159                    | Event::InputEdit(_)
1160                    | Event::Commit { .. }
1161                    | Event::CheckedChanged(_)
1162                    | Event::SelectChanged { .. }
1163                    | Event::Range { .. }
1164                    | Event::Spin { .. }
1165                    | Event::Drag {
1166                        phase: crate::DragPhase::Start
1167                            | crate::DragPhase::Move
1168                            | crate::DragPhase::Drop,
1169                        ..
1170                    }
1171            )
1172        {
1173            event.validate_payload(id, &target.descriptor)?;
1174            return Ok(false);
1175        }
1176        if let Event::Drag { from, phase, .. } = event {
1177            event.validate_payload(id, &target.descriptor)?;
1178            let source = match get(*from) {
1179                Ok(source) => source,
1180                Err(Error::NodeGone(_)) => return Ok(false),
1181                Err(error) => return Err(error),
1182            };
1183            EventKind::Drag.validate_target(&source.descriptor)?;
1184            return Ok(
1185                (Self::active_in(nodes, *from) || *phase == crate::DragPhase::Cancel)
1186                    && interactive(),
1187            );
1188        }
1189        // Navigation's explicit origin must be exactly the target, even if a
1190        // mismatched embedded identity has already been retired.
1191        if let Event::NavigationPanel { command, .. } = event {
1192            let mut cursor = Some(id);
1193            let mut inside = false;
1194            while let Some(current) = cursor {
1195                let node = get(current)?;
1196                if node
1197                    .descriptor
1198                    .view()
1199                    .semantics
1200                    .as_ref()
1201                    .and_then(|s| s.navigation_panel)
1202                    == Some(crate::NavigationPanel::Content)
1203                {
1204                    inside = true;
1205                    break;
1206                }
1207                cursor = node.parent;
1208            }
1209            if matches!(
1210                command,
1211                crate::NavigationPanelCommand::Close | crate::NavigationPanelCommand::Open
1212            ) && !inside
1213                || matches!(
1214                    command,
1215                    crate::NavigationPanelCommand::First | crate::NavigationPanelCommand::Last
1216                ) && inside
1217            {
1218                return Err(Error::InvalidEvent(
1219                    "navigation panel command disagrees with its mounted content level",
1220                ));
1221            }
1222        }
1223        if matches!(
1224            event,
1225            Event::Navigate { .. }
1226                | Event::Keyboard { .. }
1227                | Event::Palette { .. }
1228                | Event::ScrollKeyboard { .. }
1229                | Event::Range { .. }
1230                | Event::Spin { .. }
1231                | Event::Typeahead { .. }
1232                | Event::Menu { .. }
1233                | Event::NavigationPanel { .. }
1234                | Event::Choice { .. }
1235                | Event::Tags { .. }
1236        ) {
1237            event.validate_payload(id, &target.descriptor)?;
1238            return Ok(interactive()
1239                && (!matches!(event, Event::Palette { .. }) || Self::active_in(nodes, id)));
1240        }
1241        if let Some(origin) = event.origin() {
1242            let source = match get(origin) {
1243                Ok(node) => node,
1244                Err(Error::NodeGone(_)) => return Ok(false),
1245                Err(error) => return Err(error),
1246            };
1247            if matches!(source.descriptor.view().props, Props::Group) {
1248                return Err(Error::InvalidEvent("event origin has no physical box"));
1249            }
1250            if matches!(event, Event::ContextMenu { .. }) {
1251                if !Self::active_in(nodes, origin) {
1252                    return Ok(false);
1253                }
1254                if target
1255                    .descriptor
1256                    .view()
1257                    .semantics
1258                    .as_ref()
1259                    .and_then(|s| s.context_menu)
1260                    == Some(crate::ContextEditPolicy::Native)
1261                    && matches!(
1262                        source.descriptor.view().props,
1263                        Props::Input(_) | Props::Select(_)
1264                    )
1265                {
1266                    return Ok(false);
1267                }
1268            }
1269            if matches!(event, Event::Anchor { .. }) && origin == id {
1270                return Err(Error::InvalidEvent("anchor must originate in a descendant"));
1271            }
1272            let mut cursor = Some(origin);
1273            while cursor != Some(id) {
1274                if matches!(event, Event::ContextMenu { .. })
1275                    && cursor.and_then(|id| nodes.get(&id)).is_some_and(|node| {
1276                        node.descriptor
1277                            .view()
1278                            .semantics
1279                            .as_ref()
1280                            .is_some_and(|s| s.context_menu.is_some())
1281                    })
1282                {
1283                    return Err(Error::InvalidEvent(
1284                        "context origin belongs to a nearer region",
1285                    ));
1286                }
1287                if matches!(event, Event::Submit { .. })
1288                    && cursor.and_then(|id| nodes.get(&id)).is_some_and(|node| {
1289                        node.descriptor.view().field_part() == Some(crate::FieldPart::Fieldset)
1290                            && node
1291                                .descriptor
1292                                .view()
1293                                .semantics
1294                                .as_ref()
1295                                .is_some_and(|s| s.disabled)
1296                    })
1297                {
1298                    return Ok(false);
1299                }
1300                cursor = cursor
1301                    .and_then(|id| nodes.get(&id))
1302                    .and_then(|node| node.parent);
1303                if cursor.is_none() {
1304                    return Err(Error::InvalidEvent("event origin is outside its target"));
1305                }
1306            }
1307            if !Self::active_in(nodes, origin) && !event.is_terminal_loss() {
1308                return Ok(false);
1309            }
1310        }
1311        event.validate_payload(id, &target.descriptor)?;
1312        Ok(interactive())
1313    }
1314
1315    pub fn push_event(&mut self, id: NodeId, event: Event) -> Result<(), Error> {
1316        let node = self.node(id)?;
1317        if matches!(event, Event::Activate) && !node.descriptor.view().activation_enabled() {
1318            return Err(Error::InvalidProps("activation is disabled"));
1319        }
1320        if !self.validate_event(id, &event)? {
1321            return Ok(());
1322        }
1323        if !self.active(id) && !event.is_terminal_loss() {
1324            return Err(Error::InvalidPlacement("event target is not active"));
1325        }
1326        if matches!(
1327            event,
1328            Event::Activate
1329                | Event::Submit { .. }
1330                | Event::Reset
1331                | Event::Keyboard { .. }
1332                | Event::Palette { .. }
1333                | Event::ScrollKeyboard { .. }
1334                | Event::Range { .. }
1335                | Event::Spin { .. }
1336                | Event::Typeahead { .. }
1337                | Event::Menu { .. }
1338                | Event::NavigationPanel { .. }
1339                | Event::Choice { .. }
1340                | Event::Tags { .. }
1341                | Event::ContextMenu { .. }
1342                | Event::Drag {
1343                    phase: crate::DragPhase::Start
1344                        | crate::DragPhase::Move
1345                        | crate::DragPhase::Drop,
1346                    ..
1347                }
1348                | Event::CheckedChanged(_)
1349                | Event::SelectChanged { .. }
1350                | Event::ValueChanged { .. }
1351                | Event::Commit { .. }
1352        ) && !self.enabled(id)
1353        {
1354            return Err(Error::InvalidProps(
1355                "disabled control cannot receive user edits or activation",
1356            ));
1357        }
1358        self.inputs.push(Input::Event { node: id, event });
1359        Ok(())
1360    }
1361
1362    fn check_runtime(&self, id: NodeId) -> Result<(), Error> {
1363        if id.runtime() == self.runtime {
1364            Ok(())
1365        } else {
1366            Err(Error::ForeignRuntime)
1367        }
1368    }
1369
1370    fn unlink(&mut self, id: NodeId) {
1371        let node = &self.nodes[&id];
1372        if !node.placed {
1373            return;
1374        }
1375        let next = node.next;
1376        let siblings = if let Some(parent) = node.parent {
1377            &mut self
1378                .nodes
1379                .get_mut(&parent)
1380                .expect("validated parent")
1381                .children
1382        } else {
1383            &mut self.roots
1384        };
1385        let index = if siblings.first() == Some(&id) {
1386            0
1387        } else if siblings.last() == Some(&id) {
1388            siblings.len() - 1
1389        } else {
1390            siblings
1391                .iter()
1392                .position(|child| *child == id)
1393                .expect("placed sibling")
1394        };
1395        let previous = index.checked_sub(1).map(|index| siblings[index]);
1396        siblings.remove(index);
1397        if let Some(previous) = previous {
1398            self.nodes
1399                .get_mut(&previous)
1400                .expect("previous sibling")
1401                .next = next;
1402        }
1403    }
1404
1405    /// Next logical sibling of a placed node, including suspended siblings.
1406    /// Identity validation precedes the constant-time adjacency lookup.
1407    pub fn next_sibling(&self, id: NodeId) -> Result<Option<NodeId>, Error> {
1408        let node = self.node(id)?;
1409        Ok(node.placed.then_some(node.next).flatten())
1410    }
1411
1412    /// Check a proposed parent/child relation without allocating identities or
1413    /// modifying state. Ordinary moves visit ancestors only; only restricted
1414    /// interactive/button contexts require examining the child's live subtree.
1415    pub fn validate_child(&self, child: Subtree<'_>, parent: Option<NodeId>) -> Result<(), Error> {
1416        self.validate_child_inner(child, parent, true)
1417    }
1418
1419    fn validate_child_inner(
1420        &self,
1421        child: Subtree<'_>,
1422        parent: Option<NodeId>,
1423        choice: bool,
1424    ) -> Result<(), Error> {
1425        let descriptor = match child {
1426            Subtree::New(d) => d,
1427            Subtree::Plan(plan) => plan.nodes()[0].descriptor.view(),
1428            Subtree::Existing(id) => self.node(id)?.descriptor.view(),
1429        };
1430        if let Some(parent) = parent
1431            && self.node(parent)?.descriptor.view().role == Some(Role::Separator)
1432        {
1433            return Err(Error::InvalidProps(
1434                "passive separators cannot contain children",
1435            ));
1436        }
1437        self.validate_document_placement(child, parent)?;
1438        if choice {
1439            self.validate_choice_child(child, parent)?;
1440        }
1441        if descriptor.field_part() == Some(crate::FieldPart::Legend)
1442            && parent.and_then(|id| self.node(id).ok()).is_none_or(|node| {
1443                node.descriptor.view().field_part() != Some(crate::FieldPart::Fieldset)
1444            })
1445        {
1446            return Err(Error::InvalidPlacement(
1447                "legend requires a direct fieldset parent",
1448            ));
1449        }
1450        if let Subtree::Existing(id) = child {
1451            self.node(id)?;
1452        }
1453        let mut cursor = parent;
1454        let mut interactive_ancestor = false;
1455        let mut button_ancestor = false;
1456        let mut form_ancestor = false;
1457        let mut tooltip_ancestor = false;
1458        while let Some(ancestor) = cursor {
1459            if matches!(child, Subtree::Existing(id) if ancestor == id) {
1460                return Err(Error::InvalidPlacement("tree cycle"));
1461            }
1462            let node = self.node(ancestor)?;
1463            if cursor == parent && !node.descriptor.view().props.accepts_children() {
1464                return Err(Error::InvalidProps("leaf widget cannot contain children"));
1465            }
1466            interactive_ancestor |= node.descriptor.view().props.interactive()
1467                || matches!(
1468                    node.descriptor.view().field_part(),
1469                    Some(crate::FieldPart::Label | crate::FieldPart::Legend)
1470                );
1471            button_ancestor |= matches!(
1472                node.descriptor.view().props,
1473                Props::Button(_) | Props::File(_)
1474            );
1475            form_ancestor |= node.descriptor.view().field_part() == Some(crate::FieldPart::Form);
1476            tooltip_ancestor |= matches!(
1477                node.descriptor.view().role,
1478                Some(Role::Tooltip | Role::ProgressBar | Role::Slider)
1479            );
1480            cursor = node.parent;
1481        }
1482        // Most placements (including ordinary list moves) need no subtree scan.
1483        self.validate_focus_child(child, parent)?;
1484        if let Subtree::New(descriptor) = child {
1485            self.validate_name(descriptor, None)?;
1486        }
1487        if let Subtree::Plan(plan) = child {
1488            for &index in plan.semantic_nodes() {
1489                self.validate_name(&plan.nodes()[index].descriptor, None)?;
1490            }
1491        }
1492        match child {
1493            Subtree::New(descriptor) => self.admit_layers(usize::from(layer(descriptor)))?,
1494            Subtree::Plan(plan) => self.admit_layers(plan.layers())?,
1495            Subtree::Existing(_) => {}
1496        }
1497        if form_ancestor && descriptor.field_part() == Some(crate::FieldPart::Form) {
1498            return Err(Error::InvalidPlacement("forms cannot be nested"));
1499        }
1500        // A same-parent property update/reorder cannot introduce a new nested
1501        // form. Only a changed ancestor context needs the moved live subtree.
1502        let form_scan = form_ancestor
1503            && match child {
1504                Subtree::Existing(id) => self.node(id)?.parent != parent,
1505                _ => true,
1506            };
1507        if !interactive_ancestor && !button_ancestor && !form_scan && !tooltip_ancestor {
1508            return Ok(());
1509        }
1510        let check = |descriptor: DescriptorView<'_>| {
1511            if form_scan && descriptor.field_part() == Some(crate::FieldPart::Form) {
1512                return Err(Error::InvalidPlacement("forms cannot be nested"));
1513            }
1514            crate::plan::validate_context(
1515                descriptor,
1516                interactive_ancestor,
1517                button_ancestor,
1518                tooltip_ancestor,
1519            )
1520        };
1521        match child {
1522            Subtree::New(descriptor) => check(descriptor)?,
1523            Subtree::Plan(plan) => {
1524                for node in plan.nodes() {
1525                    check(node.descriptor.view())?;
1526                }
1527            }
1528            Subtree::Existing(id) => {
1529                let mut pending = vec![id];
1530                while let Some(id) = pending.pop() {
1531                    let node = self.node(id)?;
1532                    check(node.descriptor.view())?;
1533                    pending.extend(node.children.iter().copied());
1534                }
1535            }
1536        }
1537        Ok(())
1538    }
1539
1540    fn validate_document_placement(
1541        &self,
1542        child: Subtree<'_>,
1543        parent: Option<NodeId>,
1544    ) -> Result<(), Error> {
1545        let mut boxed_parent = parent;
1546        while let Some(id) = boxed_parent {
1547            let node = self.node(id)?;
1548            if !matches!(node.descriptor.view().props, Props::Group) {
1549                break;
1550            }
1551            boxed_parent = node.parent;
1552        }
1553        let parent = boxed_parent
1554            .map(|id| self.node(id).map(|node| node.descriptor.view()))
1555            .transpose()?;
1556        let check = |descriptor: DescriptorView<'_>| {
1557            crate::document::validate_child(descriptor, parent, false)
1558        };
1559        match child {
1560            Subtree::New(descriptor) => check(descriptor)?,
1561            Subtree::Existing(id) => {
1562                // Only transparent ranges change the physical parent of their
1563                // contents. Stop at boxed nodes; never scan business sources.
1564                let node = self.node(id)?;
1565                check(node.descriptor.view())?;
1566                if matches!(node.descriptor.view().props, Props::Group) {
1567                    let mut pending = node.children.iter().copied().collect::<Vec<_>>();
1568                    while let Some(id) = pending.pop() {
1569                        let node = self.node(id)?;
1570                        check(node.descriptor.view())?;
1571                        if matches!(node.descriptor.view().props, Props::Group) {
1572                            pending.extend(node.children.iter().copied());
1573                        }
1574                    }
1575                }
1576            }
1577            Subtree::Plan(plan) => {
1578                for &index in plan.document_roots() {
1579                    check(plan.nodes()[index].descriptor.view())?;
1580                }
1581            }
1582        }
1583        Ok(())
1584    }
1585
1586    /// Read-only validation shared by App staging and direct reference apply.
1587    pub fn validate_placement(
1588        &self,
1589        id: NodeId,
1590        parent: Option<NodeId>,
1591        before: Option<NodeId>,
1592        resume: bool,
1593    ) -> Result<(), Error> {
1594        let node = self.node(id)?;
1595        if resume != node.suspended {
1596            return Err(Error::InvalidPlacement(
1597                "use Resume for suspended nodes and Place otherwise",
1598            ));
1599        }
1600        self.validate_child(Subtree::Existing(id), parent)?;
1601        if let Some(before) = before {
1602            let sibling = self.node(before)?;
1603            if before == id || !sibling.placed || sibling.parent != parent {
1604                return Err(Error::InvalidPlacement(
1605                    "before must be a different child of the target parent",
1606                ));
1607            }
1608        }
1609        Ok(())
1610    }
1611
1612    fn place(
1613        &mut self,
1614        id: NodeId,
1615        parent: Option<NodeId>,
1616        before: Option<NodeId>,
1617        resume: bool,
1618    ) -> Result<(), Error> {
1619        self.validate_placement(id, parent, before, resume)?;
1620        let focus_movement = self.scope_movement(id, parent)?;
1621        self.unlink(id);
1622        let siblings = if let Some(parent) = parent {
1623            &mut self
1624                .nodes
1625                .get_mut(&parent)
1626                .expect("validated parent")
1627                .children
1628        } else {
1629            &mut self.roots
1630        };
1631        let index = before
1632            .map(|before| {
1633                if siblings.first() == Some(&before) {
1634                    return 0;
1635                }
1636                siblings
1637                    .iter()
1638                    .position(|child| *child == before)
1639                    .expect("validated sibling")
1640            })
1641            .unwrap_or(siblings.len());
1642        let previous = index.checked_sub(1).map(|index| siblings[index]);
1643        siblings.insert(index, id);
1644        if let Some(previous) = previous {
1645            self.nodes
1646                .get_mut(&previous)
1647                .expect("previous sibling")
1648                .next = Some(id);
1649        }
1650        let node = self.nodes.get_mut(&id).expect("validated node");
1651        node.next = before;
1652        node.parent = parent;
1653        node.placed = true;
1654        node.suspended = false;
1655        if let Some(movement) = focus_movement {
1656            movement.commit(self);
1657        }
1658        self.stats.placed += 1;
1659        Ok(())
1660    }
1661
1662    fn apply_one(&mut self, mutation: &Mutation) -> Result<(), Error> {
1663        match mutation {
1664            Mutation::CreatePlan { plan, ids } => {
1665                if ids.len() != plan.nodes().len() {
1666                    return Err(Error::InvalidProps("plan identity count"));
1667                }
1668                // Strict slot order proves uniqueness for the whole batch.
1669                // Fresh/recycled runs need no temporary hash allocation. An
1670                // arbitrary caller still gets the original per-slot checks.
1671                let ordered = ids.windows(2).all(|pair| pair[0].slot() < pair[1].slot())
1672                    || ids.windows(2).all(|pair| pair[0].slot() > pair[1].slot());
1673                let mut slots =
1674                    (!ordered).then(|| std::collections::HashSet::with_capacity(ids.len()));
1675                for (index, (id, node)) in ids.iter().zip(plan.nodes()).enumerate() {
1676                    self.check_runtime(*id)?;
1677                    if slots.as_mut().is_some_and(|slots| !slots.insert(id.slot())) {
1678                        return Err(Error::InvalidPlacement("duplicate plan slot"));
1679                    }
1680                    if self.nodes.contains_key(id) {
1681                        return Err(Error::DuplicateNode(*id));
1682                    }
1683                    if let Some((generation, live)) = self.generations.get(&id.slot()) {
1684                        if *live {
1685                            return Err(Error::InvalidPlacement("slot is still occupied"));
1686                        }
1687                        if *generation >= id.generation() {
1688                            return Err(Error::StaleNode(*id));
1689                        }
1690                    }
1691                    if plan.facts(index).live_names {
1692                        self.validate_name(&node.descriptor, None)?;
1693                    }
1694                }
1695                self.admit_layers(plan.layers())?;
1696                self.admit_focus_scopes(plan.focus_scopes())?;
1697                for (index, node) in plan.nodes().iter().enumerate() {
1698                    // The immutable declaration checked content/topology once;
1699                    // the complete identity/name check above precedes mutation.
1700                    // Fresh nodes need no unlink, ancestor walk or temporary Box.
1701                    let id = ids[index];
1702                    let descriptor = LiveDescriptor::plan(plan, index);
1703                    let facts = plan.facts(index);
1704                    self.layers += usize::from(facts.layer);
1705                    if facts.focus_nodes != 0 {
1706                        self.focus_scopes.insert(id, usize::from(facts.focus_nodes));
1707                    }
1708                    if let Some(name) = descriptor.view().semantic_id() {
1709                        self.names.insert(name.clone(), id);
1710                    }
1711                    self.generations.insert(id.slot(), (id.generation(), true));
1712                    let swipe = descriptor
1713                        .view()
1714                        .semantics
1715                        .as_ref()
1716                        .and_then(|s| s.swipe_capture)
1717                        .map(crate::swipe::State::new);
1718                    self.nodes.insert(
1719                        id,
1720                        Node {
1721                            descriptor,
1722                            parent: node.parent.map(|parent| ids[parent]),
1723                            children: Children::default(),
1724                            placed: node.parent.is_some(),
1725                            suspended: false,
1726                            next: None,
1727                            clipboard: None,
1728                            files: None,
1729                            swipe,
1730                        },
1731                    );
1732                    self.stats.created += 1;
1733                    if let Some(parent) = node.parent {
1734                        let siblings = &mut self
1735                            .nodes
1736                            .get_mut(&ids[parent])
1737                            .expect("plan parent")
1738                            .children;
1739                        let previous = siblings.last().copied();
1740                        siblings.insert(siblings.len(), id);
1741                        if let Some(previous) = previous {
1742                            self.nodes.get_mut(&previous).expect("plan sibling").next = Some(id);
1743                        }
1744                        self.stats.placed += 1;
1745                    }
1746                }
1747            }
1748            Mutation::Create { id, node } => {
1749                self.check_runtime(*id)?;
1750                node.validate()?;
1751                if self.nodes.contains_key(id) {
1752                    return Err(Error::DuplicateNode(*id));
1753                }
1754                if let Some((generation, live)) = self.generations.get(&id.slot()) {
1755                    if *live {
1756                        return Err(Error::InvalidPlacement("slot is still occupied"));
1757                    }
1758                    if *generation >= id.generation() {
1759                        return Err(Error::StaleNode(*id));
1760                    }
1761                }
1762                let mut descriptor = node.as_ref().clone();
1763                self.validate_name(node.as_ref(), None)?;
1764                self.admit_layers(usize::from(layer(node.view())))?;
1765                self.admit_focus_scopes(usize::from(crate::focus_scope::declared(node.view())))?;
1766                descriptor.normalize_input()?;
1767                self.layers += usize::from(layer(descriptor.view()));
1768                if crate::focus_scope::declared(descriptor.view()) {
1769                    self.focus_scopes.insert(*id, 1);
1770                }
1771                if let Some(name) = descriptor.view().semantic_id() {
1772                    self.names.insert(name.clone(), *id);
1773                }
1774                self.generations.insert(id.slot(), (id.generation(), true));
1775                let swipe = descriptor
1776                    .view()
1777                    .semantics
1778                    .as_ref()
1779                    .and_then(|s| s.swipe_capture)
1780                    .map(crate::swipe::State::new);
1781                self.nodes.insert(
1782                    *id,
1783                    Node {
1784                        descriptor: LiveDescriptor::owned(descriptor),
1785                        parent: None,
1786                        children: Children::default(),
1787                        placed: false,
1788                        suspended: false,
1789                        next: None,
1790                        clipboard: None,
1791                        files: None,
1792                        swipe,
1793                    },
1794                );
1795                self.stats.created += 1;
1796            }
1797            Mutation::Patch { id, patch } => {
1798                self.prepare_patch(*id, patch)?.accept();
1799            }
1800            Mutation::Place { id, parent, before } => self.place(*id, *parent, *before, false)?,
1801            Mutation::Resume { id, parent, before } => self.place(*id, *parent, *before, true)?,
1802            Mutation::Suspend { id } => {
1803                let node = self.node(*id)?;
1804                if !node.placed || node.suspended {
1805                    return Err(Error::InvalidPlacement(
1806                        "only placed active ranges can be suspended",
1807                    ));
1808                }
1809                self.nodes.get_mut(id).expect("validated node").suspended = true;
1810                self.prune_events();
1811                self.stats.suspended += 1;
1812            }
1813            Mutation::Dispose { id } => self.retire(*id, None)?,
1814        }
1815        Ok(())
1816    }
1817
1818    /// Apply one Dispose and return its retired identities in traversal order.
1819    /// Adapters use the removal itself to reclaim their identity-indexed state,
1820    /// instead of first walking the same subtree to build a second inventory.
1821    /// Includes detached/suspended descendants; rejection preserves the receipt.
1822    pub fn dispose(&mut self, id: NodeId) -> Result<(Receipt, Vec<NodeId>), Error> {
1823        let mut retired = Vec::new();
1824        self.retire(id, Some(&mut retired))?;
1825        self.receipt.applied += 1;
1826        Ok((self.receipt, retired))
1827    }
1828
1829    fn retire(&mut self, id: NodeId, mut retired: Option<&mut Vec<NodeId>>) -> Result<(), Error> {
1830        let parent = self.node(id)?.parent;
1831        let focus_ancestors = self.scope_ancestors(parent)?;
1832        self.unlink(id);
1833        let mut pending = vec![id];
1834        let mut focus_removed = 0usize;
1835        while let Some(id) = pending.pop() {
1836            let node = self.nodes.remove(&id).expect("owned subtree");
1837            self.focus_scopes.remove(&id);
1838            focus_removed += 1;
1839            self.layers -= usize::from(layer(node.descriptor.view()));
1840            if let Some(name) = node.descriptor.view().semantic_id() {
1841                self.names.remove(name);
1842            }
1843            self.generations
1844                .get_mut(&id.slot())
1845                .expect("known identity")
1846                .1 = false;
1847            pending.extend(node.children);
1848            self.stats.disposed += 1;
1849            if let Some(retired) = &mut retired {
1850                retired.push(id);
1851            }
1852        }
1853        for root in focus_ancestors {
1854            *self
1855                .focus_scopes
1856                .get_mut(&root)
1857                .expect("surviving scope ancestor") -= focus_removed;
1858        }
1859        // Pending native/browser events carry identities too. Do not deliver
1860        // an event whose target was destroyed by this operation.
1861        self.prune_events();
1862        Ok(())
1863    }
1864}
1865
1866impl Render for Memory {
1867    fn listen(&mut self, node: NodeId, kind: EventKind, enabled: bool) -> Result<(), Error> {
1868        let descriptor = self.node(node)?.descriptor.view();
1869        if enabled {
1870            kind.validate_target(descriptor)?;
1871        }
1872        Ok(())
1873    }
1874    fn action(&mut self, action: Action) -> Result<(), Error> {
1875        action.validate_target(&self.node(action.node())?.descriptor)?;
1876        self.validate_clipboard_action(action)?;
1877        Err(Error::Unsupported(
1878            "headless reference interpreter has no physical actions",
1879        ))
1880    }
1881    fn needs_observe(&self) -> bool {
1882        !self.inputs.is_empty()
1883    }
1884    fn style_profile(&self) -> style::Profile {
1885        style::Profile::RECORD
1886    }
1887    fn capabilities(&self) -> Capabilities {
1888        Capabilities::default()
1889    }
1890
1891    fn apply(&mut self, mutations: &[Mutation]) -> Result<Receipt, Error> {
1892        for mutation in mutations {
1893            self.apply_one(mutation)?;
1894            self.receipt.applied += 1;
1895        }
1896        Ok(self.receipt)
1897    }
1898
1899    fn request(&mut self, query: Query, token: QueryToken) -> Result<(), Error> {
1900        let result = query
1901            .validate_target(&self.node(query.node())?.descriptor)
1902            .and(Err(Error::Unsupported(
1903                "headless reference interpreter has no platform geometry, selection or focus",
1904            )));
1905        self.inputs.push(Input::Response {
1906            token,
1907            applied: self.receipt.applied,
1908            result,
1909        });
1910        Ok(())
1911    }
1912
1913    fn drain(&mut self, inputs: &mut Vec<Input>) {
1914        self.prune_events();
1915        inputs.append(&mut self.inputs);
1916    }
1917}