1use std::cmp::Ordering;
12use std::sync::Arc;
13
14use crate::conversion::to_value::make_transition_style_property;
15use crate::conversion::{Converter, Convertible, Error};
16use crate::expression::Functions;
17use crate::feature::{Value, ValueObject};
18use crate::layer::PropertyScope;
19use crate::property::set::Transitionable;
20use crate::property::transition::PropertyTransition;
21use crate::property::value::StyleValue;
22
23#[derive(Debug)]
25pub struct PropertyInfo {
26 pub(crate) name: &'static str,
28 pub(crate) scope: PropertyScope,
29 pub(crate) data_driven: bool,
31 pub(crate) tokens: bool,
33 pub(crate) overridable: bool,
36 pub(crate) cross_faded: bool,
40 pub(crate) interpolated: bool,
43 pub(crate) elevation: bool,
45}
46
47impl PropertyInfo {
48 #[must_use]
49 pub const fn paint(name: &'static str) -> Self {
50 PropertyInfo {
51 name,
52 scope: PropertyScope::Paint,
53 data_driven: false,
54 tokens: false,
55 overridable: false,
56 cross_faded: false,
57 interpolated: false,
58 elevation: false,
59 }
60 }
61
62 #[must_use]
63 pub const fn layout(name: &'static str) -> Self {
64 PropertyInfo {
65 name,
66 scope: PropertyScope::Layout,
67 data_driven: false,
68 tokens: false,
69 overridable: false,
70 cross_faded: false,
71 interpolated: false,
72 elevation: false,
73 }
74 }
75
76 #[must_use]
77 pub const fn data_driven(self) -> Self {
78 PropertyInfo { data_driven: true, ..self }
79 }
80
81 #[must_use]
82 pub const fn tokens(self) -> Self {
83 PropertyInfo { tokens: true, ..self }
84 }
85
86 #[must_use]
87 pub const fn overridable(self) -> Self {
88 PropertyInfo { overridable: true, ..self }
89 }
90
91 #[must_use]
92 pub const fn cross_faded(self) -> Self {
93 PropertyInfo { cross_faded: true, ..self }
94 }
95
96 #[must_use]
97 pub const fn interpolated(self) -> Self {
98 PropertyInfo { interpolated: true, ..self }
99 }
100
101 #[must_use]
102 pub const fn elevation(self) -> Self {
103 PropertyInfo { elevation: true, ..self }
104 }
105}
106
107#[doc(hidden)]
110#[must_use]
111pub const fn property_name<const N: usize>(field: &str) -> [u8; N] {
112 let field = field.as_bytes();
113 assert!(field.len() == N, "the length is the field's");
114 let mut name = [0; N];
115 let mut i = 0;
116 while i < N {
117 name[i] = if field[i] == b'_' { b'-' } else { field[i] };
118 i += 1;
119 }
120 name
121}
122
123#[doc(hidden)]
127#[must_use]
128pub const fn slots_by_name<const N: usize>(properties: &[PropertyInfo; N]) -> [u8; N] {
129 assert!(N <= 256, "a table has at most 256 properties");
130 let mut slots = [0; N];
131 let mut i = 0;
132 while i < N {
133 slots[i] = i as u8;
134 let mut j = i;
136 while j > 0 {
137 let order = compare(properties[slots[j - 1] as usize].name, properties[slots[j] as usize].name);
138 assert!(!matches!(order, Ordering::Equal), "two properties have the same name");
139 if matches!(order, Ordering::Less) {
140 break;
141 }
142 let previous = slots[j - 1];
143 slots[j - 1] = slots[j];
144 slots[j] = previous;
145 j -= 1;
146 }
147 i += 1;
148 }
149 slots
150}
151
152const fn compare(a: &str, b: &str) -> Ordering {
154 let (a, b) = (a.as_bytes(), b.as_bytes());
155 let mut i = 0;
156 while i < a.len() && i < b.len() {
157 if a[i] != b[i] {
158 return if a[i] < b[i] { Ordering::Less } else { Ordering::Greater };
159 }
160 i += 1;
161 }
162 if a.len() < b.len() {
163 Ordering::Less
164 } else if a.len() > b.len() {
165 Ordering::Greater
166 } else {
167 Ordering::Equal
168 }
169}
170
171#[derive(Debug)]
174pub struct PropertyTable {
175 properties: &'static [PropertyInfo],
176 by_name: &'static [u8],
178}
179
180impl PropertyTable {
181 #[must_use]
183 pub const fn new(properties: &'static [PropertyInfo], by_name: &'static [u8]) -> Self {
184 PropertyTable { properties, by_name }
185 }
186
187 #[must_use]
189 pub(crate) fn find(&self, name: &str) -> Option<usize> {
190 let index = self.by_name.binary_search_by(|&slot| self.properties[usize::from(slot)].name.cmp(name)).ok()?;
191 Some(usize::from(self.by_name[index]))
192 }
193
194 fn resolve(&self, name: &str) -> Option<(usize, bool)> {
197 if let Some(slot) = self.find(name) {
198 return Some((slot, false));
199 }
200 let slot = self.find(name.strip_suffix("-transition")?)?;
201 (self.properties[slot].scope == PropertyScope::Paint).then_some((slot, true))
202 }
203}
204
205pub trait PropertyVisitor<S> {
208 type Output;
209
210 fn paint<V: StyleValue>(
211 self,
212 get: fn(&S) -> &Transitionable<V>,
213 get_mut: fn(&mut S) -> &mut Transitionable<V>,
214 ) -> Self::Output;
215
216 fn layout<V: StyleValue>(self, get: fn(&S) -> &V, get_mut: fn(&mut S) -> &mut V) -> Self::Output;
217}
218
219pub(crate) trait Properties: Clone + 'static {
221 const TABLE: &'static PropertyTable;
222
223 fn visit<V: PropertyVisitor<Self>>(slot: usize, visitor: V) -> Option<V::Output>;
226}
227
228#[derive(Debug)]
230pub enum SetPropertyError {
231 Unknown,
233 Invalid(Error),
235}
236
237pub(crate) fn property<S: Properties>(owner: &S, name: &str) -> StyleProperty {
240 match S::TABLE.resolve(name) {
241 Some((slot, transition)) => style_property(owner, slot, transition),
242 None => StyleProperty::default(),
243 }
244}
245
246fn style_property<S: Properties>(owner: &S, slot: usize, transition: bool) -> StyleProperty {
247 struct Get<'a, S> {
248 owner: &'a S,
249 transition: bool,
250 }
251
252 impl<S> PropertyVisitor<S> for Get<'_, S> {
253 type Output = StyleProperty;
254
255 fn paint<V: StyleValue>(
256 self,
257 get: fn(&S) -> &Transitionable<V>,
258 _: fn(&mut S) -> &mut Transitionable<V>,
259 ) -> StyleProperty {
260 paint_style_property(get(self.owner), self.transition)
261 }
262
263 fn layout<V: StyleValue>(self, get: fn(&S) -> &V, _: fn(&mut S) -> &mut V) -> StyleProperty {
264 get(self.owner).style_property()
265 }
266 }
267
268 S::visit(slot, Get { owner, transition }).unwrap_or_default()
269}
270
271#[inline(never)]
278fn paint_style_property<V: StyleValue>(property: &Transitionable<V>, transition: bool) -> StyleProperty {
279 if transition { make_transition_style_property(&property.options) } else { property.value.style_property() }
280}
281
282pub(crate) trait OwnerSlot<S> {
285 fn get(&self) -> Option<&S>;
287
288 fn make_mut(&mut self) -> Option<&mut S>;
290}
291
292impl<S: Clone> OwnerSlot<S> for Arc<S> {
293 fn get(&self) -> Option<&S> {
294 Some(self)
295 }
296
297 #[inline(never)]
298 fn make_mut(&mut self) -> Option<&mut S> {
299 Some(Arc::make_mut(self))
300 }
301}
302
303pub(crate) struct InPlace<'a, S>(pub(crate) &'a mut S);
305
306impl<S> OwnerSlot<S> for InPlace<'_, S> {
307 fn get(&self) -> Option<&S> {
308 Some(self.0)
309 }
310
311 fn make_mut(&mut self) -> Option<&mut S> {
312 Some(self.0)
313 }
314}
315
316pub(crate) fn set_property<S: Properties, O: OwnerSlot<S>>(
321 owner: &mut O,
322 name: &str,
323 value: &Convertible<'_>,
324 functions: &Arc<Functions>,
325) -> Result<(), SetPropertyError> {
326 struct Set<'a, 'v, O> {
327 owner: &'a mut O,
328 value: &'a Convertible<'v>,
329 functions: &'a Arc<Functions>,
330 info: &'static PropertyInfo,
331 transition: bool,
332 error: &'a mut Option<Error>,
333 }
334
335 impl<S, O: OwnerSlot<S>> PropertyVisitor<S> for Set<'_, '_, O> {
339 type Output = ();
340
341 #[inline(never)]
342 fn paint<V: StyleValue>(
343 self,
344 get: fn(&S) -> &Transitionable<V>,
345 get_mut: fn(&mut S) -> &mut Transitionable<V>,
346 ) {
347 let mut change = PaintChange::None;
348 let Some(current) = self.owner.get() else { return };
349 if paint_change(
350 get(current),
351 self.value,
352 self.functions,
353 self.info,
354 self.transition,
355 &mut change,
356 self.error,
357 ) && let Some(owner) = self.owner.make_mut()
358 {
359 apply_paint_change(get_mut(owner), &mut change);
360 }
361 }
362
363 #[inline(never)]
364 fn layout<V: StyleValue>(self, get: fn(&S) -> &V, get_mut: fn(&mut S) -> &mut V) {
365 let mut change = None;
366 let Some(current) = self.owner.get() else { return };
367 if changed_value(get(current), self.value, self.functions, self.info, &mut change, self.error)
368 && let Some(owner) = self.owner.make_mut()
369 {
370 store(get_mut(owner), &mut change);
371 }
372 }
373 }
374
375 let (slot, transition) = S::TABLE.resolve(name).ok_or(SetPropertyError::Unknown)?;
376 let info = &S::TABLE.properties[slot];
377 let mut error = None;
378 S::visit(slot, Set { owner, value, functions, info, transition, error: &mut error })
379 .ok_or(SetPropertyError::Unknown)?;
380 error.map_or(Ok(()), |error| Err(SetPropertyError::Invalid(error)))
381}
382
383#[inline(never)]
387fn changed_value<V: StyleValue>(
388 current: &V,
389 value: &Convertible<'_>,
390 functions: &Arc<Functions>,
391 info: &PropertyInfo,
392 change: &mut Option<V>,
393 error: &mut Option<Error>,
394) -> bool {
395 match V::convert(value, info, functions) {
396 Ok(value) if *current != value => {
397 *change = Some(value);
398 true
399 }
400 Ok(_) => false,
401 Err(e) => {
402 *error = Some(e);
403 false
404 }
405 }
406}
407
408enum PaintChange<V> {
410 None,
411 Value(V),
412 Options(PropertyTransition),
413}
414
415#[inline(never)]
419fn paint_change<V: StyleValue>(
420 current: &Transitionable<V>,
421 value: &Convertible<'_>,
422 functions: &Arc<Functions>,
423 info: &PropertyInfo,
424 transition: bool,
425 change: &mut PaintChange<V>,
426 error: &mut Option<Error>,
427) -> bool {
428 if transition {
429 let mut conversion_error = Error::default();
430 match <PropertyTransition as Converter>::convert(value, &mut conversion_error) {
431 Some(options) if current.options != options => *change = PaintChange::Options(options),
432 Some(_) => {}
433 None => *error = Some(conversion_error),
434 }
435 } else {
436 let mut new_value = None;
437 changed_value(¤t.value, value, functions, info, &mut new_value, error);
438 if let Some(value) = new_value {
439 *change = PaintChange::Value(value);
440 }
441 }
442 !matches!(change, PaintChange::None)
443}
444
445#[inline(never)]
446fn apply_paint_change<V>(property: &mut Transitionable<V>, change: &mut PaintChange<V>) {
447 match std::mem::replace(change, PaintChange::None) {
448 PaintChange::None => {}
449 PaintChange::Value(value) => property.value = value,
450 PaintChange::Options(options) => property.options = options,
451 }
452}
453
454#[inline(never)]
455fn store<V>(slot: &mut V, change: &mut Option<V>) {
456 if let Some(value) = change.take() {
457 *slot = value;
458 }
459}
460
461pub(crate) fn layout_properties_differ<S: Properties>(a: &S, b: &S, section_overrides: bool) -> bool {
466 #[derive(Clone, Copy)]
468 struct Checks {
469 any: bool,
470 data_driven: bool,
471 constant: bool,
472 }
473
474 struct Differs<'a, S> {
475 a: &'a S,
476 b: &'a S,
477 checks: Checks,
478 }
479
480 impl<S> PropertyVisitor<S> for Differs<'_, S> {
481 type Output = bool;
482
483 fn paint<V: StyleValue>(
484 self,
485 get: fn(&S) -> &Transitionable<V>,
486 _: fn(&mut S) -> &mut Transitionable<V>,
487 ) -> bool {
488 values_differ(&get(self.a).value, &get(self.b).value, self.checks)
489 }
490
491 fn layout<V: StyleValue>(self, get: fn(&S) -> &V, _: fn(&mut S) -> &mut V) -> bool {
492 values_differ(get(self.a), get(self.b), self.checks)
493 }
494 }
495
496 #[inline(never)]
497 fn values_differ<V: StyleValue>(a: &V, b: &V, checks: Checks) -> bool {
498 (checks.any && a != b)
499 || (checks.data_driven && a.has_data_driven_property_difference(b))
500 || (checks.constant && a.constant_differs(b))
501 }
502
503 S::TABLE.properties.iter().enumerate().any(|(slot, info)| {
504 let checks = Checks {
505 any: info.scope == PropertyScope::Layout || info.cross_faded,
506 data_driven: info.data_driven,
507 constant: section_overrides && info.overridable,
508 };
509 (checks.any || checks.data_driven || checks.constant)
510 && S::visit(slot, Differs { a, b, checks }).unwrap_or_default()
511 })
512}
513
514pub(crate) fn defined_properties<S: Properties>(owner: &S) -> Vec<(String, PropertyScope, StyleProperty)> {
517 defined_properties_in(S::TABLE, &|slot, transition| style_property(owner, slot, transition))
518}
519
520fn defined_properties_in(
523 table: &PropertyTable,
524 get: &dyn Fn(usize, bool) -> StyleProperty,
525) -> Vec<(String, PropertyScope, StyleProperty)> {
526 let table = table.properties;
527 let mut defined = Vec::new();
528 let paint = table.iter().enumerate().filter(|(_, info)| info.scope == PropertyScope::Paint);
529 let layout = table.iter().enumerate().filter(|(_, info)| info.scope == PropertyScope::Layout);
530 let values = paint.clone().map(|(slot, info)| (slot, info, false));
531 let transitions = paint.map(|(slot, info)| (slot, info, true));
532 let layout = layout.map(|(slot, info)| (slot, info, false));
533 for (slot, info, transition) in values.chain(transitions).chain(layout) {
534 let property = get(slot, transition);
535 if property.kind() == Kind::Undefined {
536 continue;
537 }
538 let name = if transition { format!("{}-transition", info.name) } else { info.name.to_owned() };
539 defined.push((name, info.scope, property));
540 }
541 defined
542}
543
544pub(crate) fn serialize_properties<S: Properties>(owner: &S, out: &mut ValueObject) {
547 insert_properties(defined_properties(owner), out);
548}
549
550fn insert_properties(defined: Vec<(String, PropertyScope, StyleProperty)>, out: &mut ValueObject) {
551 for (name, scope, property) in defined {
552 let key = match scope {
553 PropertyScope::Paint => "paint",
554 PropertyScope::Layout => "layout",
555 };
556 if let Some(Value::Object(existing)) = out.get_mut(key) {
557 existing.entry(name).or_insert_with(|| property.value().clone());
558 } else {
559 let mut inner = ValueObject::new();
560 inner.insert(name, property.value().clone());
561 out.insert(key.to_owned(), Value::Object(inner));
562 }
563 }
564}
565
566pub(crate) fn names<S: Properties>() -> impl Iterator<Item = String> {
569 S::TABLE.properties.iter().flat_map(|info| {
570 let transition = (info.scope == PropertyScope::Paint).then(|| format!("{}-transition", info.name));
571 std::iter::once(info.name.to_owned()).chain(transition)
572 })
573}
574
575#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
576#[repr(u8)]
577pub enum Kind {
578 #[default]
579 Undefined,
580 Constant,
581 Expression,
582 Transition,
583}
584
585#[derive(Clone, Debug, Default, PartialEq)]
587pub struct StyleProperty {
588 value: Value,
589 kind: Kind,
590}
591
592impl StyleProperty {
593 #[must_use]
594 pub(crate) fn new(value: Value, kind: Kind) -> Self {
595 StyleProperty { value, kind }
596 }
597
598 #[must_use]
599 pub fn value(&self) -> &Value {
600 &self.value
601 }
602
603 #[must_use]
604 pub fn kind(&self) -> Kind {
605 self.kind
606 }
607}