1use std::collections::HashMap;
6
7use crate::*;
8
9mod children;
10pub use children::Children;
11mod submission;
12pub use submission::Submission;
13
14pub 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 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#[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#[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 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 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 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 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 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 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 pub fn named(&self, name: &SemanticId) -> Option<NodeId> {
488 self.names.get(name).copied()
489 }
490
491 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 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 pub fn receipt(&self) -> Receipt {
557 self.receipt
558 }
559
560 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 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 pub fn active(&self, id: NodeId) -> bool {
688 Self::active_in(&self.nodes, id)
689 }
690 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 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 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 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::PlotPointer { .. } = event {
1141 event.validate_payload(id, &target.descriptor)?;
1142 return Ok((event.is_terminal_loss()
1143 || (Self::active_in(nodes, id) && Self::enabled_in(nodes, id)))
1144 && interactive());
1145 }
1146 if let Event::Pointer { related, .. } | Event::PointerWithin { related, .. } = event {
1147 event.validate_payload(id, &target.descriptor)?;
1148 if let Some(related) = related {
1149 let source = match get(*related) {
1150 Ok(node) => node,
1151 Err(Error::NodeGone(_)) => return Ok(false),
1152 Err(error) => return Err(error),
1153 };
1154 if matches!(source.descriptor.view().props, Props::Group) {
1155 return Err(Error::InvalidEvent(
1156 "pointer related origin has no physical box",
1157 ));
1158 }
1159 if !Self::active_in(nodes, *related) {
1160 return Ok(false);
1161 }
1162 let mut cursor = Some(*related);
1163 while let Some(current) = cursor {
1164 if current == id {
1165 return Ok(false);
1166 }
1167 cursor = nodes.get(¤t).and_then(|node| node.parent);
1168 }
1169 }
1170 if matches!(event, Event::Pointer { .. }) {
1171 return Ok(
1172 (Self::active_in(nodes, id) || event.is_terminal_loss()) && interactive()
1173 );
1174 }
1175 }
1176 if let Event::Submit {
1177 submitter: Some(submitter),
1178 } = event
1179 {
1180 event.validate_payload(id, &target.descriptor)?;
1181 let source = match get(*submitter) {
1182 Ok(source) => source,
1183 Err(Error::NodeGone(_)) => return Ok(false),
1184 Err(error) => return Err(error),
1185 };
1186 if source
1187 .descriptor
1188 .view()
1189 .semantics
1190 .as_ref()
1191 .and_then(|s| s.form_action)
1192 != Some(crate::FormAction::Submit)
1193 {
1194 return Err(Error::InvalidEvent(
1195 "submit origin requires a submit button",
1196 ));
1197 }
1198 if !source.descriptor.view().activation_enabled() || !Self::active_in(nodes, *submitter)
1199 {
1200 return Ok(false);
1201 }
1202 }
1203 if target.descriptor.view().readonly()
1204 && matches!(
1205 event,
1206 Event::ValueChanged { .. }
1207 | Event::InputEdit(_)
1208 | Event::Commit { .. }
1209 | Event::CheckedChanged(_)
1210 | Event::SelectChanged { .. }
1211 | Event::Range { .. }
1212 | Event::Spin { .. }
1213 | Event::Drag {
1214 phase: crate::DragPhase::Start
1215 | crate::DragPhase::Move
1216 | crate::DragPhase::Drop,
1217 ..
1218 }
1219 )
1220 {
1221 event.validate_payload(id, &target.descriptor)?;
1222 return Ok(false);
1223 }
1224 if let Event::Drag { from, phase, .. } = event {
1225 event.validate_payload(id, &target.descriptor)?;
1226 let source = match get(*from) {
1227 Ok(source) => source,
1228 Err(Error::NodeGone(_)) => return Ok(false),
1229 Err(error) => return Err(error),
1230 };
1231 EventKind::Drag.validate_target(&source.descriptor)?;
1232 return Ok(
1233 (Self::active_in(nodes, *from) || *phase == crate::DragPhase::Cancel)
1234 && interactive(),
1235 );
1236 }
1237 if let Event::NavigationPanel { command, .. } = event {
1240 let mut cursor = Some(id);
1241 let mut inside = false;
1242 while let Some(current) = cursor {
1243 let node = get(current)?;
1244 if node
1245 .descriptor
1246 .view()
1247 .semantics
1248 .as_ref()
1249 .and_then(|s| s.navigation_panel)
1250 == Some(crate::NavigationPanel::Content)
1251 {
1252 inside = true;
1253 break;
1254 }
1255 cursor = node.parent;
1256 }
1257 if matches!(
1258 command,
1259 crate::NavigationPanelCommand::Close | crate::NavigationPanelCommand::Open
1260 ) && !inside
1261 || matches!(
1262 command,
1263 crate::NavigationPanelCommand::First | crate::NavigationPanelCommand::Last
1264 ) && inside
1265 {
1266 return Err(Error::InvalidEvent(
1267 "navigation panel command disagrees with its mounted content level",
1268 ));
1269 }
1270 }
1271 if matches!(
1272 event,
1273 Event::Navigate { .. }
1274 | Event::Keyboard { .. }
1275 | Event::Palette { .. }
1276 | Event::ScrollKeyboard { .. }
1277 | Event::Range { .. }
1278 | Event::Spin { .. }
1279 | Event::Typeahead { .. }
1280 | Event::Menu { .. }
1281 | Event::NavigationPanel { .. }
1282 | Event::Choice { .. }
1283 | Event::Tags { .. }
1284 ) {
1285 event.validate_payload(id, &target.descriptor)?;
1286 return Ok(interactive()
1287 && (!matches!(event, Event::Palette { .. }) || Self::active_in(nodes, id)));
1288 }
1289 if let Some(origin) = event.origin() {
1290 let source = match get(origin) {
1291 Ok(node) => node,
1292 Err(Error::NodeGone(_)) => return Ok(false),
1293 Err(error) => return Err(error),
1294 };
1295 if matches!(source.descriptor.view().props, Props::Group) {
1296 return Err(Error::InvalidEvent("event origin has no physical box"));
1297 }
1298 if matches!(event, Event::ContextMenu { .. }) {
1299 if !Self::active_in(nodes, origin) {
1300 return Ok(false);
1301 }
1302 if target
1303 .descriptor
1304 .view()
1305 .semantics
1306 .as_ref()
1307 .and_then(|s| s.context_menu)
1308 == Some(crate::ContextEditPolicy::Native)
1309 && matches!(
1310 source.descriptor.view().props,
1311 Props::Input(_) | Props::Select(_)
1312 )
1313 {
1314 return Ok(false);
1315 }
1316 }
1317 if matches!(event, Event::Anchor { .. }) && origin == id {
1318 return Err(Error::InvalidEvent("anchor must originate in a descendant"));
1319 }
1320 let mut cursor = Some(origin);
1321 while cursor != Some(id) {
1322 if matches!(event, Event::ContextMenu { .. })
1323 && cursor.and_then(|id| nodes.get(&id)).is_some_and(|node| {
1324 node.descriptor
1325 .view()
1326 .semantics
1327 .as_ref()
1328 .is_some_and(|s| s.context_menu.is_some())
1329 })
1330 {
1331 return Err(Error::InvalidEvent(
1332 "context origin belongs to a nearer region",
1333 ));
1334 }
1335 if matches!(event, Event::Submit { .. })
1336 && cursor.and_then(|id| nodes.get(&id)).is_some_and(|node| {
1337 node.descriptor.view().field_part() == Some(crate::FieldPart::Fieldset)
1338 && node
1339 .descriptor
1340 .view()
1341 .semantics
1342 .as_ref()
1343 .is_some_and(|s| s.disabled)
1344 })
1345 {
1346 return Ok(false);
1347 }
1348 cursor = cursor
1349 .and_then(|id| nodes.get(&id))
1350 .and_then(|node| node.parent);
1351 if cursor.is_none() {
1352 return Err(Error::InvalidEvent("event origin is outside its target"));
1353 }
1354 }
1355 if !Self::active_in(nodes, origin) && !event.is_terminal_loss() {
1356 return Ok(false);
1357 }
1358 }
1359 event.validate_payload(id, &target.descriptor)?;
1360 Ok(interactive())
1361 }
1362
1363 pub fn push_event(&mut self, id: NodeId, event: Event) -> Result<(), Error> {
1364 let node = self.node(id)?;
1365 if matches!(event, Event::Activate) && !node.descriptor.view().activation_enabled() {
1366 return Err(Error::InvalidProps("activation is disabled"));
1367 }
1368 if !self.validate_event(id, &event)? {
1369 return Ok(());
1370 }
1371 if !self.active(id) && !event.is_terminal_loss() {
1372 return Err(Error::InvalidPlacement("event target is not active"));
1373 }
1374 if matches!(
1375 event,
1376 Event::Activate
1377 | Event::Submit { .. }
1378 | Event::Reset
1379 | Event::Keyboard { .. }
1380 | Event::Palette { .. }
1381 | Event::ScrollKeyboard { .. }
1382 | Event::Range { .. }
1383 | Event::Spin { .. }
1384 | Event::Typeahead { .. }
1385 | Event::Menu { .. }
1386 | Event::NavigationPanel { .. }
1387 | Event::Choice { .. }
1388 | Event::Tags { .. }
1389 | Event::ContextMenu { .. }
1390 | Event::Drag {
1391 phase: crate::DragPhase::Start
1392 | crate::DragPhase::Move
1393 | crate::DragPhase::Drop,
1394 ..
1395 }
1396 | Event::CheckedChanged(_)
1397 | Event::SelectChanged { .. }
1398 | Event::ValueChanged { .. }
1399 | Event::Commit { .. }
1400 ) && !self.enabled(id)
1401 {
1402 return Err(Error::InvalidProps(
1403 "disabled control cannot receive user edits or activation",
1404 ));
1405 }
1406 self.inputs.push(Input::Event { node: id, event });
1407 Ok(())
1408 }
1409
1410 fn check_runtime(&self, id: NodeId) -> Result<(), Error> {
1411 if id.runtime() == self.runtime {
1412 Ok(())
1413 } else {
1414 Err(Error::ForeignRuntime)
1415 }
1416 }
1417
1418 fn unlink(&mut self, id: NodeId) {
1419 let node = &self.nodes[&id];
1420 if !node.placed {
1421 return;
1422 }
1423 let next = node.next;
1424 let siblings = if let Some(parent) = node.parent {
1425 &mut self
1426 .nodes
1427 .get_mut(&parent)
1428 .expect("validated parent")
1429 .children
1430 } else {
1431 &mut self.roots
1432 };
1433 let previous = siblings.remove_id(id);
1434 if let Some(previous) = previous {
1435 self.nodes
1436 .get_mut(&previous)
1437 .expect("previous sibling")
1438 .next = next;
1439 }
1440 }
1441
1442 pub fn next_sibling(&self, id: NodeId) -> Result<Option<NodeId>, Error> {
1445 let node = self.node(id)?;
1446 Ok(node.placed.then_some(node.next).flatten())
1447 }
1448
1449 pub fn validate_child(&self, child: Subtree<'_>, parent: Option<NodeId>) -> Result<(), Error> {
1453 self.validate_child_inner(child, parent, true)
1454 }
1455
1456 fn validate_child_inner(
1457 &self,
1458 child: Subtree<'_>,
1459 parent: Option<NodeId>,
1460 choice: bool,
1461 ) -> Result<(), Error> {
1462 let descriptor = match child {
1463 Subtree::New(d) => d,
1464 Subtree::Plan(plan) => plan.nodes()[0].descriptor.view(),
1465 Subtree::Existing(id) => self.node(id)?.descriptor.view(),
1466 };
1467 if let Some(parent) = parent
1468 && self.node(parent)?.descriptor.view().role == Some(Role::Separator)
1469 {
1470 return Err(Error::InvalidProps(
1471 "passive separators cannot contain children",
1472 ));
1473 }
1474 self.validate_document_placement(child, parent)?;
1475 if choice {
1476 self.validate_choice_child(child, parent)?;
1477 }
1478 if descriptor.field_part() == Some(crate::FieldPart::Legend)
1479 && parent.and_then(|id| self.node(id).ok()).is_none_or(|node| {
1480 node.descriptor.view().field_part() != Some(crate::FieldPart::Fieldset)
1481 })
1482 {
1483 return Err(Error::InvalidPlacement(
1484 "legend requires a direct fieldset parent",
1485 ));
1486 }
1487 if let Subtree::Existing(id) = child {
1488 self.node(id)?;
1489 }
1490 let mut cursor = parent;
1491 let mut interactive_ancestor = false;
1492 let mut button_ancestor = false;
1493 let mut form_ancestor = false;
1494 let mut tooltip_ancestor = false;
1495 while let Some(ancestor) = cursor {
1496 if matches!(child, Subtree::Existing(id) if ancestor == id) {
1497 return Err(Error::InvalidPlacement("tree cycle"));
1498 }
1499 let node = self.node(ancestor)?;
1500 if cursor == parent && !node.descriptor.view().props.accepts_children() {
1501 return Err(Error::InvalidProps("leaf widget cannot contain children"));
1502 }
1503 interactive_ancestor |= node.descriptor.view().props.interactive()
1504 || matches!(
1505 node.descriptor.view().field_part(),
1506 Some(crate::FieldPart::Label | crate::FieldPart::Legend)
1507 );
1508 button_ancestor |= matches!(
1509 node.descriptor.view().props,
1510 Props::Button(_) | Props::File(_)
1511 );
1512 form_ancestor |= node.descriptor.view().field_part() == Some(crate::FieldPart::Form);
1513 tooltip_ancestor |= matches!(
1514 node.descriptor.view().role,
1515 Some(Role::Tooltip | Role::ProgressBar | Role::Slider)
1516 );
1517 cursor = node.parent;
1518 }
1519 self.validate_focus_child(child, parent)?;
1521 if let Subtree::New(descriptor) = child {
1522 self.validate_name(descriptor, None)?;
1523 }
1524 if let Subtree::Plan(plan) = child {
1525 for &index in plan.semantic_nodes() {
1526 self.validate_name(&plan.nodes()[index].descriptor, None)?;
1527 }
1528 }
1529 match child {
1530 Subtree::New(descriptor) => self.admit_layers(usize::from(layer(descriptor)))?,
1531 Subtree::Plan(plan) => self.admit_layers(plan.layers())?,
1532 Subtree::Existing(_) => {}
1533 }
1534 if form_ancestor && descriptor.field_part() == Some(crate::FieldPart::Form) {
1535 return Err(Error::InvalidPlacement("forms cannot be nested"));
1536 }
1537 let form_scan = form_ancestor
1540 && match child {
1541 Subtree::Existing(id) => self.node(id)?.parent != parent,
1542 _ => true,
1543 };
1544 if !interactive_ancestor && !button_ancestor && !form_scan && !tooltip_ancestor {
1545 return Ok(());
1546 }
1547 let check = |descriptor: DescriptorView<'_>| {
1548 if form_scan && descriptor.field_part() == Some(crate::FieldPart::Form) {
1549 return Err(Error::InvalidPlacement("forms cannot be nested"));
1550 }
1551 crate::plan::validate_context(
1552 descriptor,
1553 interactive_ancestor,
1554 button_ancestor,
1555 tooltip_ancestor,
1556 )
1557 };
1558 match child {
1559 Subtree::New(descriptor) => check(descriptor)?,
1560 Subtree::Plan(plan) => {
1561 for node in plan.nodes() {
1562 check(node.descriptor.view())?;
1563 }
1564 }
1565 Subtree::Existing(id) => {
1566 let mut pending = vec![id];
1567 while let Some(id) = pending.pop() {
1568 let node = self.node(id)?;
1569 check(node.descriptor.view())?;
1570 pending.extend(node.children.iter().copied());
1571 }
1572 }
1573 }
1574 Ok(())
1575 }
1576
1577 fn validate_document_placement(
1578 &self,
1579 child: Subtree<'_>,
1580 parent: Option<NodeId>,
1581 ) -> Result<(), Error> {
1582 let mut boxed_parent = parent;
1583 while let Some(id) = boxed_parent {
1584 let node = self.node(id)?;
1585 if !matches!(node.descriptor.view().props, Props::Group) {
1586 break;
1587 }
1588 boxed_parent = node.parent;
1589 }
1590 let parent = boxed_parent
1591 .map(|id| self.node(id).map(|node| node.descriptor.view()))
1592 .transpose()?;
1593 let check = |descriptor: DescriptorView<'_>| {
1594 crate::document::validate_child(descriptor, parent, false)
1595 };
1596 match child {
1597 Subtree::New(descriptor) => check(descriptor)?,
1598 Subtree::Existing(id) => {
1599 let node = self.node(id)?;
1602 check(node.descriptor.view())?;
1603 if matches!(node.descriptor.view().props, Props::Group) {
1604 let mut pending = node.children.iter().copied().collect::<Vec<_>>();
1605 while let Some(id) = pending.pop() {
1606 let node = self.node(id)?;
1607 check(node.descriptor.view())?;
1608 if matches!(node.descriptor.view().props, Props::Group) {
1609 pending.extend(node.children.iter().copied());
1610 }
1611 }
1612 }
1613 }
1614 Subtree::Plan(plan) => {
1615 for &index in plan.document_roots() {
1616 check(plan.nodes()[index].descriptor.view())?;
1617 }
1618 }
1619 }
1620 Ok(())
1621 }
1622
1623 pub fn validate_placement(
1625 &self,
1626 id: NodeId,
1627 parent: Option<NodeId>,
1628 before: Option<NodeId>,
1629 resume: bool,
1630 ) -> Result<(), Error> {
1631 let node = self.node(id)?;
1632 if resume != node.suspended {
1633 return Err(Error::InvalidPlacement(
1634 "use Resume for suspended nodes and Place otherwise",
1635 ));
1636 }
1637 self.validate_child(Subtree::Existing(id), parent)?;
1638 if let Some(before) = before {
1639 let sibling = self.node(before)?;
1640 if before == id || !sibling.placed || sibling.parent != parent {
1641 return Err(Error::InvalidPlacement(
1642 "before must be a different child of the target parent",
1643 ));
1644 }
1645 }
1646 Ok(())
1647 }
1648
1649 fn place(
1650 &mut self,
1651 id: NodeId,
1652 parent: Option<NodeId>,
1653 before: Option<NodeId>,
1654 resume: bool,
1655 ) -> Result<(), Error> {
1656 self.validate_placement(id, parent, before, resume)?;
1657 let focus_movement = self.scope_movement(id, parent)?;
1658 self.unlink(id);
1659 let siblings = if let Some(parent) = parent {
1660 &mut self
1661 .nodes
1662 .get_mut(&parent)
1663 .expect("validated parent")
1664 .children
1665 } else {
1666 &mut self.roots
1667 };
1668 let previous = siblings.insert_before(id, before);
1669 if let Some(previous) = previous {
1670 self.nodes
1671 .get_mut(&previous)
1672 .expect("previous sibling")
1673 .next = Some(id);
1674 }
1675 let node = self.nodes.get_mut(&id).expect("validated node");
1676 node.next = before;
1677 node.parent = parent;
1678 node.placed = true;
1679 node.suspended = false;
1680 if let Some(movement) = focus_movement {
1681 movement.commit(self);
1682 }
1683 self.stats.placed += 1;
1684 Ok(())
1685 }
1686
1687 fn apply_one(&mut self, mutation: &Mutation) -> Result<(), Error> {
1688 match mutation {
1689 Mutation::CreatePlan { plan, ids } => {
1690 if ids.len() != plan.nodes().len() {
1691 return Err(Error::InvalidProps("plan identity count"));
1692 }
1693 let ordered = ids.windows(2).all(|pair| pair[0].slot() < pair[1].slot())
1697 || ids.windows(2).all(|pair| pair[0].slot() > pair[1].slot());
1698 let mut slots =
1699 (!ordered).then(|| std::collections::HashSet::with_capacity(ids.len()));
1700 for (index, (id, node)) in ids.iter().zip(plan.nodes()).enumerate() {
1701 self.check_runtime(*id)?;
1702 if slots.as_mut().is_some_and(|slots| !slots.insert(id.slot())) {
1703 return Err(Error::InvalidPlacement("duplicate plan slot"));
1704 }
1705 if self.nodes.contains_key(id) {
1706 return Err(Error::DuplicateNode(*id));
1707 }
1708 if let Some((generation, live)) = self.generations.get(&id.slot()) {
1709 if *live {
1710 return Err(Error::InvalidPlacement("slot is still occupied"));
1711 }
1712 if *generation >= id.generation() {
1713 return Err(Error::StaleNode(*id));
1714 }
1715 }
1716 if plan.facts(index).live_names {
1717 self.validate_name(&node.descriptor, None)?;
1718 }
1719 }
1720 self.admit_layers(plan.layers())?;
1721 self.admit_focus_scopes(plan.focus_scopes())?;
1722 for (index, node) in plan.nodes().iter().enumerate() {
1723 let id = ids[index];
1727 let descriptor = LiveDescriptor::plan(plan, index);
1728 let facts = plan.facts(index);
1729 self.layers += usize::from(facts.layer);
1730 if facts.focus_nodes != 0 {
1731 self.focus_scopes.insert(id, usize::from(facts.focus_nodes));
1732 }
1733 if let Some(name) = descriptor.view().semantic_id() {
1734 self.names.insert(name.clone(), id);
1735 }
1736 self.generations.insert(id.slot(), (id.generation(), true));
1737 let swipe = descriptor
1738 .view()
1739 .semantics
1740 .as_ref()
1741 .and_then(|s| s.swipe_capture)
1742 .map(crate::swipe::State::new);
1743 self.nodes.insert(
1744 id,
1745 Node {
1746 descriptor,
1747 parent: node.parent.map(|parent| ids[parent]),
1748 children: Children::default(),
1749 placed: node.parent.is_some(),
1750 suspended: false,
1751 next: None,
1752 clipboard: None,
1753 files: None,
1754 swipe,
1755 },
1756 );
1757 self.stats.created += 1;
1758 if let Some(parent) = node.parent {
1759 let siblings = &mut self
1760 .nodes
1761 .get_mut(&ids[parent])
1762 .expect("plan parent")
1763 .children;
1764 let previous = siblings.last().copied();
1765 siblings.insert_before(id, None);
1766 if let Some(previous) = previous {
1767 self.nodes.get_mut(&previous).expect("plan sibling").next = Some(id);
1768 }
1769 self.stats.placed += 1;
1770 }
1771 }
1772 }
1773 Mutation::Create { id, node } => {
1774 self.check_runtime(*id)?;
1775 node.validate()?;
1776 if self.nodes.contains_key(id) {
1777 return Err(Error::DuplicateNode(*id));
1778 }
1779 if let Some((generation, live)) = self.generations.get(&id.slot()) {
1780 if *live {
1781 return Err(Error::InvalidPlacement("slot is still occupied"));
1782 }
1783 if *generation >= id.generation() {
1784 return Err(Error::StaleNode(*id));
1785 }
1786 }
1787 let mut descriptor = node.as_ref().clone();
1788 self.validate_name(node.as_ref(), None)?;
1789 self.admit_layers(usize::from(layer(node.view())))?;
1790 self.admit_focus_scopes(usize::from(crate::focus_scope::declared(node.view())))?;
1791 descriptor.normalize_input()?;
1792 self.layers += usize::from(layer(descriptor.view()));
1793 if crate::focus_scope::declared(descriptor.view()) {
1794 self.focus_scopes.insert(*id, 1);
1795 }
1796 if let Some(name) = descriptor.view().semantic_id() {
1797 self.names.insert(name.clone(), *id);
1798 }
1799 self.generations.insert(id.slot(), (id.generation(), true));
1800 let swipe = descriptor
1801 .view()
1802 .semantics
1803 .as_ref()
1804 .and_then(|s| s.swipe_capture)
1805 .map(crate::swipe::State::new);
1806 self.nodes.insert(
1807 *id,
1808 Node {
1809 descriptor: LiveDescriptor::owned(descriptor),
1810 parent: None,
1811 children: Children::default(),
1812 placed: false,
1813 suspended: false,
1814 next: None,
1815 clipboard: None,
1816 files: None,
1817 swipe,
1818 },
1819 );
1820 self.stats.created += 1;
1821 }
1822 Mutation::Patch { id, patch } => {
1823 self.prepare_patch(*id, patch)?.accept();
1824 }
1825 Mutation::Place { id, parent, before } => self.place(*id, *parent, *before, false)?,
1826 Mutation::Resume { id, parent, before } => self.place(*id, *parent, *before, true)?,
1827 Mutation::Suspend { id } => {
1828 let node = self.node(*id)?;
1829 if !node.placed || node.suspended {
1830 return Err(Error::InvalidPlacement(
1831 "only placed active ranges can be suspended",
1832 ));
1833 }
1834 self.nodes.get_mut(id).expect("validated node").suspended = true;
1835 self.prune_events();
1836 self.stats.suspended += 1;
1837 }
1838 Mutation::Dispose { id } => self.retire(*id, None)?,
1839 }
1840 Ok(())
1841 }
1842
1843 pub fn dispose(&mut self, id: NodeId) -> Result<(Receipt, Vec<NodeId>), Error> {
1848 let mut retired = Vec::new();
1849 self.retire(id, Some(&mut retired))?;
1850 self.receipt.applied += 1;
1851 Ok((self.receipt, retired))
1852 }
1853
1854 fn retire(&mut self, id: NodeId, mut retired: Option<&mut Vec<NodeId>>) -> Result<(), Error> {
1855 let parent = self.node(id)?.parent;
1856 let focus_ancestors = self.scope_ancestors(parent)?;
1857 self.unlink(id);
1858 let mut pending = vec![id];
1859 let mut focus_removed = 0usize;
1860 while let Some(id) = pending.pop() {
1861 let node = self.nodes.remove(&id).expect("owned subtree");
1862 self.focus_scopes.remove(&id);
1863 focus_removed += 1;
1864 self.layers -= usize::from(layer(node.descriptor.view()));
1865 if let Some(name) = node.descriptor.view().semantic_id() {
1866 self.names.remove(name);
1867 }
1868 self.generations
1869 .get_mut(&id.slot())
1870 .expect("known identity")
1871 .1 = false;
1872 pending.extend(node.children);
1873 self.stats.disposed += 1;
1874 if let Some(retired) = &mut retired {
1875 retired.push(id);
1876 }
1877 }
1878 for root in focus_ancestors {
1879 *self
1880 .focus_scopes
1881 .get_mut(&root)
1882 .expect("surviving scope ancestor") -= focus_removed;
1883 }
1884 self.prune_events();
1887 Ok(())
1888 }
1889}
1890
1891impl Render for Memory {
1892 fn supports_plot_pointer(&self) -> bool {
1893 true
1894 }
1895 fn listen(&mut self, node: NodeId, kind: EventKind, enabled: bool) -> Result<(), Error> {
1896 let descriptor = self.node(node)?.descriptor.view();
1897 if enabled {
1898 kind.validate_target(descriptor)?;
1899 }
1900 Ok(())
1901 }
1902 fn action(&mut self, action: Action) -> Result<(), Error> {
1903 action.validate_target(&self.node(action.node())?.descriptor)?;
1904 self.validate_clipboard_action(action)?;
1905 Err(Error::Unsupported(
1906 "headless reference interpreter has no physical actions",
1907 ))
1908 }
1909 fn needs_observe(&self) -> bool {
1910 !self.inputs.is_empty()
1911 }
1912 fn style_profile(&self) -> style::Profile {
1913 style::Profile::RECORD
1914 }
1915 fn capabilities(&self) -> Capabilities {
1916 Capabilities::default()
1917 }
1918
1919 fn apply(&mut self, mutations: &[Mutation]) -> Result<Receipt, Error> {
1920 for mutation in mutations {
1921 self.apply_one(mutation)?;
1922 self.receipt.applied += 1;
1923 }
1924 Ok(self.receipt)
1925 }
1926
1927 fn request(&mut self, query: Query, token: QueryToken) -> Result<(), Error> {
1928 let result = query
1929 .validate_target(&self.node(query.node())?.descriptor)
1930 .and(Err(Error::Unsupported(
1931 "headless reference interpreter has no platform geometry, selection or focus",
1932 )));
1933 self.inputs.push(Input::Response {
1934 token,
1935 applied: self.receipt.applied,
1936 result,
1937 });
1938 Ok(())
1939 }
1940
1941 fn drain(&mut self, inputs: &mut Vec<Input>) {
1942 self.prune_events();
1943 inputs.append(&mut self.inputs);
1944 }
1945}