use std::{
any::{Any, TypeId, type_name},
fmt,
hash::Hasher,
marker::PhantomData,
};
use cranpose_core::{ProvidedValue, hash::default};
use cranpose_ui_layout::{
ConstraintsHold, LayoutDirection, LayoutModifierMeasureResult, WrappedHold,
};
use super::super::{
AnyModifierElement, Constraints, DynModifierElement, ElementMaker, InvalidationKind,
Measurable, ModifierNodeContext, NodeCapabilities, Size,
};
pub const PLAIN_WORDS_MAX: usize = 5;
pub trait PlainElement: fmt::Debug + PartialEq + Sized + 'static {
const WORDS: usize;
const CAPABILITIES: NodeCapabilities;
const UPDATE_INVALIDATION: Option<InvalidationKind> = None;
fn to_words(&self, words: &mut [u32]);
fn from_words(words: &[u32]) -> Self;
const LAYOUT: Option<&'static PlainLayoutFns> = None;
fn inspector_name(&self) -> &'static str {
type_name::<Self>()
}
fn inspector_properties(&self, _inspector: &mut dyn FnMut(&'static str, String)) {}
}
pub trait PlainLayout: PlainElement {
fn measure(
&self,
context: &mut dyn ModifierNodeContext,
measurable: &dyn Measurable,
constraints: Constraints,
) -> LayoutModifierMeasureResult;
fn prepared(self, _at: PrepareAt) -> Self {
self
}
const PREPARES: bool = false;
fn measure_hold(
&self,
_density: f32,
_constraints: Constraints,
_size: Size,
_wrapped: WrappedHold,
) -> Option<ConstraintsHold> {
None
}
fn intrinsic(&self, measurable: &dyn Measurable, kind: PlainIntrinsic, _density: f32) -> f32 {
kind.of(measurable)
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PrepareAt {
pub density: f32,
pub direction: LayoutDirection,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PlainIntrinsic {
MinWidth(f32),
MaxWidth(f32),
MinHeight(f32),
MaxHeight(f32),
}
impl PlainIntrinsic {
pub fn of(self, measurable: &dyn Measurable) -> f32 {
match self {
Self::MinWidth(height) => measurable.min_intrinsic_width(height),
Self::MaxWidth(height) => measurable.max_intrinsic_width(height),
Self::MinHeight(width) => measurable.min_intrinsic_height(width),
Self::MaxHeight(width) => measurable.max_intrinsic_height(width),
}
}
pub fn cross(self) -> f32 {
match self {
Self::MinWidth(cross)
| Self::MaxWidth(cross)
| Self::MinHeight(cross)
| Self::MaxHeight(cross) => cross,
}
}
pub fn at(self, cross: f32) -> Self {
match self {
Self::MinWidth(_) => Self::MinWidth(cross),
Self::MaxWidth(_) => Self::MaxWidth(cross),
Self::MinHeight(_) => Self::MinHeight(cross),
Self::MaxHeight(_) => Self::MaxHeight(cross),
}
}
pub fn is_width(self) -> bool {
matches!(self, Self::MinWidth(_) | Self::MaxWidth(_))
}
}
type PrepareFn = fn(&[u32], PrepareAt, &mut [u32]);
type MeasureFn = fn(
&[u32],
&mut dyn ModifierNodeContext,
&dyn Measurable,
Constraints,
) -> LayoutModifierMeasureResult;
pub struct PlainLayoutFns {
prepare: Option<PrepareFn>,
measure: MeasureFn,
measure_hold: fn(&[u32], f32, Constraints, Size, WrappedHold) -> Option<ConstraintsHold>,
intrinsic: fn(&[u32], &dyn Measurable, PlainIntrinsic, f32) -> f32,
}
impl fmt::Debug for PlainLayoutFns {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PlainLayoutFns").finish_non_exhaustive()
}
}
impl PlainLayoutFns {
pub const fn of<E: PlainLayout>() -> Self {
Self {
prepare: if E::PREPARES {
Some(|words, at, prepared| {
E::from_words(words)
.prepared(at)
.to_words(&mut prepared[..E::WORDS]);
})
} else {
None
},
measure: |words, context, measurable, constraints| {
E::from_words(words).measure(context, measurable, constraints)
},
measure_hold: |words, density, constraints, size, wrapped| {
E::from_words(words).measure_hold(density, constraints, size, wrapped)
},
intrinsic: |words, measurable, kind, density| {
E::from_words(words).intrinsic(measurable, kind, density)
},
}
}
#[inline]
pub fn prepare(&self, words: &[u32; PLAIN_WORDS_MAX], at: PrepareAt) -> [u32; PLAIN_WORDS_MAX] {
match self.prepare {
Some(prepare) => {
let mut prepared = [0; PLAIN_WORDS_MAX];
prepare(words, at, &mut prepared);
prepared
}
None => *words,
}
}
#[inline]
pub fn measure(
&self,
words: &[u32],
context: &mut dyn ModifierNodeContext,
measurable: &dyn Measurable,
constraints: Constraints,
) -> LayoutModifierMeasureResult {
(self.measure)(words, context, measurable, constraints)
}
pub fn measure_hold(
&self,
words: &[u32],
density: f32,
constraints: Constraints,
size: Size,
wrapped: WrappedHold,
) -> Option<ConstraintsHold> {
(self.measure_hold)(words, density, constraints, size, wrapped)
}
pub fn intrinsic(
&self,
words: &[u32],
measurable: &dyn Measurable,
kind: PlainIntrinsic,
density: f32,
) -> f32 {
(self.intrinsic)(words, measurable, kind, density)
}
}
pub struct PlainFns {
element_type: TypeId,
words: u8,
capabilities: NodeCapabilities,
update_invalidation: Option<InvalidationKind>,
layout: Option<&'static PlainLayoutFns>,
type_name: fn() -> &'static str,
inspector_name: fn(&[u32]) -> &'static str,
inspector_properties: fn(&[u32], &mut dyn FnMut(&'static str, String)),
}
impl fmt::Debug for PlainFns {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PlainFns").finish_non_exhaustive()
}
}
impl PlainFns {
pub fn element_type(&self) -> TypeId {
self.element_type
}
pub fn words(&self) -> usize {
usize::from(self.words)
}
pub fn capabilities(&self) -> NodeCapabilities {
self.capabilities
}
pub fn layout(&self) -> Option<&'static PlainLayoutFns> {
self.layout
}
pub fn type_name(&self) -> &'static str {
(self.type_name)()
}
pub(in super::super) fn hash_code(&self, words: &[u32]) -> u64 {
hash_words(words)
}
pub(in super::super) fn element(&'static self, words: &[u32]) -> DynModifierElement {
DynModifierElement::plain(PlainWords::new(self, words))
}
#[inline]
pub fn read<E: PlainElement>(&self, words: &[u32]) -> Option<E> {
(self.element_type() == TypeId::of::<E>()).then(|| E::from_words(words))
}
}
struct FnsOf<E>(PhantomData<fn() -> E>);
impl<E: PlainElement> FnsOf<E> {
const WORDS: u8 = {
assert!(E::WORDS <= PLAIN_WORDS_MAX, "a plain element's words fit");
E::WORDS as u8
};
const FNS: PlainFns = PlainFns {
element_type: TypeId::of::<E>(),
words: Self::WORDS,
capabilities: E::CAPABILITIES,
update_invalidation: E::UPDATE_INVALIDATION,
layout: E::LAYOUT,
type_name: type_name::<E>,
inspector_name: |words| E::from_words(words).inspector_name(),
inspector_properties: |words, inspector| {
E::from_words(words).inspector_properties(inspector);
},
};
}
fn hash_words(words: &[u32]) -> u64 {
let mut hasher = default::new();
for &word in words {
hasher.write_u32(word);
}
hasher.finish()
}
fn same_words(a: &[u32], b: &[u32]) -> bool {
a.len() == b.len() && a.iter().zip(b).fold(0, |differ, (&x, &y)| differ | (x ^ y)) == 0
}
pub trait PlainValue {
fn fns(&self) -> &'static PlainFns;
fn write_words(&self, words: &mut [u32]);
fn equals_words(&self, words: &[u32]) -> bool;
}
#[derive(Clone, Copy)]
pub(crate) struct PlainWords {
fns: &'static PlainFns,
words: [u32; PLAIN_WORDS_MAX],
#[expect(dead_code, reason = "its use is the values it never holds")]
room: Room,
}
#[derive(Clone, Copy)]
#[repr(u8)]
enum Room {
Zero = 0,
}
impl PlainWords {
pub(crate) fn new(fns: &'static PlainFns, words: &[u32]) -> Self {
let mut held = [0; PLAIN_WORDS_MAX];
held[..words.len()].copy_from_slice(words);
Self {
fns,
words: held,
room: Room::Zero,
}
}
fn of<E: PlainElement>(element: &E) -> Self {
let mut words = [0; PLAIN_WORDS_MAX];
element.to_words(&mut words[..E::WORDS]);
Self {
fns: &FnsOf::<E>::FNS,
words,
room: Room::Zero,
}
}
pub(crate) fn words(&self) -> &[u32] {
&self.words[..self.fns.words()]
}
}
impl fmt::Debug for PlainWords {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.fns.type_name())
}
}
impl PlainValue for PlainWords {
fn fns(&self) -> &'static PlainFns {
self.fns
}
fn write_words(&self, words: &mut [u32]) {
words.copy_from_slice(self.words());
}
fn equals_words(&self, words: &[u32]) -> bool {
same_words(self.words(), words)
}
}
impl AnyModifierElement for PlainWords {
fn element_type(&self) -> TypeId {
self.fns.element_type()
}
fn maker(&self) -> ElementMaker<'_> {
ElementMaker::Plain(self)
}
fn key(&self) -> Option<u64> {
None
}
fn capabilities(&self) -> NodeCapabilities {
self.fns.capabilities
}
fn hash_code(&self) -> u64 {
hash_words(self.words())
}
fn equals_element(&self, other: &dyn AnyModifierElement) -> bool {
other.equals_plain(self.fns, self.words())
}
fn inspector_name(&self) -> &'static str {
(self.fns.inspector_name)(self.words())
}
fn record_inspector_properties(&self, visitor: &mut dyn FnMut(&'static str, String)) {
(self.fns.inspector_properties)(self.words(), visitor);
}
fn requires_update(&self) -> bool {
false
}
fn auto_invalidates_on_update(&self) -> bool {
true
}
fn update_invalidation_kind(&self) -> Option<InvalidationKind> {
self.fns.update_invalidation
}
fn provided_composition_locals(&self) -> Vec<ProvidedValue> {
Vec::new()
}
fn as_any(&self) -> &dyn Any {
self
}
fn equals_plain(&self, fns: &PlainFns, words: &[u32]) -> bool {
(std::ptr::eq(fns, self.fns) || fns.element_type() == self.fns.element_type())
&& same_words(self.words(), words)
}
}
#[inline(never)]
pub fn plain_element<E: PlainElement>(element: &E) -> DynModifierElement {
DynModifierElement::plain(PlainWords::of(element))
}