use std::{
any::{Any, TypeId, type_name},
fmt,
hash::Hasher,
marker::PhantomData,
rc::Rc,
};
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: fn() -> TypeId,
words: u8,
capabilities: NodeCapabilities,
layout: Option<&'static PlainLayoutFns>,
type_name: fn() -> &'static str,
element: fn(&[u32]) -> DynModifierElement,
}
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(&self, words: &[u32]) -> DynModifierElement {
(self.element)(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,
layout: E::LAYOUT,
type_name: type_name::<E>,
element: |words| plain_element(E::from_words(words)),
};
}
fn hash_words(words: &[u32]) -> u64 {
let mut hasher = default::new();
for &word in words {
hasher.write_u32(word);
}
hasher.finish()
}
pub trait PlainValue {
fn fns(&self) -> &'static PlainFns;
fn write_words(&self, words: &mut [u32]);
fn equals_words(&self, words: &[u32]) -> bool;
}
struct TypedPlainElement<E: PlainElement>(E);
impl<E: PlainElement> fmt::Debug for TypedPlainElement<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TypedPlainElement")
.field("type", &type_name::<E>())
.finish()
}
}
impl<E: PlainElement> PlainValue for TypedPlainElement<E> {
fn fns(&self) -> &'static PlainFns {
&FnsOf::<E>::FNS
}
fn write_words(&self, words: &mut [u32]) {
self.0.to_words(words);
}
fn equals_words(&self, words: &[u32]) -> bool {
E::from_words(words) == self.0
}
}
impl<E: PlainElement> AnyModifierElement for TypedPlainElement<E> {
fn element_type(&self) -> TypeId {
TypeId::of::<E>()
}
fn maker(&self) -> ElementMaker<'_> {
ElementMaker::Plain(self)
}
fn key(&self) -> Option<u64> {
None
}
fn capabilities(&self) -> NodeCapabilities {
E::CAPABILITIES
}
fn hash_code(&self) -> u64 {
let mut words = [0; PLAIN_WORDS_MAX];
let words = &mut words[..E::WORDS];
self.0.to_words(words);
hash_words(words)
}
fn equals_element(&self, other: &dyn AnyModifierElement) -> bool {
other
.as_any()
.downcast_ref::<Self>()
.is_some_and(|typed| typed.0 == self.0)
}
fn inspector_name(&self) -> &'static str {
self.0.inspector_name()
}
fn record_inspector_properties(&self, visitor: &mut dyn FnMut(&'static str, String)) {
self.0.inspector_properties(visitor);
}
fn requires_update(&self) -> bool {
false
}
fn auto_invalidates_on_update(&self) -> bool {
true
}
fn update_invalidation_kind(&self) -> Option<InvalidationKind> {
E::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() == TypeId::of::<E>())
&& E::from_words(words) == self.0
}
}
pub fn plain_element<E: PlainElement>(element: E) -> DynModifierElement {
Rc::new(TypedPlainElement(element))
}