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