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