Skip to main content

cranpose_foundation/modifier/
chain.rs

1//! The chain of modifier nodes a layout node holds, and its reconciliation
2//! with the node's modifier.
3
4use std::{any::TypeId, cell::RefCell, rc::Rc};
5
6use super::{
7    AnyModifierElement, DynModifierElement, ElementMaker, InvalidationKind, MAX_DELEGATE_DEPTH,
8    ModifierChainIter, ModifierChainNodeRef, ModifierNode, ModifierNodeContext, NodeCapabilities,
9    NodeMaker, NodePath, chain_node_ref::ChainPosition,
10};
11mod entry;
12mod entry_element;
13mod in_place;
14mod plain;
15use entry::ModifierNodeEntry;
16use entry_element::EntryElement;
17pub use entry_element::HeldElement;
18use in_place::{InPlace, update_entry_in_place};
19pub(crate) use plain::PlainWords;
20pub use plain::{
21    PLAIN_WORDS_MAX, PlainElement, PlainFns, PlainIntrinsic, PlainLayout, PlainLayoutFns,
22    PlainValue, PrepareAt, plain_element,
23};
24
25fn visit_node_tree_mut(
26    node: &mut dyn ModifierNode,
27    visitor: &mut dyn FnMut(&mut dyn ModifierNode),
28) {
29    visitor(node);
30    node.for_each_delegate_mut(&mut |child| visit_node_tree_mut(child, visitor));
31}
32
33fn nth_delegate(node: &dyn ModifierNode, target: usize) -> Option<&dyn ModifierNode> {
34    let mut current = 0usize;
35    let mut result: Option<&dyn ModifierNode> = None;
36    node.for_each_delegate(&mut |child| {
37        if result.is_none() && current == target {
38            result = Some(child);
39        }
40        current += 1;
41    });
42    result
43}
44
45fn nth_delegate_mut(node: &mut dyn ModifierNode, target: usize) -> Option<&mut dyn ModifierNode> {
46    let mut current = 0usize;
47    let mut result: Option<&mut dyn ModifierNode> = None;
48    node.for_each_delegate_mut(&mut |child| {
49        if result.is_none() && current == target {
50            result = Some(child);
51        }
52        current += 1;
53    });
54    result
55}
56
57fn with_node_context<F, R>(
58    node: &mut dyn ModifierNode,
59    context: &mut dyn ModifierNodeContext,
60    f: F,
61) -> R
62where
63    F: FnOnce(&mut dyn ModifierNode, &mut dyn ModifierNodeContext) -> R,
64{
65    context.push_active_capabilities(node.node_state().capabilities());
66    let result = f(node, context);
67    context.pop_active_capabilities();
68    result
69}
70
71fn request_update_auto_invalidations(
72    element: &dyn AnyModifierElement,
73    context: &mut dyn ModifierNodeContext,
74    capabilities: NodeCapabilities,
75) {
76    if let Some(kind) = element.update_invalidation_kind() {
77        let capabilities = NodeCapabilities::for_invalidation(kind);
78        context.push_active_capabilities(capabilities);
79        context.invalidate(kind);
80        context.pop_active_capabilities();
81    } else if element.auto_invalidates_on_update() {
82        request_auto_invalidations(context, capabilities);
83    }
84}
85
86fn request_auto_invalidations(
87    context: &mut dyn ModifierNodeContext,
88    capabilities: NodeCapabilities,
89) {
90    if capabilities.is_empty() {
91        return;
92    }
93
94    context.push_active_capabilities(capabilities);
95
96    if capabilities.contains(NodeCapabilities::LAYOUT) {
97        context.invalidate(InvalidationKind::Layout);
98    }
99    if capabilities.contains(NodeCapabilities::DRAW) {
100        context.invalidate(InvalidationKind::Draw);
101    }
102    if capabilities.contains(NodeCapabilities::POINTER_INPUT) {
103        context.invalidate(InvalidationKind::PointerInput);
104    }
105    if capabilities.contains(NodeCapabilities::SEMANTICS) {
106        context.invalidate(InvalidationKind::Semantics);
107    }
108    if capabilities.contains(NodeCapabilities::FOCUS) {
109        context.invalidate(InvalidationKind::Focus);
110    }
111
112    context.pop_active_capabilities();
113}
114
115fn attach_node_tree(node: &mut dyn ModifierNode, context: &mut dyn ModifierNodeContext) {
116    visit_node_tree_mut(node, &mut |n| {
117        if !n.node_state().is_attached() {
118            n.node_state().set_attached(true);
119            with_node_context(n, context, |node, ctx| node.on_attach(ctx));
120        }
121    });
122}
123
124fn reset_node_tree(node: &mut dyn ModifierNode) {
125    visit_node_tree_mut(node, &mut |n| n.on_reset());
126}
127
128fn detach_node_tree(node: &mut dyn ModifierNode) {
129    visit_node_tree_mut(node, &mut |n| {
130        if n.node_state().is_attached() {
131            n.on_detach();
132            n.node_state().set_attached(false);
133        }
134    });
135}
136
137/// Chain of modifier nodes attached to a layout node.
138///
139/// The chain tracks ownership of modifier nodes and reuses them across
140/// updates when the incoming element list still contains a node of the
141/// same type. Removed nodes detach automatically so callers do not need
142/// to manually manage their lifetimes.
143pub struct ModifierNodeChain {
144    entries: Vec<ModifierNodeEntry>,
145    pub(super) aggregated_capabilities: NodeCapabilities,
146    // While a node of the chain delegates: the chain's nodes in order,
147    // delegates after the node that delegates to them, each with its
148    // capabilities and the union of its own and those of every node after
149    // it. `None` otherwise, when the entries are the order and keep the
150    // unions: most chains delegate nowhere, and the list sits out of line.
151    #[expect(
152        clippy::box_collection,
153        reason = "one word in every chain, where a vector takes three"
154    )]
155    delegated_order: Option<Box<Vec<(NodePath, NodeCapabilities, NodeCapabilities)>>>,
156    /// Whether the chain's nodes are attached. A node that joins an attached
157    /// chain attaches as it joins; one that joins a detached chain waits for
158    /// [`Self::attach_nodes`].
159    attached: bool,
160}
161
162/// Buffers the reconciliation of a chain reuses, held per thread rather than
163/// per chain: a chain kept its own after its first reconciliation, a few
164/// hundred bytes on every node of a tree.
165#[derive(Default)]
166struct ReconcileScratch {
167    old_used: Vec<bool>,
168    match_order: Vec<Option<usize>>,
169    final_slots: Vec<Option<ModifierNodeEntry>>,
170    elements: Vec<DynModifierElement>,
171}
172
173thread_local! {
174    static RECONCILE_SCRATCH: RefCell<ReconcileScratch> =
175        RefCell::default();
176}
177
178impl Default for ModifierNodeChain {
179    fn default() -> Self {
180        Self::new()
181    }
182}
183
184struct EntryMatchQuery<'a> {
185    element_type: TypeId,
186    node_type: TypeId,
187    key: Option<u64>,
188    hash_code: u64,
189    element: &'a DynModifierElement,
190}
191
192// The first old entry no element took yet that `query` may take over: one
193// of its types and key, or, for an unkeyed element, an equal unkeyed one of
194// its types, else any unkeyed one of its types. A chain holds a few entries,
195// so a scan takes less than an index would.
196fn find_match(
197    entries: &[ModifierNodeEntry],
198    used: &[bool],
199    query: &EntryMatchQuery<'_>,
200) -> Option<usize> {
201    let candidates = || {
202        entries
203            .iter()
204            .zip(used)
205            .enumerate()
206            .filter(|(_, (entry, used))| {
207                let held = entry.held();
208                !**used
209                    && held.element_type() == query.element_type
210                    && held.node_type() == query.node_type
211            })
212            .map(|(index, (entry, _))| (index, entry))
213    };
214    match query.key {
215        Some(key) => candidates()
216            .find(|(_, entry)| entry.key() == Some(key))
217            .map(|(index, _)| index),
218        None => {
219            let mut unkeyed = candidates().filter(|(_, entry)| entry.key().is_none());
220            let first = unkeyed.next()?;
221            std::iter::once(first)
222                .chain(unkeyed)
223                .find(|(_, entry)| {
224                    let held = entry.held();
225                    held.hash_code() == query.hash_code && held.equals(&**query.element)
226                })
227                .map_or(Some(first.0), |(index, _)| Some(index))
228        }
229    }
230}
231
232// A new entry for `element`: its node, updated, and attached when `attach`,
233// as it joins an attached chain, or its words. The flag tells whether the
234// node delegates, asked while the node is borrowed for its update.
235fn new_entry(
236    element: &DynModifierElement,
237    context: &mut dyn ModifierNodeContext,
238    attach: bool,
239) -> (ModifierNodeEntry, bool) {
240    match element.maker() {
241        ElementMaker::Plain(value) => (ModifierNodeEntry::of_plain(value), false),
242        ElementMaker::Node(maker) => {
243            let entry = ModifierNodeEntry::of_node(element, maker, element.capabilities());
244            let delegating = entry.node().is_some_and(|node| {
245                let mut node = node.borrow_mut();
246                if attach {
247                    attach_node_tree(&mut *node, context);
248                }
249                maker.update_node(&mut *node);
250                delegates(&*node)
251            });
252            (entry, delegating)
253        }
254    }
255}
256
257// `new_entry` for an element that joins a chain of entries already there:
258// the stages its node takes part in are invalidated.
259fn fresh_entry(
260    element: &DynModifierElement,
261    context: &mut dyn ModifierNodeContext,
262    attach: bool,
263) -> ModifierNodeEntry {
264    let (entry, _) = new_entry(element, context, attach);
265    request_auto_invalidations(context, entry.capabilities());
266    entry
267}
268
269// Whether `node` delegates to another node.
270fn delegates(node: &dyn ModifierNode) -> bool {
271    let mut delegates = false;
272    node.for_each_delegate(&mut |_| delegates = true);
273    delegates
274}
275
276/// Matches `element`, at `new_pos` of the rebuilt tail, against the old
277/// entries: one of its type and key that can
278/// take it is updated and marked for `new_pos`, and `None` is returned;
279/// otherwise the element's new entry is, attached when `attach`.
280fn reconcile_element(
281    element: DynModifierElement,
282    new_pos: usize,
283    old_entries: &mut [ModifierNodeEntry],
284    (used, match_order): (&mut [bool], &mut [Option<usize>]),
285    context: &mut dyn ModifierNodeContext,
286    attach: bool,
287) -> Option<ModifierNodeEntry> {
288    let maker = element.maker();
289    let key = element.key();
290    let query = EntryMatchQuery {
291        element_type: element.element_type(),
292        node_type: match maker {
293            ElementMaker::Node(maker) => maker.node_type(),
294            ElementMaker::Plain(value) => value.fns().element_type(),
295        },
296        key,
297        // Only an unkeyed element is matched by its hash.
298        hash_code: if key.is_none() {
299            element.hash_code()
300        } else {
301            0
302        },
303        element: &element,
304    };
305    let capabilities = element.capabilities();
306    let Some(idx) = find_match(old_entries, used, &query) else {
307        return Some(fresh_entry(&element, context, attach));
308    };
309    let entry = &mut old_entries[idx];
310    match (&mut *entry, maker) {
311        (ModifierNodeEntry::Plain { fns, words, .. }, ElementMaker::Plain(value)) => {
312            let held = &mut words[..fns.words()];
313            if !value.equals_words(held) {
314                value.write_words(held);
315                request_update_auto_invalidations(&*element, context, capabilities);
316            }
317        }
318        (
319            ModifierNodeEntry::Node {
320                element: held,
321                node,
322                capabilities: held_capabilities,
323                ..
324            },
325            ElementMaker::Node(maker),
326        ) if maker.can_update_node(&*node.borrow()) => {
327            let same_element = held.view(node, *held_capabilities).equals(&*element);
328            if !same_element || element.requires_update() {
329                maker.update_node(&mut *node.borrow_mut());
330                request_update_auto_invalidations(&*element, context, capabilities);
331                *held = EntryElement::new(&element, maker);
332            }
333            *held_capabilities = capabilities;
334            node.borrow().node_state().set_capabilities(capabilities);
335        }
336        _ => return Some(fresh_entry(&element, context, attach)),
337    }
338
339    used[idx] = true;
340    match_order[idx] = Some(new_pos);
341    if idx != new_pos {
342        request_auto_invalidations(context, capabilities);
343    }
344    None
345}
346
347impl ModifierNodeChain {
348    /// An attached chain: its nodes attach as they join it.
349    pub fn new() -> Self {
350        let mut chain = Self::detached();
351        chain.attached = true;
352        chain
353    }
354
355    /// A detached chain: its nodes attach at [`Self::attach_nodes`], as a
356    /// layout node's do once the node has its id.
357    pub fn detached() -> Self {
358        Self {
359            entries: Vec::new(),
360            aggregated_capabilities: NodeCapabilities::empty(),
361            delegated_order: None,
362            attached: false,
363        }
364    }
365
366    /// Detaches all nodes in the chain.
367    pub fn detach_nodes(&mut self) {
368        if !self.attached {
369            return;
370        }
371        self.attached = false;
372        for entry in &self.entries {
373            entry.detach();
374        }
375    }
376
377    /// Whether the chain's nodes are attached.
378    pub fn is_attached(&self) -> bool {
379        self.attached
380    }
381
382    /// Attaches all nodes in the chain.
383    pub fn attach_nodes(&mut self, context: &mut dyn ModifierNodeContext) {
384        if self.attached {
385            return;
386        }
387        self.attached = true;
388        for node in self.entries.iter().filter_map(ModifierNodeEntry::node) {
389            attach_node_tree(&mut *node.borrow_mut(), context);
390        }
391    }
392
393    /// Reconcile the chain against the provided elements, attaching newly
394    /// created nodes and detaching nodes that are no longer required.
395    ///
396    /// This method delegates to `update_from_ref_iter` which handles the
397    /// actual reconciliation logic.
398    pub fn update_from_slice(
399        &mut self,
400        elements: &[DynModifierElement],
401        context: &mut dyn ModifierNodeContext,
402    ) {
403        self.update_from_ref_iter(elements.iter(), context);
404    }
405
406    /// Updates in place the entries `changed` names, one bit an index, for
407    /// `elements` that differ from the chain's only in those: entries and
408    /// elements line up one to one, and every other entry stays as it is.
409    /// `false` when they do not line up or an entry cannot take its element;
410    /// a full update then reconciles the chain.
411    pub fn update_entries_in_place<'a, I>(
412        &mut self,
413        elements: I,
414        element_count: usize,
415        changed: u64,
416        context: &mut dyn ModifierNodeContext,
417    ) -> bool
418    where
419        I: Iterator<Item = &'a DynModifierElement>,
420    {
421        if element_count != self.entries.len() {
422            return false;
423        }
424        let mut relink = false;
425        let updated = self
426            .entries
427            .iter_mut()
428            .zip(elements)
429            .enumerate()
430            .filter(|&(index, _)| {
431                u32::try_from(index)
432                    .ok()
433                    .and_then(|bit| changed.checked_shr(bit))
434                    .is_some_and(|rest| rest & 1 == 1)
435            })
436            .map(|(_, pair)| pair)
437            .all(
438                |(entry, element)| match update_entry_in_place(entry, element, context) {
439                    Some(outcome) => {
440                        relink |= outcome == InPlace::Relink;
441                        true
442                    }
443                    None => false,
444                },
445            );
446        if relink {
447            self.sync_chain_links();
448        }
449        updated
450    }
451
452    /// Asks `context` for what an update of the last node's values
453    /// invalidates, by the node's capabilities, after its caller updated the
454    /// node in place and left its capabilities as they were.
455    pub fn invalidate_last(&self, context: &mut dyn ModifierNodeContext) {
456        if let Some(entry) = self.entries.last() {
457            request_auto_invalidations(context, entry.capabilities());
458        }
459    }
460
461    /// Reconciles the chain against the elements that `elements` yields, without collecting them
462    /// first. See `update_from_slice`.
463    pub fn update_from_ref_iter<'a, I>(
464        &mut self,
465        elements: I,
466        context: &mut dyn ModifierNodeContext,
467    ) where
468        I: Iterator<Item = &'a DynModifierElement>,
469    {
470        // No element of a chain without entries, as a new node's, can take
471        // over an entry: the reconciliation's buffers stay unused.
472        if self.entries.is_empty() {
473            self.build(elements, context);
474            return;
475        }
476        // Taken out for the reconciliation, so one that reconciles another
477        // chain inside it works on buffers of its own.
478        let mut scratch = RECONCILE_SCRATCH
479            .try_with(|scratch| std::mem::take(&mut *scratch.borrow_mut()))
480            .unwrap_or_default();
481        self.reconcile(elements, context, &mut scratch);
482        scratch.elements.clear();
483        scratch.final_slots.clear();
484        let _ = RECONCILE_SCRATCH.try_with(|slot| *slot.borrow_mut() = scratch);
485    }
486
487    // Makes an entry of each of `elements` for a chain that holds none, in
488    // one pass, which also finds the union of their capabilities and whether
489    // a node delegates. The union is invalidated once for the whole chain:
490    // a node's invalidations reach every stage its chain takes part in.
491    fn build<'a, I>(&mut self, elements: I, context: &mut dyn ModifierNodeContext)
492    where
493        I: Iterator<Item = &'a DynModifierElement>,
494    {
495        self.entries.reserve_exact(elements.size_hint().0);
496        let mut capabilities = NodeCapabilities::empty();
497        let mut delegating = false;
498        for element in elements {
499            let (entry, delegated) = new_entry(element, context, self.attached);
500            capabilities |= entry.capabilities();
501            delegating |= delegated;
502            self.entries.push(entry);
503        }
504        request_auto_invalidations(context, capabilities);
505        if delegating {
506            self.order_with_delegates();
507        } else {
508            self.delegated_order = None;
509        }
510        self.link_aggregates();
511    }
512
513    fn reconcile<'a, I>(
514        &mut self,
515        elements: I,
516        context: &mut dyn ModifierNodeContext,
517        scratch: &mut ReconcileScratch,
518    ) where
519        I: Iterator<Item = &'a DynModifierElement>,
520    {
521        let old_len = self.entries.len();
522        let mut fast_path_failed_at: Option<usize> = None;
523        let mut elements_count = 0;
524        // Entries updated where they are keep the links between them, unless
525        // their capabilities or delegates change.
526        let mut relink = false;
527
528        scratch.elements.clear();
529
530        for (idx, element) in elements.enumerate() {
531            elements_count = idx + 1;
532            if fast_path_failed_at.is_none() && idx < old_len {
533                if let Some(outcome) =
534                    update_entry_in_place(&mut self.entries[idx], element, context)
535                {
536                    relink |= outcome == InPlace::Relink;
537                    continue;
538                }
539                fast_path_failed_at = Some(idx);
540            }
541            scratch.elements.push(element.clone());
542        }
543
544        if fast_path_failed_at.is_none() && scratch.elements.is_empty() {
545            if elements_count < self.entries.len() {
546                for entry in self.entries.drain(elements_count..) {
547                    request_auto_invalidations(context, entry.capabilities());
548                    entry.detach();
549                }
550                relink = true;
551            }
552            if relink {
553                self.sync_chain_links();
554            }
555            return;
556        }
557
558        self.rebuild_tail(fast_path_failed_at.unwrap_or(old_len), context, scratch);
559    }
560
561    /// Rebuilds the chain from `fail_idx` for the elements in `scratch`:
562    /// each takes over an old entry of its type and key, wherever it was,
563    /// or gets a node of its own; old entries nothing took over detach.
564    fn rebuild_tail(
565        &mut self,
566        fail_idx: usize,
567        context: &mut dyn ModifierNodeContext,
568        scratch: &mut ReconcileScratch,
569    ) {
570        // No old entry to take over, as for elements that join the end of a
571        // chain: every element gets an entry of its own, with no query for a
572        // match.
573        if fail_idx == self.entries.len() {
574            self.entries.reserve_exact(scratch.elements.len());
575            for element in scratch.elements.drain(..) {
576                self.entries
577                    .push(fresh_entry(&element, context, self.attached));
578            }
579            self.sync_chain_links();
580            return;
581        }
582        let mut old_entries: Vec<ModifierNodeEntry> = self.entries.drain(fail_idx..).collect();
583        let processed_entries_len = self.entries.len();
584        let old_len = old_entries.len();
585
586        scratch.old_used.clear();
587        scratch.old_used.resize(old_len, false);
588
589        scratch.match_order.clear();
590        scratch.match_order.resize(old_len, None);
591
592        let new_elements_count = scratch.elements.len();
593        scratch.final_slots.clear();
594        scratch.final_slots.reserve(new_elements_count);
595
596        for (new_pos, element) in scratch.elements.drain(..).enumerate() {
597            let fresh = reconcile_element(
598                element,
599                new_pos,
600                &mut old_entries,
601                (&mut scratch.old_used, &mut scratch.match_order),
602                context,
603                self.attached,
604            );
605            scratch.final_slots.push(fresh);
606        }
607
608        for (i, entry) in old_entries.into_iter().enumerate() {
609            match scratch.match_order[i] {
610                Some(pos) if scratch.old_used[i] => scratch.final_slots[pos] = Some(entry),
611                _ => {
612                    request_auto_invalidations(context, entry.capabilities());
613                    entry.detach();
614                }
615            }
616        }
617
618        // Exactly: a chain is rebuilt only when its modifiers change, and
619        // most hold one to three entries, where growth would make room for
620        // four.
621        self.entries.reserve_exact(scratch.final_slots.len());
622        for slot in scratch.final_slots.drain(..) {
623            if let Some(entry) = slot {
624                self.entries.push(entry);
625            } else {
626                log::error!("modifier reconciliation produced an empty final slot");
627            }
628        }
629
630        debug_assert_eq!(
631            self.entries.len(),
632            processed_entries_len + new_elements_count
633        );
634        self.sync_chain_links();
635    }
636
637    /// Convenience wrapper that accepts any iterator of type-erased
638    /// modifier elements. Elements are collected into a temporary vector
639    /// before reconciliation.
640    pub fn update<I>(&mut self, elements: I, context: &mut dyn ModifierNodeContext)
641    where
642        I: IntoIterator<Item = DynModifierElement>,
643    {
644        let collected: Vec<DynModifierElement> = elements.into_iter().collect();
645        self.update_from_slice(&collected, context);
646    }
647
648    /// Resets all nodes in the chain. This mirrors the behaviour of
649    /// Jetpack Compose's `onReset` callback.
650    pub fn reset(&mut self) {
651        for node in self.entries.iter().filter_map(ModifierNodeEntry::node) {
652            reset_node_tree(&mut *node.borrow_mut());
653        }
654    }
655
656    /// Detaches every node in the chain and clears internal storage.
657    pub fn detach_all(&mut self) {
658        for entry in std::mem::take(&mut self.entries) {
659            entry.detach();
660            if let Some(node) = entry.node() {
661                node.borrow()
662                    .node_state()
663                    .set_capabilities(NodeCapabilities::empty());
664            }
665        }
666        self.sync_chain_links();
667    }
668
669    /// The number of entries in the chain: its nodes and its plain elements.
670    pub fn len(&self) -> usize {
671        self.entries.len()
672    }
673
674    /// Whether the chain holds no nodes.
675    pub fn is_empty(&self) -> bool {
676        self.entries.is_empty()
677    }
678
679    /// The elements of the chain's nodes, one for each in chain order: those
680    /// the chain was last updated from, or equal ones it kept, or the nodes
681    /// that hold every value of them.
682    pub fn held_elements(&self) -> impl ExactSizeIterator<Item = HeldElement<'_>> {
683        self.entries.iter().map(ModifierNodeEntry::held)
684    }
685
686    /// Returns the aggregated capability mask for the entire chain.
687    pub fn capabilities(&self) -> NodeCapabilities {
688        self.aggregated_capabilities
689    }
690
691    /// Returns true if the chain contains at least one node with the requested capability.
692    pub fn has_capability(&self, capability: NodeCapabilities) -> bool {
693        self.aggregated_capabilities.contains(capability)
694    }
695
696    /// Returns the sentinel head reference for traversal.
697    pub fn head(&self) -> ModifierChainNodeRef<'_> {
698        self.node_ref(ChainPosition::Head)
699    }
700
701    /// Returns the sentinel tail reference for traversal.
702    pub fn tail(&self) -> ModifierChainNodeRef<'_> {
703        self.node_ref(ChainPosition::Tail)
704    }
705
706    /// Iterates over the chain from head to tail, skipping sentinels.
707    pub fn head_to_tail(&self) -> ModifierChainIter<'_> {
708        ModifierChainIter::forward(self)
709    }
710
711    /// Iterates over the chain from tail to head, skipping sentinels.
712    pub fn tail_to_head(&self) -> ModifierChainIter<'_> {
713        ModifierChainIter::backward(self)
714    }
715
716    /// Calls `f` for every node in insertion order.
717    pub fn for_each_forward<F>(&self, mut f: F)
718    where
719        F: FnMut(ModifierChainNodeRef<'_>),
720    {
721        for node in self.head_to_tail() {
722            f(node);
723        }
724    }
725
726    /// Calls `f` for every node containing any capability from `mask`.
727    pub fn for_each_forward_matching<F>(&self, mask: NodeCapabilities, mut f: F)
728    where
729        F: FnMut(ModifierChainNodeRef<'_>),
730    {
731        if mask.is_empty() {
732            self.for_each_forward(f);
733            return;
734        }
735
736        if !self.head().aggregate_child_capabilities().intersects(mask) {
737            return;
738        }
739
740        for node in self.head_to_tail() {
741            if node.kind_set().intersects(mask) {
742                f(node);
743            }
744        }
745    }
746
747    /// Calls `f` for every node containing any capability from `mask`, providing the node ref.
748    pub fn for_each_node_with_capability<F>(&self, mask: NodeCapabilities, mut f: F)
749    where
750        F: FnMut(ModifierChainNodeRef<'_>, &dyn ModifierNode),
751    {
752        self.for_each_forward_matching(mask, |node_ref| {
753            node_ref.with_node(|node| f(node_ref.clone(), node));
754        });
755    }
756
757    /// Calls `f` for every node in reverse insertion order.
758    pub fn for_each_backward<F>(&self, mut f: F)
759    where
760        F: FnMut(ModifierChainNodeRef<'_>),
761    {
762        for node in self.tail_to_head() {
763            f(node);
764        }
765    }
766
767    /// Returns the node reference that owns `node`.
768    pub fn find_node_ref(&self, node: &dyn ModifierNode) -> Option<ModifierChainNodeRef<'_>> {
769        fn node_data_ptr(node: &dyn ModifierNode) -> *const () {
770            node as *const dyn ModifierNode as *const ()
771        }
772
773        let target = node_data_ptr(node);
774        // A node comes before its delegates, so a delegate that starts its
775        // node's memory finds the node.
776        (0..self.order_len())
777            .find(|&index| {
778                self.with_path(self.order_at(index).0, |node| node_data_ptr(node) == target)
779                    .unwrap_or(false)
780            })
781            .map(|index| self.node_ref(ChainPosition::Node(index)))
782    }
783
784    /// Downcasts the node at `index` to the requested type.
785    /// Returns a `Ref` guard that dereferences to the node type.
786    pub fn node<N: ModifierNode + 'static>(&self, index: usize) -> Option<std::cell::Ref<'_, N>> {
787        self.get_node_rc(index).and_then(|node| {
788            std::cell::Ref::filter_map(node.borrow(), |boxed_node| {
789                boxed_node.as_any().downcast_ref::<N>()
790            })
791            .ok()
792        })
793    }
794
795    /// Downcasts the node at `index` to the requested mutable type.
796    /// Returns a `RefMut` guard that dereferences to the node type.
797    pub fn node_mut<N: ModifierNode + 'static>(
798        &self,
799        index: usize,
800    ) -> Option<std::cell::RefMut<'_, N>> {
801        self.get_node_rc(index).and_then(|node| {
802            std::cell::RefMut::filter_map(node.borrow_mut(), |boxed_node| {
803                boxed_node.as_any_mut().downcast_mut::<N>()
804            })
805            .ok()
806        })
807    }
808
809    /// Returns the shared node at the given index, `None` for a plain
810    /// element, which has none. Coordinators compare it with the node they
811    /// hold and clone it only to hold a new one.
812    pub fn get_node_rc(&self, index: usize) -> Option<&Rc<RefCell<dyn ModifierNode>>> {
813        self.entries.get(index).and_then(ModifierNodeEntry::node)
814    }
815
816    /// The table and the words of the plain element at `index`.
817    #[inline]
818    pub fn plain_words(&self, index: usize) -> Option<(&'static PlainFns, &[u32])> {
819        self.entries.get(index)?.plain_words()
820    }
821
822    /// How the plain element at `index` measures, with every word of its
823    /// entry: the words past the element's own are zero.
824    #[inline]
825    pub fn plain_layout(
826        &self,
827        index: usize,
828    ) -> Option<(Option<&'static PlainLayoutFns>, &[u32; PLAIN_WORDS_MAX])> {
829        self.entries.get(index)?.plain_layout()
830    }
831
832    /// The value of the plain element at `index`, when it is an `E`.
833    #[inline]
834    pub fn plain<E: PlainElement>(&self, index: usize) -> Option<E> {
835        self.entries.get(index)?.held().plain()
836    }
837
838    /// Returns true if the chain contains any nodes matching the given invalidation kind.
839    pub fn has_nodes_for_invalidation(&self, kind: InvalidationKind) -> bool {
840        self.aggregated_capabilities
841            .contains(NodeCapabilities::for_invalidation(kind))
842    }
843
844    /// Visits every node mutably in insertion order together with its capability mask.
845    pub fn visit_nodes_mut<F>(&mut self, mut f: F)
846    where
847        F: FnMut(&mut dyn ModifierNode, NodeCapabilities),
848    {
849        for index in 0..self.order_len() {
850            let (path, cached_caps, _agg) = self.order_at(index);
851            let Some(node) = self.entries[path.entry()].node() else {
852                continue;
853            };
854            let mut node_borrow = node.borrow_mut();
855            let mut current: &mut dyn ModifierNode = &mut *node_borrow;
856            for &delegate_index in path.delegates() {
857                match nth_delegate_mut(current, delegate_index as usize) {
858                    Some(delegate) => current = delegate,
859                    None => return,
860                }
861            }
862            f(current, cached_caps);
863        }
864    }
865
866    pub(super) fn node_ref(&self, position: ChainPosition) -> ModifierChainNodeRef<'_> {
867        ModifierChainNodeRef {
868            chain: self,
869            position,
870        }
871    }
872
873    // Runs `f` on the node at `path`; `None` when a delegate of it is gone.
874    pub(super) fn with_path<R>(
875        &self,
876        path: NodePath,
877        f: impl FnOnce(&dyn ModifierNode) -> R,
878    ) -> Option<R> {
879        let node_borrow = self.entries[path.entry()].node()?.borrow();
880        let mut current: &dyn ModifierNode = &*node_borrow;
881        for &delegate_index in path.delegates() {
882            current = nth_delegate(current, delegate_index as usize)?;
883        }
884        Some(f(current))
885    }
886
887    // How many nodes the chain's order holds, delegates included.
888    pub(super) fn order_len(&self) -> usize {
889        self.delegated_order
890            .as_deref()
891            .map_or(self.entries.len(), Vec::len)
892    }
893
894    // The node at `index` of the chain's order: its path, its capabilities
895    // and the union of capabilities from it to the tail.
896    pub(super) fn order_at(&self, index: usize) -> (NodePath, NodeCapabilities, NodeCapabilities) {
897        match self.delegated_order.as_deref() {
898            Some(order) => order[index],
899            None => {
900                let entry = &self.entries[index];
901                (
902                    NodePath::root(index),
903                    entry.capabilities(),
904                    entry.aggregate(),
905                )
906            }
907        }
908    }
909
910    // Orders the nodes again and works out the union of capabilities from
911    // each node to the tail.
912    fn sync_chain_links(&mut self) {
913        let delegating = self
914            .entries
915            .iter()
916            .filter_map(ModifierNodeEntry::node)
917            .any(|node| delegates(&*node.borrow()));
918        if delegating {
919            self.order_with_delegates();
920        } else {
921            self.delegated_order = None;
922        }
923        self.link_aggregates();
924    }
925
926    // Works out the union of capabilities from each node to the tail.
927    fn link_aggregates(&mut self) {
928        let mut aggregate = NodeCapabilities::empty();
929        if let Some(order) = self.delegated_order.as_deref_mut() {
930            for (_, caps, aggregate_child) in order.iter_mut().rev() {
931                aggregate |= *caps;
932                *aggregate_child = aggregate;
933            }
934        } else {
935            for entry in self.entries.iter_mut().rev() {
936                aggregate |= entry.capabilities();
937                entry.set_aggregate(aggregate);
938            }
939        }
940        self.aggregated_capabilities = aggregate;
941    }
942
943    // Orders the nodes of a chain of which a node delegates, each delegate
944    // after the node that delegates to it.
945    fn order_with_delegates(&mut self) {
946        let order = self.delegated_order.get_or_insert_default();
947        order.clear();
948        let mut path_buf = [0usize; MAX_DELEGATE_DEPTH];
949        for (index, entry) in self.entries.iter().enumerate() {
950            match entry.node() {
951                Some(node) => {
952                    Self::enumerate_link_order(&*node.borrow(), index, &mut path_buf, 0, order);
953                }
954                None => order.push((
955                    NodePath::root(index),
956                    entry.capabilities(),
957                    NodeCapabilities::empty(),
958                )),
959            }
960        }
961    }
962
963    fn enumerate_link_order(
964        node: &dyn ModifierNode,
965        entry: usize,
966        path_buf: &mut [usize; MAX_DELEGATE_DEPTH],
967        path_len: usize,
968        out: &mut Vec<(NodePath, NodeCapabilities, NodeCapabilities)>,
969    ) {
970        let caps = node.node_state().capabilities();
971        out.push((
972            NodePath::from_slice(entry, &path_buf[..path_len]),
973            caps,
974            NodeCapabilities::empty(),
975        ));
976        let mut delegate_index = 0usize;
977        node.for_each_delegate(&mut |child| {
978            if path_len < MAX_DELEGATE_DEPTH {
979                path_buf[path_len] = delegate_index;
980                Self::enumerate_link_order(child, entry, path_buf, path_len + 1, out);
981            }
982            delegate_index += 1;
983        });
984    }
985}