Skip to main content

cranpose_foundation/modifier/chain/
plain.rs

1// A modifier element that is a value alone: a chain keeps it as words in
2// the element's entry, with no node.
3
4use std::{
5    any::{Any, TypeId, type_name},
6    fmt,
7    hash::Hasher,
8    marker::PhantomData,
9};
10
11use cranpose_core::{ProvidedValue, hash::default};
12use cranpose_ui_layout::{
13    ConstraintsHold, LayoutDirection, LayoutModifierMeasureResult, WrappedHold,
14};
15
16use super::super::{
17    AnyModifierElement, Constraints, DynModifierElement, ElementMaker, InvalidationKind,
18    Measurable, ModifierNodeContext, NodeCapabilities, Size,
19};
20
21/// The most words a plain element's value takes: with its type's table
22/// they fit in the room of a chain entry, and a coordinator keeps a copy
23/// of them for every layout modifier of a node.
24pub const PLAIN_WORDS_MAX: usize = 5;
25
26/// A modifier element that is a value and nothing else: it keeps no state
27/// between frames, hears of no attach, detach or reset and delegates to no
28/// node. A chain keeps its value as [`Self::WORDS`] words and makes no node
29/// for it; a reader takes the value back with [`Self::from_words`].
30pub trait PlainElement: fmt::Debug + PartialEq + Sized + 'static {
31    /// How many words the value takes: at most [`PLAIN_WORDS_MAX`].
32    const WORDS: usize;
33
34    /// What the element takes part in: layout, draw or both.
35    const CAPABILITIES: NodeCapabilities;
36
37    /// The one pipeline stage a changed value invalidates, or `None` to
38    /// invalidate every stage of [`Self::CAPABILITIES`].
39    const UPDATE_INVALIDATION: Option<InvalidationKind> = None;
40
41    /// Writes the value into `words`, which holds [`Self::WORDS`] words.
42    fn to_words(&self, words: &mut [u32]);
43
44    /// The value that [`Self::to_words`] wrote into `words`.
45    fn from_words(words: &[u32]) -> Self;
46
47    /// How the element measures the content it wraps, for an element with
48    /// [`NodeCapabilities::LAYOUT`]: `Some(&PlainLayoutFns::of::<Self>())`
49    /// for a [`PlainLayout`]. `None`, the default, passes the content's
50    /// measure through.
51    const LAYOUT: Option<&'static PlainLayoutFns> = None;
52
53    /// Human readable name surfaced to inspector tooling.
54    fn inspector_name(&self) -> &'static str {
55        type_name::<Self>()
56    }
57
58    /// Records inspector properties for tooling.
59    fn inspector_properties(&self, _inspector: &mut dyn FnMut(&'static str, String)) {}
60}
61
62/// A plain element that measures the content it wraps, as a
63/// [`super::super::LayoutModifierNode`] does, from its value alone.
64pub trait PlainLayout: PlainElement {
65    /// Measures the wrapped content under `constraints` and returns the size
66    /// the element takes and where it places the content.
67    fn measure(
68        &self,
69        context: &mut dyn ModifierNodeContext,
70        measurable: &dyn Measurable,
71        constraints: Constraints,
72    ) -> LayoutModifierMeasureResult;
73
74    /// The element as a coordinator keeps it for the measures `at` tells:
75    /// an element that rounds its values to device pixels, or mirrors them
76    /// for a layout direction, may do so here once, and measure from those
77    /// values. The default is the element itself.
78    fn prepared(self, _at: PrepareAt) -> Self {
79        self
80    }
81
82    /// Whether [`Self::prepared`] changes the element: `false`, the
83    /// default, lets a coordinator copy the words as they are.
84    const PREPARES: bool = false;
85
86    /// The incoming constraints the last measure, which gave `size` under
87    /// `constraints`, holds for; see
88    /// [`super::super::LayoutModifierNode::measure_hold`].
89    fn measure_hold(
90        &self,
91        _density: f32,
92        _constraints: Constraints,
93        _size: Size,
94        _wrapped: WrappedHold,
95    ) -> Option<ConstraintsHold> {
96        None
97    }
98
99    /// The intrinsic size `kind` names: the wrapped content's by default,
100    /// for an element that keeps the content's size.
101    fn intrinsic(&self, measurable: &dyn Measurable, kind: PlainIntrinsic, _density: f32) -> f32 {
102        kind.of(measurable)
103    }
104}
105
106/// What a coordinator prepares a plain layout element for.
107#[derive(Clone, Copy, Debug, PartialEq)]
108pub struct PrepareAt {
109    /// The density of the node's measures.
110    pub density: f32,
111    /// The direction the node's layout reads.
112    pub direction: LayoutDirection,
113}
114
115/// Which intrinsic size a measure asks for.
116#[derive(Clone, Copy, Debug, PartialEq)]
117pub enum PlainIntrinsic {
118    /// The minimum width at a height.
119    MinWidth(f32),
120    /// The maximum width at a height.
121    MaxWidth(f32),
122    /// The minimum height at a width.
123    MinHeight(f32),
124    /// The maximum height at a width.
125    MaxHeight(f32),
126}
127
128impl PlainIntrinsic {
129    /// This intrinsic size of `measurable`.
130    pub fn of(self, measurable: &dyn Measurable) -> f32 {
131        match self {
132            Self::MinWidth(height) => measurable.min_intrinsic_width(height),
133            Self::MaxWidth(height) => measurable.max_intrinsic_width(height),
134            Self::MinHeight(width) => measurable.min_intrinsic_height(width),
135            Self::MaxHeight(width) => measurable.max_intrinsic_height(width),
136        }
137    }
138
139    /// The extent across the axis asked for: the height of a width, the
140    /// width of a height.
141    pub fn cross(self) -> f32 {
142        match self {
143            Self::MinWidth(cross)
144            | Self::MaxWidth(cross)
145            | Self::MinHeight(cross)
146            | Self::MaxHeight(cross) => cross,
147        }
148    }
149
150    /// The same size asked for at the extent `cross` across its axis.
151    pub fn at(self, cross: f32) -> Self {
152        match self {
153            Self::MinWidth(_) => Self::MinWidth(cross),
154            Self::MaxWidth(_) => Self::MaxWidth(cross),
155            Self::MinHeight(_) => Self::MinHeight(cross),
156            Self::MaxHeight(_) => Self::MaxHeight(cross),
157        }
158    }
159
160    /// Whether a width is asked for, not a height.
161    pub fn is_width(self) -> bool {
162        matches!(self, Self::MinWidth(_) | Self::MaxWidth(_))
163    }
164}
165
166// Writes an element's words as a coordinator keeps them.
167type PrepareFn = fn(&[u32], PrepareAt, &mut [u32]);
168
169type MeasureFn = fn(
170    &[u32],
171    &mut dyn ModifierNodeContext,
172    &dyn Measurable,
173    Constraints,
174) -> LayoutModifierMeasureResult;
175
176/// How a plain layout element measures, read from its words: what a
177/// coordinator keeps of the element's type.
178pub struct PlainLayoutFns {
179    // `None` for an element a coordinator keeps as it is.
180    prepare: Option<PrepareFn>,
181    measure: MeasureFn,
182    measure_hold: fn(&[u32], f32, Constraints, Size, WrappedHold) -> Option<ConstraintsHold>,
183    intrinsic: fn(&[u32], &dyn Measurable, PlainIntrinsic, f32) -> f32,
184}
185
186impl fmt::Debug for PlainLayoutFns {
187    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188        f.debug_struct("PlainLayoutFns").finish_non_exhaustive()
189    }
190}
191
192impl PlainLayoutFns {
193    /// The table of the plain layout element `E`.
194    pub const fn of<E: PlainLayout>() -> Self {
195        Self {
196            prepare: if E::PREPARES {
197                Some(|words, at, prepared| {
198                    E::from_words(words)
199                        .prepared(at)
200                        .to_words(&mut prepared[..E::WORDS]);
201                })
202            } else {
203                None
204            },
205            measure: |words, context, measurable, constraints| {
206                E::from_words(words).measure(context, measurable, constraints)
207            },
208            measure_hold: |words, density, constraints, size, wrapped| {
209                E::from_words(words).measure_hold(density, constraints, size, wrapped)
210            },
211            intrinsic: |words, measurable, kind, density| {
212                E::from_words(words).intrinsic(measurable, kind, density)
213            },
214        }
215    }
216
217    /// The words of the element `words` hold as a coordinator keeps it for
218    /// the measures `at` tells; see [`PlainLayout::prepared`]. The other
219    /// calls take prepared words.
220    #[inline]
221    pub fn prepare(&self, words: &[u32; PLAIN_WORDS_MAX], at: PrepareAt) -> [u32; PLAIN_WORDS_MAX] {
222        match self.prepare {
223            Some(prepare) => {
224                let mut prepared = [0; PLAIN_WORDS_MAX];
225                prepare(words, at, &mut prepared);
226                prepared
227            }
228            None => *words,
229        }
230    }
231
232    /// Measures as the element `words` hold does.
233    #[inline]
234    pub fn measure(
235        &self,
236        words: &[u32],
237        context: &mut dyn ModifierNodeContext,
238        measurable: &dyn Measurable,
239        constraints: Constraints,
240    ) -> LayoutModifierMeasureResult {
241        (self.measure)(words, context, measurable, constraints)
242    }
243
244    /// The hold of the last measure of the element `words` hold.
245    pub fn measure_hold(
246        &self,
247        words: &[u32],
248        density: f32,
249        constraints: Constraints,
250        size: Size,
251        wrapped: WrappedHold,
252    ) -> Option<ConstraintsHold> {
253        (self.measure_hold)(words, density, constraints, size, wrapped)
254    }
255
256    /// The intrinsic size `kind` names of the element `words` hold.
257    pub fn intrinsic(
258        &self,
259        words: &[u32],
260        measurable: &dyn Measurable,
261        kind: PlainIntrinsic,
262        density: f32,
263    ) -> f32 {
264        (self.intrinsic)(words, measurable, kind, density)
265    }
266}
267
268/// What a chain keeps of a plain element's type beside its words: how many
269/// they are, what the element takes part in, and how to read them.
270pub struct PlainFns {
271    element_type: TypeId,
272    words: u8,
273    capabilities: NodeCapabilities,
274    update_invalidation: Option<InvalidationKind>,
275    layout: Option<&'static PlainLayoutFns>,
276    type_name: fn() -> &'static str,
277    inspector_name: fn(&[u32]) -> &'static str,
278    inspector_properties: fn(&[u32], &mut dyn FnMut(&'static str, String)),
279}
280
281impl fmt::Debug for PlainFns {
282    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
283        f.debug_struct("PlainFns").finish_non_exhaustive()
284    }
285}
286
287impl PlainFns {
288    /// The type of the element the words hold.
289    pub fn element_type(&self) -> TypeId {
290        self.element_type
291    }
292
293    /// How many words the element's value takes.
294    pub fn words(&self) -> usize {
295        usize::from(self.words)
296    }
297
298    /// What the element takes part in.
299    pub fn capabilities(&self) -> NodeCapabilities {
300        self.capabilities
301    }
302
303    /// How the element measures, when it does.
304    pub fn layout(&self) -> Option<&'static PlainLayoutFns> {
305        self.layout
306    }
307
308    /// The name of the element's type.
309    pub fn type_name(&self) -> &'static str {
310        (self.type_name)()
311    }
312
313    pub(in super::super) fn hash_code(&self, words: &[u32]) -> u64 {
314        hash_words(words)
315    }
316
317    pub(in super::super) fn element(&'static self, words: &[u32]) -> DynModifierElement {
318        DynModifierElement::plain(PlainWords::new(self, words))
319    }
320
321    /// The element `words` hold, when it is an `E`.
322    #[inline]
323    pub fn read<E: PlainElement>(&self, words: &[u32]) -> Option<E> {
324        (self.element_type() == TypeId::of::<E>()).then(|| E::from_words(words))
325    }
326}
327
328struct FnsOf<E>(PhantomData<fn() -> E>);
329
330impl<E: PlainElement> FnsOf<E> {
331    const WORDS: u8 = {
332        assert!(E::WORDS <= PLAIN_WORDS_MAX, "a plain element's words fit");
333        E::WORDS as u8
334    };
335
336    const FNS: PlainFns = PlainFns {
337        element_type: TypeId::of::<E>(),
338        words: Self::WORDS,
339        capabilities: E::CAPABILITIES,
340        update_invalidation: E::UPDATE_INVALIDATION,
341        layout: E::LAYOUT,
342        type_name: type_name::<E>,
343        inspector_name: |words| E::from_words(words).inspector_name(),
344        inspector_properties: |words, inspector| {
345            E::from_words(words).inspector_properties(inspector);
346        },
347    };
348}
349
350// The hash of a plain element: of its words, in one function for every
351// type, as two elements compare.
352fn hash_words(words: &[u32]) -> u64 {
353    let mut hasher = default::new();
354    for &word in words {
355        hasher.write_u32(word);
356    }
357    hasher.finish()
358}
359
360// Whether two plain elements of one type hold an equal value: equal words,
361// as Compose's data classes compare a float by its bits (the two zeros
362// differ, a NaN equals itself). The words of a value number five at most,
363// so the comparison folds them inline rather than calling `memcmp`.
364fn same_words(a: &[u32], b: &[u32]) -> bool {
365    a.len() == b.len() && a.iter().zip(b).fold(0, |differ, (&x, &y)| differ | (x ^ y)) == 0
366}
367
368/// A plain element as a chain reads it: its type's table, and its value as
369/// words.
370pub trait PlainValue {
371    /// The table of the element's type.
372    fn fns(&self) -> &'static PlainFns;
373
374    /// Writes the value into `words`, as many as the table tells.
375    fn write_words(&self, words: &mut [u32]);
376
377    /// Whether `words`, written by an element of this type, hold a value
378    /// equal to this one, as the element type compares.
379    fn equals_words(&self, words: &[u32]) -> bool;
380}
381
382// A plain element's value as a modifier holds it in place of an
383// allocation: its type's table and its words, those past the value's own
384// zero.
385#[derive(Clone, Copy)]
386pub(crate) struct PlainWords {
387    fns: &'static PlainFns,
388    words: [u32; PLAIN_WORDS_MAX],
389    // A byte that holds one value, in the room after the words: the enums
390    // around the value, a modifier's element and a modifier of one element
391    // or of several, keep their tags in the values it never holds and stay
392    // as large as the value.
393    #[expect(dead_code, reason = "its use is the values it never holds")]
394    room: Room,
395}
396
397#[derive(Clone, Copy)]
398#[repr(u8)]
399enum Room {
400    Zero = 0,
401}
402
403impl PlainWords {
404    pub(crate) fn new(fns: &'static PlainFns, words: &[u32]) -> Self {
405        let mut held = [0; PLAIN_WORDS_MAX];
406        held[..words.len()].copy_from_slice(words);
407        Self {
408            fns,
409            words: held,
410            room: Room::Zero,
411        }
412    }
413
414    fn of<E: PlainElement>(element: &E) -> Self {
415        let mut words = [0; PLAIN_WORDS_MAX];
416        element.to_words(&mut words[..E::WORDS]);
417        Self {
418            fns: &FnsOf::<E>::FNS,
419            words,
420            room: Room::Zero,
421        }
422    }
423
424    pub(crate) fn words(&self) -> &[u32] {
425        &self.words[..self.fns.words()]
426    }
427}
428
429// The type alone, as the wrapper of a node's element prints: the values
430// would bring each element's formatting into every image.
431impl fmt::Debug for PlainWords {
432    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
433        f.write_str(self.fns.type_name())
434    }
435}
436
437impl PlainValue for PlainWords {
438    fn fns(&self) -> &'static PlainFns {
439        self.fns
440    }
441
442    fn write_words(&self, words: &mut [u32]) {
443        words.copy_from_slice(self.words());
444    }
445
446    fn equals_words(&self, words: &[u32]) -> bool {
447        same_words(self.words(), words)
448    }
449}
450
451impl AnyModifierElement for PlainWords {
452    fn element_type(&self) -> TypeId {
453        self.fns.element_type()
454    }
455
456    fn maker(&self) -> ElementMaker<'_> {
457        ElementMaker::Plain(self)
458    }
459
460    fn key(&self) -> Option<u64> {
461        None
462    }
463
464    fn capabilities(&self) -> NodeCapabilities {
465        self.fns.capabilities
466    }
467
468    fn hash_code(&self) -> u64 {
469        hash_words(self.words())
470    }
471
472    fn equals_element(&self, other: &dyn AnyModifierElement) -> bool {
473        other.equals_plain(self.fns, self.words())
474    }
475
476    fn inspector_name(&self) -> &'static str {
477        (self.fns.inspector_name)(self.words())
478    }
479
480    fn record_inspector_properties(&self, visitor: &mut dyn FnMut(&'static str, String)) {
481        (self.fns.inspector_properties)(self.words(), visitor);
482    }
483
484    fn requires_update(&self) -> bool {
485        false
486    }
487
488    fn auto_invalidates_on_update(&self) -> bool {
489        true
490    }
491
492    fn update_invalidation_kind(&self) -> Option<InvalidationKind> {
493        self.fns.update_invalidation
494    }
495
496    fn provided_composition_locals(&self) -> Vec<ProvidedValue> {
497        Vec::new()
498    }
499
500    fn as_any(&self) -> &dyn Any {
501        self
502    }
503
504    fn equals_plain(&self, fns: &PlainFns, words: &[u32]) -> bool {
505        // The same table tells the same type without a call; two tables of
506        // one type may still differ in address.
507        (std::ptr::eq(fns, self.fns) || fns.element_type() == self.fns.element_type())
508            && same_words(self.words(), words)
509    }
510}
511
512/// The type-erased element of a plain `element`, a copy of its value.
513// One copy for each element type: a modifier builder inlined into an app's
514// body then holds a call, not the writing of the element's words.
515#[inline(never)]
516pub fn plain_element<E: PlainElement>(element: &E) -> DynModifierElement {
517    DynModifierElement::plain(PlainWords::of(element))
518}