use std::cmp::Ordering;
use std::sync::Arc;
use crate::conversion::to_value::make_transition_style_property;
use crate::conversion::{Converter, Convertible, Error};
use crate::expression::Functions;
use crate::feature::{Value, ValueObject};
use crate::layer::PropertyScope;
use crate::property::set::Transitionable;
use crate::property::transition::TransitionOptions;
use crate::property::value::StyleValue;
#[derive(Debug)]
pub struct PropertyInfo {
pub(crate) name: &'static str,
pub(crate) scope: PropertyScope,
pub(crate) data_driven: bool,
pub(crate) tokens: bool,
pub(crate) overridable: bool,
pub(crate) cross_faded: bool,
}
impl PropertyInfo {
#[must_use]
pub const fn paint(name: &'static str) -> Self {
PropertyInfo {
name,
scope: PropertyScope::Paint,
data_driven: false,
tokens: false,
overridable: false,
cross_faded: false,
}
}
#[must_use]
pub const fn layout(name: &'static str) -> Self {
PropertyInfo {
name,
scope: PropertyScope::Layout,
data_driven: false,
tokens: false,
overridable: false,
cross_faded: false,
}
}
#[must_use]
pub const fn data_driven(self) -> Self {
PropertyInfo { data_driven: true, ..self }
}
#[must_use]
pub const fn tokens(self) -> Self {
PropertyInfo { tokens: true, ..self }
}
#[must_use]
pub const fn overridable(self) -> Self {
PropertyInfo { overridable: true, ..self }
}
#[must_use]
pub const fn cross_faded(self) -> Self {
PropertyInfo { cross_faded: true, ..self }
}
}
#[doc(hidden)]
#[must_use]
pub const fn property_name<const N: usize>(field: &str) -> [u8; N] {
let field = field.as_bytes();
assert!(field.len() == N, "the length is the field's");
let mut name = [0; N];
let mut i = 0;
while i < N {
name[i] = if field[i] == b'_' { b'-' } else { field[i] };
i += 1;
}
name
}
#[doc(hidden)]
#[must_use]
pub const fn slots_by_name<const N: usize>(properties: &[PropertyInfo; N]) -> [u8; N] {
assert!(N <= 256, "a table has at most 256 properties");
let mut slots = [0; N];
let mut i = 0;
while i < N {
slots[i] = i as u8;
let mut j = i;
while j > 0 {
let order = compare(properties[slots[j - 1] as usize].name, properties[slots[j] as usize].name);
assert!(!matches!(order, Ordering::Equal), "two properties have the same name");
if matches!(order, Ordering::Less) {
break;
}
let previous = slots[j - 1];
slots[j - 1] = slots[j];
slots[j] = previous;
j -= 1;
}
i += 1;
}
slots
}
const fn compare(a: &str, b: &str) -> Ordering {
let (a, b) = (a.as_bytes(), b.as_bytes());
let mut i = 0;
while i < a.len() && i < b.len() {
if a[i] != b[i] {
return if a[i] < b[i] { Ordering::Less } else { Ordering::Greater };
}
i += 1;
}
if a.len() < b.len() {
Ordering::Less
} else if a.len() > b.len() {
Ordering::Greater
} else {
Ordering::Equal
}
}
#[derive(Debug)]
pub struct PropertyTable {
properties: &'static [PropertyInfo],
by_name: &'static [u8],
}
impl PropertyTable {
#[must_use]
pub const fn new(properties: &'static [PropertyInfo], by_name: &'static [u8]) -> Self {
PropertyTable { properties, by_name }
}
#[must_use]
pub(crate) fn find(&self, name: &str) -> Option<usize> {
let index = self.by_name.binary_search_by(|&slot| self.properties[usize::from(slot)].name.cmp(name)).ok()?;
Some(usize::from(self.by_name[index]))
}
fn resolve(&self, name: &str) -> Option<(usize, bool)> {
if let Some(slot) = self.find(name) {
return Some((slot, false));
}
let slot = self.find(name.strip_suffix("-transition")?)?;
(self.properties[slot].scope == PropertyScope::Paint).then_some((slot, true))
}
}
pub trait PropertyVisitor<S> {
type Output;
fn paint<V: StyleValue>(
self,
get: fn(&S) -> &Transitionable<V>,
get_mut: fn(&mut S) -> &mut Transitionable<V>,
) -> Self::Output;
fn layout<V: StyleValue>(self, get: fn(&S) -> &V, get_mut: fn(&mut S) -> &mut V) -> Self::Output;
}
pub(crate) trait Properties: Clone + 'static {
const TABLE: &'static PropertyTable;
fn visit<V: PropertyVisitor<Self>>(slot: usize, visitor: V) -> Option<V::Output>;
}
#[derive(Debug)]
pub enum SetPropertyError {
Unknown,
Invalid(Error),
}
pub(crate) fn property<S: Properties>(owner: &S, name: &str) -> StyleProperty {
match S::TABLE.resolve(name) {
Some((slot, transition)) => style_property(owner, slot, transition),
None => StyleProperty::default(),
}
}
fn style_property<S: Properties>(owner: &S, slot: usize, transition: bool) -> StyleProperty {
struct Get<'a, S> {
owner: &'a S,
transition: bool,
}
impl<S> PropertyVisitor<S> for Get<'_, S> {
type Output = StyleProperty;
fn paint<V: StyleValue>(
self,
get: fn(&S) -> &Transitionable<V>,
_: fn(&mut S) -> &mut Transitionable<V>,
) -> StyleProperty {
paint_style_property(get(self.owner), self.transition)
}
fn layout<V: StyleValue>(self, get: fn(&S) -> &V, _: fn(&mut S) -> &mut V) -> StyleProperty {
get(self.owner).style_property()
}
}
S::visit(slot, Get { owner, transition }).unwrap_or_default()
}
#[inline(never)]
fn paint_style_property<V: StyleValue>(property: &Transitionable<V>, transition: bool) -> StyleProperty {
if transition { make_transition_style_property(&property.options) } else { property.value.style_property() }
}
pub(crate) trait OwnerSlot<S> {
fn get(&self) -> Option<&S>;
fn make_mut(&mut self) -> Option<&mut S>;
}
impl<S: Clone> OwnerSlot<S> for Arc<S> {
fn get(&self) -> Option<&S> {
Some(self)
}
#[inline(never)]
fn make_mut(&mut self) -> Option<&mut S> {
Some(Arc::make_mut(self))
}
}
pub(crate) struct InPlace<'a, S>(pub(crate) &'a mut S);
impl<S> OwnerSlot<S> for InPlace<'_, S> {
fn get(&self) -> Option<&S> {
Some(self.0)
}
fn make_mut(&mut self) -> Option<&mut S> {
Some(self.0)
}
}
pub(crate) fn set_property<S: Properties, O: OwnerSlot<S>>(
owner: &mut O,
name: &str,
value: &Convertible<'_>,
functions: &Arc<Functions>,
) -> Result<(), SetPropertyError> {
struct Set<'a, 'v, O> {
owner: &'a mut O,
value: &'a Convertible<'v>,
functions: &'a Arc<Functions>,
info: &'static PropertyInfo,
transition: bool,
error: &'a mut Option<Error>,
}
impl<S, O: OwnerSlot<S>> PropertyVisitor<S> for Set<'_, '_, O> {
type Output = ();
#[inline(never)]
fn paint<V: StyleValue>(
self,
get: fn(&S) -> &Transitionable<V>,
get_mut: fn(&mut S) -> &mut Transitionable<V>,
) {
let mut change = PaintChange::None;
let Some(current) = self.owner.get() else { return };
if paint_change(
get(current),
self.value,
self.functions,
self.info,
self.transition,
&mut change,
self.error,
) && let Some(owner) = self.owner.make_mut()
{
apply_paint_change(get_mut(owner), &mut change);
}
}
#[inline(never)]
fn layout<V: StyleValue>(self, get: fn(&S) -> &V, get_mut: fn(&mut S) -> &mut V) {
let mut change = None;
let Some(current) = self.owner.get() else { return };
if changed_value(get(current), self.value, self.functions, self.info, &mut change, self.error)
&& let Some(owner) = self.owner.make_mut()
{
store(get_mut(owner), &mut change);
}
}
}
let (slot, transition) = S::TABLE.resolve(name).ok_or(SetPropertyError::Unknown)?;
let info = &S::TABLE.properties[slot];
let mut error = None;
S::visit(slot, Set { owner, value, functions, info, transition, error: &mut error })
.ok_or(SetPropertyError::Unknown)?;
error.map_or(Ok(()), |error| Err(SetPropertyError::Invalid(error)))
}
#[inline(never)]
fn changed_value<V: StyleValue>(
current: &V,
value: &Convertible<'_>,
functions: &Arc<Functions>,
info: &PropertyInfo,
change: &mut Option<V>,
error: &mut Option<Error>,
) -> bool {
match V::convert(value, info, functions) {
Ok(value) if *current != value => {
*change = Some(value);
true
}
Ok(_) => false,
Err(e) => {
*error = Some(e);
false
}
}
}
enum PaintChange<V> {
None,
Value(V),
Options(TransitionOptions),
}
#[inline(never)]
fn paint_change<V: StyleValue>(
current: &Transitionable<V>,
value: &Convertible<'_>,
functions: &Arc<Functions>,
info: &PropertyInfo,
transition: bool,
change: &mut PaintChange<V>,
error: &mut Option<Error>,
) -> bool {
if transition {
let mut conversion_error = Error::default();
match <TransitionOptions as Converter>::convert(value, &mut conversion_error) {
Some(options) if current.options != options => *change = PaintChange::Options(options),
Some(_) => {}
None => *error = Some(conversion_error),
}
} else {
let mut new_value = None;
changed_value(¤t.value, value, functions, info, &mut new_value, error);
if let Some(value) = new_value {
*change = PaintChange::Value(value);
}
}
!matches!(change, PaintChange::None)
}
#[inline(never)]
fn apply_paint_change<V>(property: &mut Transitionable<V>, change: &mut PaintChange<V>) {
match std::mem::replace(change, PaintChange::None) {
PaintChange::None => {}
PaintChange::Value(value) => property.value = value,
PaintChange::Options(options) => property.options = options,
}
}
#[inline(never)]
fn store<V>(slot: &mut V, change: &mut Option<V>) {
if let Some(value) = change.take() {
*slot = value;
}
}
pub(crate) fn layout_properties_differ<S: Properties>(a: &S, b: &S, section_overrides: bool) -> bool {
#[derive(Clone, Copy)]
struct Checks {
any: bool,
data_driven: bool,
constant: bool,
}
struct Differs<'a, S> {
a: &'a S,
b: &'a S,
checks: Checks,
}
impl<S> PropertyVisitor<S> for Differs<'_, S> {
type Output = bool;
fn paint<V: StyleValue>(
self,
get: fn(&S) -> &Transitionable<V>,
_: fn(&mut S) -> &mut Transitionable<V>,
) -> bool {
values_differ(&get(self.a).value, &get(self.b).value, self.checks)
}
fn layout<V: StyleValue>(self, get: fn(&S) -> &V, _: fn(&mut S) -> &mut V) -> bool {
values_differ(get(self.a), get(self.b), self.checks)
}
}
#[inline(never)]
fn values_differ<V: StyleValue>(a: &V, b: &V, checks: Checks) -> bool {
(checks.any && a != b)
|| (checks.data_driven && a.has_data_driven_property_difference(b))
|| (checks.constant && a.constant_differs(b))
}
S::TABLE.properties.iter().enumerate().any(|(slot, info)| {
let checks = Checks {
any: info.scope == PropertyScope::Layout || info.cross_faded,
data_driven: info.data_driven,
constant: section_overrides && info.overridable,
};
(checks.any || checks.data_driven || checks.constant)
&& S::visit(slot, Differs { a, b, checks }).unwrap_or_default()
})
}
pub(crate) fn defined_properties<S: Properties>(owner: &S) -> Vec<(String, PropertyScope, StyleProperty)> {
defined_properties_in(S::TABLE, &|slot, transition| style_property(owner, slot, transition))
}
fn defined_properties_in(
table: &PropertyTable,
get: &dyn Fn(usize, bool) -> StyleProperty,
) -> Vec<(String, PropertyScope, StyleProperty)> {
let table = table.properties;
let mut defined = Vec::new();
let paint = table.iter().enumerate().filter(|(_, info)| info.scope == PropertyScope::Paint);
let layout = table.iter().enumerate().filter(|(_, info)| info.scope == PropertyScope::Layout);
let values = paint.clone().map(|(slot, info)| (slot, info, false));
let transitions = paint.map(|(slot, info)| (slot, info, true));
let layout = layout.map(|(slot, info)| (slot, info, false));
for (slot, info, transition) in values.chain(transitions).chain(layout) {
let property = get(slot, transition);
if property.kind() == Kind::Undefined {
continue;
}
let name = if transition { format!("{}-transition", info.name) } else { info.name.to_owned() };
defined.push((name, info.scope, property));
}
defined
}
pub(crate) fn serialize_properties<S: Properties>(owner: &S, out: &mut ValueObject) {
insert_properties(defined_properties(owner), out);
}
fn insert_properties(defined: Vec<(String, PropertyScope, StyleProperty)>, out: &mut ValueObject) {
for (name, scope, property) in defined {
let key = match scope {
PropertyScope::Paint => "paint",
PropertyScope::Layout => "layout",
};
if let Some(Value::Object(existing)) = out.get_mut(key) {
existing.entry(name).or_insert_with(|| property.value().clone());
} else {
let mut inner = ValueObject::new();
inner.insert(name, property.value().clone());
out.insert(key.to_owned(), Value::Object(inner));
}
}
}
pub(crate) fn names<S: Properties>() -> impl Iterator<Item = String> {
S::TABLE.properties.iter().flat_map(|info| {
let transition = (info.scope == PropertyScope::Paint).then(|| format!("{}-transition", info.name));
std::iter::once(info.name.to_owned()).chain(transition)
})
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[repr(u8)]
pub enum Kind {
#[default]
Undefined,
Constant,
Expression,
Transition,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StyleProperty {
value: Value,
kind: Kind,
}
impl StyleProperty {
#[must_use]
pub(crate) fn new(value: Value, kind: Kind) -> Self {
StyleProperty { value, kind }
}
#[must_use]
pub fn value(&self) -> &Value {
&self.value
}
#[must_use]
pub fn kind(&self) -> Kind {
self.kind
}
}