Compare commits

...
6 changed files with 427 additions and 201 deletions

No files matched your search

Generated
+1
View File
@@ -966,6 +966,7 @@ dependencies = [
"serde",
"serde_json",
"skrifa",
"thiserror 2.0.18",
"tinyvec",
"tsify",
"wasm-bindgen",
@@ -51,6 +51,7 @@ log = { workspace = true }
base64 = { workspace = true }
polycool = { workspace = true }
futures = { workspace = true }
thiserror = { workspace = true }
# Optional workspace dependencies
serde = { workspace = true, optional = true }
+182 -44
View File
@@ -1,3 +1,4 @@
use crate::TypeDescriptor;
use crate::bounds::{BoundingBox, RenderBoundingBox};
use crate::math::quad::Quad;
use crate::transform::ApplyTransform;
@@ -203,6 +204,12 @@ fn implicit_default_value(key: &str) -> Option<Box<dyn AnyAttributeValue>> {
}
}
/// What pushing and extending lists pad a missing `key` attribute with: `key`'s implicit default if it has type `T`, otherwise
/// `T::default()`.
pub fn implicit_default<T: Clone + Default + 'static>(key: &str) -> T {
implicit_default_value(key).and_then(|default| default.as_any().downcast_ref::<T>().cloned()).unwrap_or_default()
}
/// Appends `count` copies of `key`'s implicit default to `attribute` (see [`implicit_default_value`]).
fn pad_with_implicit_default(key: &str, attribute: &mut dyn AnyAttribute, count: usize) {
match implicit_default_value(key) {
@@ -398,8 +405,8 @@ pub trait AnyAttribute: std::any::Any + Send + Sync {
/// Converts the shared attribute into one that can be downcast to its concrete type.
fn into_any_arc(self: Arc<Self>) -> Arc<dyn std::any::Any + Send + Sync>;
/// Pushes a scalar attribute value onto the end of this attribute.
fn push(&mut self, value: Arc<dyn AnyAttributeValue>);
/// Pushes a scalar attribute value onto the end of this attribute, or a default if it has another type, which returns `false`.
fn push(&mut self, value: Arc<dyn AnyAttributeValue>) -> bool;
/// Pushes a default value onto the end of this attribute.
fn push_default(&mut self);
@@ -409,8 +416,8 @@ pub trait AnyAttribute: std::any::Any + Send + Sync {
fn push_repeated(&mut self, value: &dyn AnyAttributeValue, count: usize);
/// Sets the value at the given index, padding with defaults if the attribute is shorter than `index`.
/// Falls back to a default if the value's type doesn't match.
fn set_at(&mut self, index: usize, value: Box<dyn AnyAttributeValue>);
/// Hands the value back if it has another type.
fn set_at(&mut self, index: usize, value: Box<dyn AnyAttributeValue>) -> Result<(), Box<dyn AnyAttributeValue>>;
/// Creates a new attribute of the same type filled with `count` number of default values.
fn new_with_defaults(&self, count: usize) -> Arc<dyn AnyAttribute>;
@@ -423,8 +430,8 @@ pub trait AnyAttribute: std::any::Any + Send + Sync {
self.len() == 0
}
/// Appends all values from another attribute of the same type.
fn extend(&mut self, other: Arc<dyn AnyAttribute>);
/// Appends all values from another attribute of the same type, or defaults for them if it has another type, which returns `false` unless it is empty.
fn extend(&mut self, other: Arc<dyn AnyAttribute>) -> bool;
/// Returns a shared reference to the value at the requested index.
fn get_any(&self, index: usize) -> Option<&dyn std::any::Any>;
@@ -444,6 +451,9 @@ pub trait AnyAttribute: std::any::Any + Send + Sync {
/// Compares this attribute to another for value-by-value equality (object-safe wrapper around `PartialEq`).
/// Returns `false` if the underlying types differ.
fn eq_dyn(&self, other: &dyn AnyAttribute) -> bool;
/// The type of this attribute's values.
fn value_type(&self) -> TypeDescriptor;
}
/// Adapts a `&mut dyn Hasher` so generic `CacheHash::cache_hash<H>` calls (which require `H: Sized + Hasher`) can
@@ -542,9 +552,11 @@ impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>
/// Pushes an attribute value onto the end of this attribute's list, downcasting it to `T`.
/// Falls back to a default value if the type doesn't match, to maintain the attribute-length invariant.
fn push(&mut self, value: Arc<dyn AnyAttributeValue>) {
let value = value.into_any_arc().downcast::<T>().map(Arc::unwrap_or_clone).unwrap_or_default();
self.0.push(value);
fn push(&mut self, value: Arc<dyn AnyAttributeValue>) -> bool {
let value = value.into_any_arc().downcast::<T>().map(Arc::unwrap_or_clone);
let matches = value.is_ok();
self.0.push(value.unwrap_or_default());
matches
}
/// Pushes a default `T` value onto the end of this attribute list.
@@ -559,8 +571,11 @@ impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>
}
/// Sets the value at the given index, padding with defaults if the attribute is shorter than `index`.
/// Falls back to a default if the value's type doesn't match.
fn set_at(&mut self, index: usize, value: Box<dyn AnyAttributeValue>) {
/// Hands the value back if it isn't a `T`.
fn set_at(&mut self, index: usize, value: Box<dyn AnyAttributeValue>) -> Result<(), Box<dyn AnyAttributeValue>> {
if !value.as_any().is::<T>() {
return Err(value);
}
while self.0.len() < index {
self.0.push(T::default());
}
@@ -570,6 +585,7 @@ impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>
} else {
self.0[index] = value;
}
Ok(())
}
/// Creates a new attribute filled with `count` default `T` values.
@@ -585,14 +601,18 @@ impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>
/// Appends all values from another attribute, downcasting it to the same `Attribute<T>` type.
/// Falls back to padding with defaults if the type doesn't match, to maintain the attribute-length invariant.
fn extend(&mut self, other: Arc<dyn AnyAttribute>) {
fn extend(&mut self, other: Arc<dyn AnyAttribute>) -> bool {
let other_len = other.len();
match other.into_any_arc().downcast::<Self>().map(Arc::try_unwrap) {
Ok(Ok(other)) => self.0.extend(other.0),
Ok(Err(shared)) => self.0.extend_from_slice(&shared.0),
Err(_) => self.0.extend(std::iter::repeat_with(T::default).take(other_len)),
Err(_) => {
self.0.extend(std::iter::repeat_with(T::default).take(other_len));
return other_len == 0;
}
}
true
}
/// Returns a shared reference to the value at the given index as a type-erased `Any`.
@@ -629,6 +649,10 @@ impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>
fn eq_dyn(&self, other: &dyn AnyAttribute) -> bool {
other.as_any().downcast_ref::<Self>().is_some_and(|other| self.0 == other.0)
}
fn value_type(&self) -> TypeDescriptor {
crate::descriptor!(T)
}
}
// ==================
@@ -700,6 +724,11 @@ impl ListDyn {
pub fn attribute<U: 'static>(&self, key: &str, index: usize) -> Option<&U> {
self.attributes.get_value(key, index)
}
/// Returns the type of the values the attribute for the given key holds, or `None` if absent.
pub fn attribute_type(&self, key: &str) -> Option<TypeDescriptor> {
self.attributes.value_type(key)
}
}
impl<T> From<List<T>> for ListDyn {
@@ -1081,23 +1110,31 @@ impl Attributes {
/// Pushes an item's scalar attributes into this attribute store.
/// Existing attributes that the item lacks receive a default value.
/// New attribute keys create a new attribute padded with defaults for all prior items.
fn push_item(&mut self, item: ItemAttributeValues) {
/// Returns the first attribute that holds another type than the item's value for it, which gets the default instead.
fn push_item(&mut self, item: ItemAttributeValues) -> Option<AttributeTypeConflictError> {
let len = self.len;
self.len += 1;
if self.attributes.is_empty() && item.0.is_none() {
return;
return None;
}
let mut item_entries = item.into_entries();
let mut conflict = None;
// Push values into existing attributes, or the implicit default if the item lacks that attribute
for (attribute_key, attribute) in self.attributes.as_mut_slice() {
let attribute = unshared(attribute);
match item_entries.iter().position(|(key, _)| key == attribute_key) {
Some(position) => attribute.push(item_entries.swap_remove(position).1),
None => pad_with_implicit_default(attribute_key.as_str(), attribute, 1),
// An attribute without values holds no type to keep
Some(position) if len == 0 => *attribute = item_entries.swap_remove(position).1.into_attribute(attribute_key.as_str(), 0),
Some(position) => {
if !unshared(attribute).push(item_entries.swap_remove(position).1) {
conflict.get_or_insert_with(|| AttributeTypeConflictError {
name: attribute_key.as_str().to_string(),
});
}
}
None => pad_with_implicit_default(attribute_key.as_str(), unshared(attribute), 1),
}
}
@@ -1106,33 +1143,41 @@ impl Attributes {
let attribute = value.into_attribute(key.as_str(), len);
self.attributes.push((key, attribute));
}
conflict
}
/// Appends all attribute data from another attribute store into this one.
/// Attributes present in only one side are padded with defaults for the other side's items.
fn extend(&mut self, other: Attributes) {
/// Returns the first attribute both stores hold with values of different types, where the other store's items get the default.
fn extend(&mut self, other: Attributes) -> Option<AttributeTypeConflictError> {
let (len, other_len) = (self.len, other.len);
self.len += other_len;
// An empty store takes on the other's attributes whole, sharing them
if len == 0 && self.entries().is_empty() {
self.attributes = other.attributes;
return;
return None;
}
// Nothing to add or pad, so self's attributes can stay shared
if other.attributes.is_empty() && (other_len == 0 || self.attributes.is_empty()) {
return;
return None;
}
let mut other_entries = other.attributes.into_vec();
let mut conflict = None;
// Extend matching attributes, or pad self's attributes with implicit defaults for the other's item count
for (key, self_attribute) in self.attributes.as_mut_slice() {
let self_attribute = unshared(self_attribute);
match other_entries.iter().position(|(other_key, _)| other_key == key) {
Some(position) => self_attribute.extend(other_entries.swap_remove(position).1),
None => pad_with_implicit_default(key.as_str(), self_attribute, other_len),
// An attribute without values holds no type to keep
Some(position) if len == 0 => *self_attribute = other_entries.swap_remove(position).1,
Some(position) => {
if !unshared(self_attribute).extend(other_entries.swap_remove(position).1) {
conflict.get_or_insert_with(|| AttributeTypeConflictError { name: key.as_str().to_string() });
}
}
None => pad_with_implicit_default(key.as_str(), unshared(self_attribute), other_len),
}
}
@@ -1145,6 +1190,13 @@ impl Attributes {
self.attributes.push((key, combined));
}
conflict
}
/// The type of the values the attribute for the given key holds, if present.
fn value_type(&self, key: &str) -> Option<TypeDescriptor> {
self.entries().iter().find(|(k, _)| k.is(key)).map(|(_, attribute)| attribute.value_type())
}
/// Gets a reference to the value at the given index from the attribute for the given key.
@@ -1221,18 +1273,24 @@ impl Attributes {
}
/// Sets a single type-erased value at the given index of a list of `item_count` items, creating the attribute from the
/// value's type if the key holds none.
fn set_value_dyn(&mut self, key: &str, index: usize, value: Box<dyn AnyAttributeValue>, item_count: usize) {
let position = self.position(key);
if let Some((_, attribute)) = position.and_then(|position| self.attributes.as_mut_slice().get_mut(position)) {
unshared(attribute).set_at(index, value);
} else {
let mut new_attribute = Arc::<dyn AnyAttributeValue>::from(value).into_attribute(key, index);
let trailing_defaults = item_count.saturating_sub(new_attribute.len());
pad_with_implicit_default(key, unshared(&mut new_attribute), trailing_defaults);
self.attributes.push((AttributeKey::new(key), new_attribute));
/// value's type if the key holds none. An attribute of another type is replaced, padded with implicit defaults.
fn set_value_dyn(&mut self, key: &str, index: usize, mut value: Box<dyn AnyAttributeValue>, item_count: usize) {
if let Some(position) = self.position(key)
&& let Some((_, attribute)) = self.attributes.as_mut_slice().get_mut(position)
{
match unshared(attribute).set_at(index, value) {
Ok(()) => return,
Err(mistyped) => {
self.attributes.remove(position);
value = mistyped;
}
}
}
let mut new_attribute = Arc::<dyn AnyAttributeValue>::from(value).into_attribute(key, index);
let trailing_defaults = item_count.saturating_sub(new_attribute.len());
pad_with_implicit_default(key, unshared(&mut new_attribute), trailing_defaults);
self.attributes.push((AttributeKey::new(key), new_attribute));
}
/// Returns a debug-formatted string for the value at the given index in the attribute for the given key.
@@ -1327,6 +1385,12 @@ impl Attributes {
}
}
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
#[error("The \"{name}\" attribute holds different types of values in the lists being combined")]
pub struct AttributeTypeConflictError {
pub name: String,
}
// =======
// List<T>
// =======
@@ -1488,7 +1552,7 @@ impl<T> List<T> {
}
/// Sets a single type-erased attribute value at the given index, creating the attribute from the value's underlying type if it doesn't exist (padded with defaults to match the list's length).
/// Falls back to default if the value's type doesn't match an existing attribute.
/// An existing attribute of another type is replaced the same way.
pub fn set_attribute_value_dyn(&mut self, key: impl AsRef<str>, index: usize, value: AttributeValueDyn) {
self.attributes.set_value_dyn(key.as_ref(), index, value.0, self.element.len());
}
@@ -1545,14 +1609,16 @@ impl<T: Clone> List<T> {
Arc::make_mut(&mut self.element)
}
/// Appends an item to the end of this list.
pub fn push(&mut self, item: Item<T>) {
/// Appends an item to the end of this list, returning the first attribute the list holds with another type than the item's value for it.
/// The list keeps its type for it, giving the item its default.
pub fn push(&mut self, item: Item<T>) -> Option<AttributeTypeConflictError> {
self.elements_mut().push(item.element);
self.attributes.push_item(item.attributes);
self.attributes.push_item(item.attributes)
}
/// Appends all items from another list into this one.
pub fn extend(&mut self, list: List<T>) {
/// Appends all items from another list into this one, returning the first attribute both lists have with values of different types.
/// This list keeps its type for it, giving the other list's items its default.
pub fn extend(&mut self, list: List<T>) -> Option<AttributeTypeConflictError> {
// An empty list adopts the other's elements without copying them
if self.element.is_empty() {
self.element = list.element;
@@ -1563,7 +1629,7 @@ impl<T: Clone> List<T> {
Err(shared) => elements.extend_from_slice(&shared),
}
}
self.attributes.extend(list.attributes);
self.attributes.extend(list.attributes)
}
/// Returns an iterator over mutable references to all element values.
@@ -2179,6 +2245,78 @@ mod tests {
assert_eq!(starts(&rebuilt), [11, 21, 10, 20, 0]);
}
// Combining lists keeps only the first type of an attribute both have, and reports the attribute whose values were lost
#[test]
fn combining_lists_reports_attribute_type_conflicts() {
let mut base = List::new_from_elements(vec![1_u32, 2]);
base.set_attribute_values(ATTR_START, vec![10_u64, 20]);
base.set_attribute_values(ATTR_NAME, vec![String::from("a"), String::from("b")]);
let mut matching = List::new_from_elements(vec![3_u32]);
matching.set_attribute_values(ATTR_START, vec![30_u64]);
matching.set_attribute_values(ATTR_END, vec![1.5_f64]);
assert_eq!(base.extend(matching), None);
let mut empty = List::new();
empty.set_attribute_values(ATTR_NAME, Vec::<i64>::new());
assert_eq!(base.extend(empty), None, "an empty list loses no values");
let mut mistyped = List::new_from_elements(vec![4_u32]);
mistyped.set_attribute_values(ATTR_NAME, vec![7_i64]);
let conflict = AttributeTypeConflictError { name: ATTR_NAME.to_string() };
assert_eq!(base.extend(mistyped), Some(conflict.clone()));
assert_eq!(conflict.to_string(), "The \"name\" attribute holds different types of values in the lists being combined");
assert_eq!(base.attribute::<String>(ATTR_NAME, 3), Some(&String::new()));
assert_eq!(base.push(Item::new_from_element(5).with_attribute(ATTR_START, 50_u64)), None);
let mistyped_item = Item::new_from_element(6).with_attribute(ATTR_START, 60_f64);
assert_eq!(base.push(mistyped_item), Some(AttributeTypeConflictError { name: ATTR_START.to_string() }));
assert_eq!(base.attribute::<u64>(ATTR_START, 5), Some(&0));
}
#[test]
fn an_attribute_without_values_takes_the_type_of_the_values_added_to_it() {
let mut mistyped = List::new_from_elements(vec![1_u32]);
mistyped.set_attribute_values(ATTR_NAME, vec![7_i64]);
let mut extended = List::<u32>::new();
extended.set_attribute_values(ATTR_NAME, Vec::<String>::new());
assert_eq!(extended.extend(mistyped), None);
assert_eq!(extended.attribute::<i64>(ATTR_NAME, 0), Some(&7));
let mut pushed = List::<u32>::new();
pushed.set_attribute_values(ATTR_NAME, Vec::<String>::new());
assert_eq!(pushed.push(Item::new_from_element(1).with_attribute(ATTR_NAME, 7_i64)), None);
assert_eq!(pushed.attribute::<i64>(ATTR_NAME, 0), Some(&7));
}
// An attribute's type reads back from a list's type-erased view, and a missing value reads as what padding fills in
#[test]
fn attribute_types_and_implicit_defaults_read_back() {
let mut list = List::new_from_elements(vec![1_u32]);
list.set_attribute(ATTR_OPACITY, 0, 0.5_f64);
let list = ListDyn::from(list);
assert_eq!(list.attribute_type(ATTR_OPACITY), Some(crate::descriptor!(f64)));
assert_eq!(list.attribute_type(ATTR_OPACITY).map(|value_type| value_type.to_string()), Some("Number".to_string()));
assert_eq!(list.attribute_type(ATTR_START), None);
assert_eq!(implicit_default::<f64>(ATTR_OPACITY), 1.);
assert_eq!(implicit_default::<f64>(ATTR_START), 0.);
assert_eq!(implicit_default::<i64>(ATTR_OPACITY), 0);
}
// A type-erased value of another type replaces the attribute, as a typed one does, instead of becoming the old type's default
#[test]
fn setting_a_value_of_another_type_replaces_the_attribute() {
let mut list = List::new_from_elements(vec![1_u32, 2]);
list.set_attribute_values(ATTR_OPACITY, vec![0.5_f64, 0.25]);
list.set_attribute_value_dyn(ATTR_OPACITY, 1, AttributeValueDyn(Box::new(3_i64)));
assert_eq!(list.iter_attribute_values::<i64>(ATTR_OPACITY).map(|values| values.copied().collect::<Vec<_>>()), Some(vec![0, 3]));
list.set_attribute_value_dyn(ATTR_OPACITY, 0, AttributeValueDyn(Box::new(0.75_f64)));
assert_eq!(list.iter_attribute_values::<f64>(ATTR_OPACITY).map(|values| values.copied().collect::<Vec<_>>()), Some(vec![0.75, 1.]));
}
// Keys are stored inline up to a length limit and shared beyond it, which reads the same either way
#[test]
fn attribute_keys_of_any_length_read_back() {
@@ -232,7 +232,9 @@ impl Appearance {
let row = cover_row(coverage, paint);
match placement {
CoverPlacement::Above => self.0.push(row),
CoverPlacement::Above => {
self.0.push(row);
}
CoverPlacement::Below => {
let mut reordered = List::new_from_item(row);
reordered.extend(std::mem::take(&mut self.0));
@@ -2,7 +2,7 @@ use crate::appearance::{Appearance, Cover, Coverage};
use brush_types::Stroke;
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::graphene_hash::CacheHash;
use core_types::list::{ATTR_APPEARANCE, ATTR_PAINT, Item, ItemAttributeValues, List, NodeIdPath};
use core_types::list::{ATTR_APPEARANCE, ATTR_PAINT, AttributeTypeConflictError, Item, ItemAttributeValues, List, NodeIdPath};
use core_types::math::quad::Quad;
use core_types::none;
use core_types::ops::FromAnchorPosition;
@@ -180,15 +180,16 @@ pub fn is_lone_anonymous_leaf(content: &List<Graphic>) -> bool {
/// Deeply flattens a `List<Graphic>`, collecting only elements matching a specific variant (extracted by `extract_variant`)
/// and discarding all other non-matching content. Recursion through `Graphic::GraphicList` sub-`List`s composes transforms and opacity.
fn flatten_graphic_list<T: Clone>(content: List<Graphic>, extract_variant: fn(Graphic) -> Option<List<T>>) -> List<T> {
/// Also gives the first attribute that the flattened lists have with values of different types.
fn flatten_graphic_list<T: Clone>(content: List<Graphic>, extract_variant: fn(Graphic) -> Option<List<T>>) -> (List<T>, Option<AttributeTypeConflictError>) {
// Its list is already the flat answer, so hand it back rather than rebuilding it item by item
if is_lone_anonymous_leaf(&content) {
let Some(item) = content.into_iter().next() else { return List::new() };
let Some(item) = content.into_iter().next() else { return (List::new(), None) };
return extract_variant(item.into_element()).unwrap_or_default();
return (extract_variant(item.into_element()).unwrap_or_default(), None);
}
fn flatten_recursive<T: Clone>(output: &mut List<T>, current_graphic_list: List<Graphic>, extract_variant: fn(Graphic) -> Option<List<T>>) {
fn flatten_recursive<T: Clone>(output: &mut List<T>, conflict: &mut Option<AttributeTypeConflictError>, current_graphic_list: List<Graphic>, extract_variant: fn(Graphic) -> Option<List<T>>) {
for current_graphic_item in current_graphic_list.into_iter() {
// Whether the parent carries each composed attribute: a structural fact (attribute presence), never a value comparison.
// Flattening composes a parent attribute onto its children only when the parent has it,
@@ -244,7 +245,7 @@ fn flatten_graphic_list<T: Clone>(content: List<Graphic>, extract_variant: fn(Gr
}
}
flatten_recursive(output, sub_list, extract_variant);
flatten_recursive(output, conflict, sub_list, extract_variant);
}
// Extract the target variant and push its items, composing the parent's attributes onto each
other => {
@@ -273,7 +274,9 @@ fn flatten_graphic_list<T: Clone>(content: List<Graphic>, extract_variant: fn(Gr
item.set_attribute(ATTR_APPEARANCE, appearance.clone());
}
output.push(item);
if let Some(item_conflict) = output.push(item) {
conflict.get_or_insert(item_conflict);
}
}
}
}
@@ -282,8 +285,9 @@ fn flatten_graphic_list<T: Clone>(content: List<Graphic>, extract_variant: fn(Gr
}
let mut output = List::new();
flatten_recursive(&mut output, content, extract_variant);
output
let mut conflict = None;
flatten_recursive(&mut output, &mut conflict, content, extract_variant);
(output, conflict)
}
/// Whether a normalized paint graphic list actually carries renderable paint.
@@ -405,7 +409,19 @@ pub trait IntoGraphicList: Clone + Send + Sync + Default + std::fmt::Debug + Par
where
Self: std::marker::Sized,
{
flatten_graphic_list(self.into_graphic_list(), T::try_from_graphic)
flatten_graphic_list(self.into_graphic_list(), T::try_from_graphic).0
}
/// Deeply flattens any content of type `T`, failing with the flattened list and the first attribute that holds values of different
/// types in the flattened lists (their later items hold the first type's default).
fn try_into_flattened_list<T: TryFromGraphic>(self) -> Result<List<T>, (List<T>, AttributeTypeConflictError)>
where
Self: std::marker::Sized,
{
match flatten_graphic_list(self.into_graphic_list(), T::try_from_graphic) {
(list, None) => Ok(list),
(list, Some(conflict)) => Err((list, conflict)),
}
}
}
@@ -1049,6 +1065,27 @@ mod tests {
assert_eq!(color_of(1), Some(Color::WHITE), "a padded item should inherit the parent appearance");
}
// Flattening lists that hold an attribute with different types keeps the first type, and says which attribute lost values
#[test]
fn flatten_reports_an_attribute_holding_different_types() {
let tagged = |value: Item<Vector>| Item::new_from_element(Graphic::VectorList(List::new_from_item(value)));
let mut graphics = List::new();
graphics.push(tagged(Item::new_from_element(Vector::default()).with_attribute("tag", 1_f64)));
graphics.push(tagged(Item::new_from_element(Vector::default()).with_attribute("tag", String::from("two"))));
let Err((flattened, conflict)) = graphics.clone().try_into_flattened_list::<Vector>() else {
panic!("expected the conflicting tag to be reported")
};
assert_eq!(conflict.name, "tag");
assert_eq!(flattened, graphics.clone().into_flattened_list::<Vector>());
assert_eq!(flattened.attribute::<f64>("tag", 1), Some(&0.));
let mut matching = List::new();
matching.push(tagged(Item::new_from_element(Vector::default()).with_attribute("tag", 1_f64)));
matching.push(tagged(Item::new_from_element(Vector::default()).with_attribute("tag", 2_f64)));
assert!(matching.try_into_flattened_list::<Vector>().is_ok());
}
#[test]
fn embedded_item_keeps_its_attributes_inside_the_variant() {
let color = Item::new_from_element(Color::RED).with_attribute(ATTR_POSITION, 0.25_f64);
+193 -146
View File
@@ -1,7 +1,9 @@
use brush_types::Stroke;
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::list::{AttributeValueDyn, Item, List, ListDyn, NodeIdPath};
use core_types::{ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, AnyHash, BlendMode, CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, Interrupt, OwnedContextImpl};
use core_types::list::{AttributeTypeConflictError, AttributeValueDyn, Item, List, ListDyn, NodeIdPath, implicit_default};
use core_types::{
ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, AnyHash, BlendMode, CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, Interrupt, OwnedContextImpl, descriptor,
};
use glam::{DAffine2, DVec2};
use graphic_types::graphic::{Graphic, IntoGraphicList, is_lone_anonymous_leaf};
use graphic_types::{Artboard, Vector};
@@ -560,6 +562,14 @@ fn path_of_subgraph(_: impl Ctx, node_path: Item<NodeIdPath>) -> Item<NodeIdPath
Item::new_from_element(NodeIdPath(node_path.into_iter().take(len.saturating_sub(1)).collect()))
}
#[derive(Debug, thiserror::Error)]
pub enum AttributeTypeError {
#[error("The \"{name}\" attribute holds {held} values, not {requested}")]
WrongType { name: String, held: String, requested: String },
#[error(transparent)]
Conflict(#[from] AttributeTypeConflictError),
}
/// Sets a named attribute on the input list, computing one value per item via the value-producing input. That input
/// is evaluated once per item, with the item's index and the item itself (as a list containing only that item,
/// passed as a vararg) provided via context, so the upstream pipeline can return a different value per item that may
@@ -615,14 +625,8 @@ fn read_attribute_vector(
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<Vector> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<Vector>(&name, index) else { continue };
result.push(Item::new_from_element(value.clone()));
}
result
) -> Result<List<Vector>, AttributeTypeError> {
read_list_attribute(&content, name.element())
}
/// Reads a named `Number` or `Integer` attribute from the input list, outputting each value as an element of a new `Number[]`.
@@ -633,15 +637,16 @@ fn read_attribute_number(
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<f64> {
) -> Result<List<f64>, AttributeTypeError> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let value = content.attribute::<f64>(&name, index).copied().or_else(|| content.attribute::<i64>(&name, index).map(|v| *v as f64));
let Some(value) = value else { continue };
result.push(Item::new_from_element(value));
if content.attribute_type(&name) == Some(descriptor!(i64)) {
return Ok((0..content.len())
.filter_map(|index| content.attribute::<i64>(&name, index))
.map(|value| Item::new_from_element(*value as f64))
.collect());
}
result
read_attribute(&content, &name)
}
/// Reads a named `Bool` attribute from the input list, outputting each value as an element of a new `Bool[]`.
@@ -652,14 +657,8 @@ fn read_attribute_bool(
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<bool> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<bool>(&name, index) else { continue };
result.push(Item::new_from_element(*value));
}
result
) -> Result<List<bool>, AttributeTypeError> {
read_attribute(&content, name.element())
}
/// Reads a named `String` attribute from the input list, outputting each value as an element of a new `String[]`.
@@ -670,14 +669,8 @@ fn read_attribute_string(
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<String> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<String>(&name, index) else { continue };
result.push(Item::new_from_element(value.clone()));
}
result
) -> Result<List<String>, AttributeTypeError> {
read_attribute(&content, name.element())
}
/// Reads a named `Transform` attribute from the input list, outputting each value as an element of a new `Transform[]`.
@@ -688,14 +681,8 @@ fn read_attribute_transform(
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<DAffine2> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<DAffine2>(&name, index) else { continue };
result.push(Item::new_from_element(*value));
}
result
) -> Result<List<DAffine2>, AttributeTypeError> {
read_attribute(&content, name.element())
}
/// Reads a named `Color` attribute from the input list, outputting each value as an element of a new `Color[]`.
@@ -706,14 +693,8 @@ fn read_attribute_color(
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<Color> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<Color>(&name, index) else { continue };
result.push(Item::new_from_element(*value));
}
result
) -> Result<List<Color>, AttributeTypeError> {
read_attribute(&content, name.element())
}
/// Reads a named `BlendMode` attribute from the input list, outputting each value as an element of a new `BlendMode[]`.
@@ -724,14 +705,8 @@ fn read_attribute_blend_mode(
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<BlendMode> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<BlendMode>(&name, index) else { continue };
result.push(Item::new_from_element(*value));
}
result
) -> Result<List<BlendMode>, AttributeTypeError> {
read_attribute(&content, name.element())
}
/// Reads a named `GradientForm` attribute from the input list, outputting each value as an element of a new `GradientForm[]`.
@@ -742,14 +717,8 @@ fn read_attribute_gradient_form(
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<GradientForm> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<GradientForm>(&name, index) else { continue };
result.push(Item::new_from_element(*value));
}
result
) -> Result<List<GradientForm>, AttributeTypeError> {
read_attribute(&content, name.element())
}
/// Reads a named `GradientSpread` attribute from the input list, outputting each value as an element of a new `GradientSpread[]`.
@@ -760,14 +729,8 @@ fn read_attribute_gradient_spread(
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<GradientSpread> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<GradientSpread>(&name, index) else { continue };
result.push(Item::new_from_element(*value));
}
result
) -> Result<List<GradientSpread>, AttributeTypeError> {
read_attribute(&content, name.element())
}
/// Reads a named `GradientSpace` attribute from the input list, outputting each value as an element of a new `GradientSpace[]`.
@@ -778,14 +741,8 @@ fn read_attribute_gradient_space(
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<GradientSpace> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<GradientSpace>(&name, index) else { continue };
result.push(Item::new_from_element(*value));
}
result
) -> Result<List<GradientSpace>, AttributeTypeError> {
read_attribute(&content, name.element())
}
/// Reads a named `GradientInterpolation` attribute from the input list, outputting each value as an element of a new `GradientInterpolation[]`.
@@ -796,14 +753,8 @@ fn read_attribute_gradient_interpolation(
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<GradientInterpolation> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<GradientInterpolation>(&name, index) else { continue };
result.push(Item::new_from_element(*value));
}
result
) -> Result<List<GradientInterpolation>, AttributeTypeError> {
read_attribute(&content, name.element())
}
/// Reads a named `GradientHueDirection` attribute from the input list, outputting each value as an element of a new `GradientHueDirection[]`.
@@ -814,14 +765,8 @@ fn read_attribute_gradient_hue_direction(
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<GradientHueDirection> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<GradientHueDirection>(&name, index) else { continue };
result.push(Item::new_from_element(*value));
}
result
) -> Result<List<GradientHueDirection>, AttributeTypeError> {
read_attribute(&content, name.element())
}
/// Reads a named `Gradient` attribute from the input list, outputting each value as an element of a new `Gradient[]`.
@@ -832,14 +777,8 @@ fn read_attribute_gradient_stops(
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<Gradient> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<Gradient>(&name, index) else { continue };
result.push(Item::new_from_element(value.clone()));
}
result
) -> Result<List<Gradient>, AttributeTypeError> {
read_list_attribute(&content, name.element())
}
/// Reads a named `Artboard` attribute from the input list, outputting each value as an element of a new `Artboard[]`.
@@ -850,14 +789,8 @@ fn read_attribute_artboard(
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<Artboard> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<Artboard>(&name, index) else { continue };
result.push(Item::new_from_element(value.clone()));
}
result
) -> Result<List<Artboard>, AttributeTypeError> {
read_attribute(&content, name.element())
}
/// Reads a named `Raster` attribute from the input list, outputting each value as an element of a new `Raster[]`.
@@ -868,14 +801,41 @@ fn read_attribute_raster(
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<Raster<CPU>> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<Raster<CPU>>(&name, index) else { continue };
result.push(Item::new_from_element(value.clone()));
) -> Result<List<Raster<CPU>>, AttributeTypeError> {
read_list_attribute(&content, name.element())
}
/// Reads the named attribute's value for every item, reading an attribute no item has as each item's implicit default.
fn read_attribute<T: Clone + Default + 'static>(content: &ListDyn, name: &str) -> Result<List<T>, AttributeTypeError> {
let requested = descriptor!(T);
if let Some(held) = content.attribute_type(name)
&& held != requested
{
return Err(AttributeTypeError::WrongType {
name: name.to_string(),
held: held.to_string(),
requested: requested.to_string(),
});
}
result
Ok((0..content.len())
.map(|index| Item::new_from_element(content.attribute::<T>(name, index).cloned().unwrap_or_else(|| implicit_default(name))))
.collect())
}
/// Reads the named attribute like [`read_attribute`], joining the lists of an attribute holding one list per item, as Write Attribute stores a list.
fn read_list_attribute<T: Clone + Default + 'static>(content: &ListDyn, name: &str) -> Result<List<T>, AttributeTypeError> {
if content.attribute_type(name) != Some(descriptor!(List<T>)) {
return read_attribute(content, name);
}
let mut result = List::new();
for list in (0..content.len()).filter_map(|index| content.attribute::<List<T>>(name, index)) {
if let Some(conflict) = result.extend(list.clone()) {
return Err(conflict.into());
}
}
Ok(result)
}
/// Joins two lists of the same type, extending the base list with the items from the new list.
@@ -919,11 +879,12 @@ fn extend<T: Send + Clone>(
List<Stroke>,
)]
new: List<T>,
) -> List<T> {
) -> Result<List<T>, (List<T>, AttributeTypeConflictError)> {
let mut base = base;
base.extend(new);
base
match base.extend(new) {
Some(conflict) => Err((base, conflict)),
None => Ok(base),
}
}
// TODO: Eventually remove this document upgrade code
@@ -937,7 +898,7 @@ fn legacy_layer_extend<T: Send + Clone>(
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>)]
new: List<T>,
nested_node_path: Item<NodeIdPath>,
) -> List<T> {
) -> Result<List<T>, (List<T>, AttributeTypeConflictError)> {
// Drop this internal node's own trailing entry so the stamped path ends at the user-facing parent layer-style node (which encapsulates it)
let nested_node_path = nested_node_path.into_element().0;
let layer_path = {
@@ -946,12 +907,18 @@ fn legacy_layer_extend<T: Send + Clone>(
};
let mut base = base;
let mut conflict = None;
for mut row in new.into_iter() {
row.set_attribute(ATTR_EDITOR_LAYER_PATH, layer_path.clone());
base.push(row);
if let Some(row_conflict) = base.push(row) {
conflict.get_or_insert(row_conflict);
}
}
base
match conflict {
Some(conflict) => Err((base, conflict)),
None => Ok(base),
}
}
/// Nests the input graphical content in a wrapper graphic, collecting it all into a single group.
@@ -985,11 +952,11 @@ fn as_graphic(_: impl Ctx, value: Item<Graphic>) -> Item<Graphic> {
/// Removes a level of nesting from a `Graphic[]`, or all nesting if "Fully Flatten" is enabled.
#[node_macro::node(category("Graphic"), icon("NodeFlattenGraphic"))]
fn flatten_graphic(_: impl Ctx, content: List<Graphic>, fully_flatten: Item<bool>) -> List<Graphic> {
fn flatten_graphic(_: impl Ctx, content: List<Graphic>, fully_flatten: Item<bool>) -> Result<List<Graphic>, (List<Graphic>, AttributeTypeConflictError)> {
let fully_flatten = fully_flatten.into_element();
// TODO: Avoid mutable reference, instead return a new List<Graphic>?
fn flatten_list(output_graphic_list: &mut List<Graphic>, current_graphic_list: List<Graphic>, fully_flatten: bool, recursion_depth: usize) {
fn flatten_list(output_graphic_list: &mut List<Graphic>, conflict: &mut Option<AttributeTypeConflictError>, current_graphic_list: List<Graphic>, fully_flatten: bool, recursion_depth: usize) {
for index in 0..current_graphic_list.len() {
let Some(current_element) = current_graphic_list.element(index) else { continue };
let current_element = current_element.clone();
@@ -1011,27 +978,34 @@ fn flatten_graphic(_: impl Ctx, content: List<Graphic>, fully_flatten: Item<bool
*graphic_transform = current_transform * *graphic_transform;
}
flatten_list(output_graphic_list, current_element, fully_flatten, recursion_depth + 1);
flatten_list(output_graphic_list, conflict, current_element, fully_flatten, recursion_depth + 1);
}
// Push any leaf element: a group beyond the recursion depth, or any non-group variant
_ => {
let attributes = current_graphic_list.clone_item_attributes(index);
output_graphic_list.push(Item::from_parts(current_element, attributes));
if let Some(item_conflict) = output_graphic_list.push(Item::from_parts(current_element, attributes)) {
conflict.get_or_insert(item_conflict);
}
}
}
}
}
let mut output = List::new();
flatten_list(&mut output, content, fully_flatten, 0);
let mut conflict = None;
flatten_list(&mut output, &mut conflict, content, fully_flatten, 0);
output
match conflict {
Some(conflict) => Err((output, conflict)),
None => Ok(output),
}
}
/// Converts a `Graphic[]` into a `Vector[]` by deeply flattening any vector content it contains, and discarding any non-vector content.
#[node_macro::node(category("Graphic"), icon("NodeFlattenVector"))]
pub fn flatten_vector(_: impl Ctx, content: List<Graphic>) -> List<Vector> {
let mut output: List<Vector> = content.clone().into_flattened_list();
pub fn flatten_vector(_: impl Ctx, content: List<Graphic>) -> Result<List<Vector>, (List<Vector>, AttributeTypeConflictError)> {
let mut flattened = content.clone().try_into_flattened_list();
let (Ok(output) | Err((output, _))) = &mut flattened;
// TODO: Replace this snapshot hack with per-layer metadata driven by each layer's Monitor node.
// TODO: Flattening here erases the upstream `List<Graphic>` hierarchy that editor metadata collection walks
@@ -1057,13 +1031,15 @@ pub fn flatten_vector(_: impl Ctx, content: List<Graphic>) -> List<Vector> {
output.set_attribute(ATTR_EDITOR_MERGED_LAYERS, 0, merged_layers);
}
output
flattened
}
#[derive(Debug, thiserror::Error)]
pub enum FlattenRasterError {
#[error("GPU rasters such as brush strokes can't be flattened yet, so they were left out")]
GpuRasters,
#[error(transparent)]
AttributeTypeConflict(#[from] AttributeTypeConflictError),
}
/// Whether the content holds GPU rasters, which flattening to CPU rasters leaves out.
@@ -1081,30 +1057,34 @@ fn has_gpu_raster(graphic: &Graphic) -> bool {
#[node_macro::node(category("Graphic"), icon("NodeFlattenRaster"))]
fn flatten_raster(_: impl Ctx, content: List<Graphic>) -> Result<List<Raster<CPU>>, (List<Raster<CPU>>, FlattenRasterError)> {
let has_gpu_rasters = content.iter_element_values().any(has_gpu_raster);
let rasters = content.into_flattened_list();
let flattened = content.try_into_flattened_list();
if has_gpu_rasters {
let rasters = flattened.unwrap_or_else(|(rasters, _)| rasters);
return Err((rasters, FlattenRasterError::GpuRasters));
}
Ok(rasters)
flattened.map_err(|(rasters, conflict)| (rasters, conflict.into()))
}
/// Converts a `Graphic[]` into a `Color[]` by deeply flattening any color content it contains, and discarding any non-color content.
#[node_macro::node(category("Graphic"), icon("NodeFlattenColor"))]
fn flatten_color(_: impl Ctx, content: List<Graphic>) -> List<Color> {
content.into_flattened_list()
fn flatten_color(_: impl Ctx, content: List<Graphic>) -> Result<List<Color>, (List<Color>, AttributeTypeConflictError)> {
content.try_into_flattened_list()
}
/// Converts a `Graphic[]` into a `Gradient[]` by deeply flattening any gradient content it contains, and discarding any non-gradient content.
#[node_macro::node(category("Graphic"), icon("NodeFlattenGradient"))]
fn flatten_gradient(_: impl Ctx, content: List<Graphic>) -> List<Gradient> {
content.into_flattened_list()
fn flatten_gradient(_: impl Ctx, content: List<Graphic>) -> Result<List<Gradient>, (List<Gradient>, AttributeTypeConflictError)> {
content.try_into_flattened_list()
}
/// Constructs a gradient from a `Color[]`, where each color becomes a gradient stop. A `position` attribute on the colors places their stops along the ramp and a `midpoint` attribute skews each transition, while colors carrying neither are distributed evenly across the 0 to 1 range.
#[node_macro::node(category("Gradient"), icon("NodeColorsToGradient"), name("Colors to Gradient"))]
fn colors_to_gradient(_: impl Ctx, colors: List<Graphic>) -> Item<Gradient> {
Item::new_from_element(Gradient::from(colors.into_flattened_list::<Color>()))
fn colors_to_gradient(_: impl Ctx, colors: List<Graphic>) -> Result<Item<Gradient>, (Item<Gradient>, AttributeTypeConflictError)> {
colors
.try_into_flattened_list::<Color>()
.map(|colors| Item::new_from_element(Gradient::from(colors)))
.map_err(|(colors, conflict)| (Item::new_from_element(Gradient::from(colors)), conflict))
}
/// Unwraps a gradient into a `Color[]` of its stops, keeping any `position` and `midpoint` attributes that place them along the ramp. Attributes belonging to the gradient as a whole (like spread and interpolation), rather than its individual color stops, are not preserved.
@@ -1116,6 +1096,7 @@ fn gradient_to_colors(_: impl Ctx, gradient: Item<Gradient>) -> List<Color> {
#[cfg(test)]
mod test {
use super::*;
use core_types::ATTR_OPACITY;
fn list_of<T>(elements: impl IntoIterator<Item = T>) -> List<T> {
elements.into_iter().map(Item::new_from_element).collect()
@@ -1204,6 +1185,72 @@ mod test {
assert_eq!(mirrored(String::new(), ReferencePoint::Center).unwrap().len(), 2);
}
fn with_values<U: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static>(key: &str, values: Vec<U>) -> ListDyn {
let mut list = List::new_from_elements(vec![(); values.len()]);
list.set_attribute_values(key, values);
ListDyn::from(list)
}
#[test]
fn reading_a_missing_attribute_gives_each_item_its_implicit_default() {
let plain = ListDyn::from(List::new_from_elements(vec![(), ()]));
assert_eq!(elements(&read_attribute_number((), plain.clone(), Item::new_from_element(ATTR_OPACITY.to_string())).unwrap()), [1., 1.]);
assert_eq!(elements(&read_attribute_number((), plain.clone(), Item::new_from_element("misspelled".to_string())).unwrap()), [0., 0.]);
assert_eq!(
elements(&read_attribute_transform((), plain, Item::new_from_element(ATTR_TRANSFORM.to_string())).unwrap()),
[DAffine2::IDENTITY; 2]
);
}
#[test]
fn reading_an_attribute_as_another_type_fails() {
let numbers = with_values("tag", vec![1_f64, 2.]);
let error = read_attribute_bool((), numbers.clone(), Item::new_from_element("tag".to_string())).unwrap_err();
assert_eq!(error.to_string(), "The \"tag\" attribute holds Number values, not Bool");
assert_eq!(
elements(&read_attribute_number((), with_values("tag", vec![3_i64]), Item::new_from_element("tag".to_string())).unwrap()),
[3.]
);
}
#[test]
fn reading_a_list_attribute_joins_the_lists() {
let vectors = with_values("shapes", vec![list_of([Vector::default(), Vector::default()]), list_of([Vector::default()])]);
assert_eq!(read_attribute_vector((), vectors, Item::new_from_element("shapes".to_string())).unwrap().len(), 3);
let texts = with_values("words", vec![list_of(["a".to_string()])]);
let error = read_attribute_string((), texts, Item::new_from_element("words".to_string())).unwrap_err();
assert_eq!(error.to_string(), "The \"words\" attribute holds String[] values, not String");
}
#[test]
fn reading_list_attributes_with_differently_typed_attributes_fails() {
let mut first = list_of([Vector::default()]);
first.set_attribute("tag", 0, 5_f64);
let mut second = list_of([Vector::default()]);
second.set_attribute("tag", 0, "text".to_string());
let vectors = with_values("shapes", vec![first, second]);
let error = read_attribute_vector((), vectors, Item::new_from_element("shapes".to_string())).unwrap_err();
assert_eq!(error.to_string(), "The \"tag\" attribute holds different types of values in the lists being combined");
}
#[test]
fn extending_with_an_attribute_of_another_type_falls_back_with_its_name() {
let mut base = list_of([1., 2.]);
base.set_attribute("tag", 0, 5_f64);
let mut new = list_of([3.]);
new.set_attribute("tag", 0, "text".to_string());
let Err((extended, conflict)) = extend((), base, new) else {
panic!("expected the conflicting tag to be reported")
};
assert_eq!(elements(&extended), [1., 2., 3.]);
assert_eq!(extended.attribute::<f64>("tag", 2), Some(&0.));
assert_eq!(conflict.name, "tag");
}
#[test]
fn shift_wraps_items_around() {
let forward = shift((), list_of([1., 2., 3., 4.]), Item::new_from_element(1_i64), Item::new_from_element(true));
@@ -1285,7 +1332,7 @@ mod test {
let colors = gradient_to_colors((), Item::new_from_element(gradient.clone()));
assert_eq!(elements(&colors), [Color::RED, Color::GREEN, Color::BLUE], "every stop should come out as its color");
let restored = colors_to_gradient((), embed_colors(colors));
let restored = colors_to_gradient((), embed_colors(colors)).unwrap();
assert_eq!(
restored.element(),
&gradient,
@@ -1298,7 +1345,7 @@ mod test {
let gradient = Gradient::from(vec![Color::RED, Color::GREEN, Color::BLUE]);
assert!(!gradient.has_position_attribute(), "even spacing is stored as the attribute's absence");
let restored = colors_to_gradient((), embed_colors(gradient_to_colors((), Item::new_from_element(gradient.clone()))));
let restored = colors_to_gradient((), embed_colors(gradient_to_colors((), Item::new_from_element(gradient.clone())))).unwrap();
assert_eq!(restored.element(), &gradient, "a default ramp should round trip without gaining attributes it never had");
}
}