1use cssparser::{
18 self, BasicParseErrorKind, ParseErrorKind, Parser, ParserInput, RuleBodyParser, ToCss,
19};
20use markup5ever::{ExpandedName, LocalName, QualName, expanded_name, local_name, ns};
21use std::collections::HashSet;
22
23#[cfg(doc)]
24use crate::make_property;
25
26use crate::css::{DeclParser, Declaration, Origin, RuleBodyItem};
27use crate::error::*;
28use crate::parsers::{Parse, ParseValue};
29use crate::property_macros::Property;
30use crate::rsvg_log;
31use crate::session::Session;
32use crate::transform::{Transform, TransformAttribute, TransformProperty};
33use crate::xml::Attributes;
34
35pub use crate::font_props::*;
37pub use crate::property_defs::*;
38
39#[derive(Clone)]
50pub enum SpecifiedValue<T>
51where
52 T: Property + Clone + Default,
53{
54 Unspecified,
55 Inherit,
56 Specified(T),
57}
58
59impl<T> SpecifiedValue<T>
60where
61 T: Property + Clone + Default,
62{
63 pub fn compute(&self, src: &T, src_values: &ComputedValues) -> T {
64 let value: T = match *self {
65 SpecifiedValue::Unspecified => {
66 if <T as Property>::inherits_automatically() {
67 src.clone()
68 } else {
69 Default::default()
70 }
71 }
72
73 SpecifiedValue::Inherit => src.clone(),
74
75 SpecifiedValue::Specified(ref v) => v.clone(),
76 };
77
78 value.compute(src_values)
79 }
80}
81
82#[derive(PartialEq)]
86enum PresentationAttr {
87 No,
88 Yes,
89}
90
91#[derive(PartialEq)]
93pub enum ParseAs {
94 Property,
95 PresentationAttr,
96}
97
98impl PropertyId {
99 fn as_u8(&self) -> u8 {
100 *self as u8
101 }
102
103 fn as_usize(&self) -> usize {
104 *self as usize
105 }
106}
107
108#[derive(Clone)]
110pub struct SpecifiedValues {
111 indices: [u8; PropertyId::UnsetProperty as usize],
112 props: Vec<ParsedProperty>,
113
114 transform: Option<Transform>,
115}
116
117impl Default for SpecifiedValues {
118 fn default() -> Self {
119 SpecifiedValues {
120 indices: [PropertyId::UnsetProperty.as_u8(); PropertyId::UnsetProperty as usize],
122 props: Vec::new(),
123 transform: None,
124 }
125 }
126}
127
128impl ComputedValues {
129 pub fn transform(&self) -> Transform {
132 self.transform
133 }
134
135 pub fn is_overflow(&self) -> bool {
136 matches!(self.overflow(), Overflow::Auto | Overflow::Visible)
137 }
138
139 pub fn is_displayed(&self) -> bool {
143 self.display() != Display::None
144 }
145
146 pub fn is_visible(&self) -> bool {
150 self.visibility() == Visibility::Visible
151 }
152}
153
154macro_rules! make_properties {
184 {
185 shorthands: {
186 $($short_str:tt => ( $short_presentation_attr:expr, $short_field:ident: $short_name:ident ),)*
187 }
188
189 longhands: {
190 $($long_str:tt => ( $long_presentation_attr:expr, $long_field:ident: $long_name:ident ),)+
191 }
192
193 longhands_not_supported_by_markup5ever: {
196 $($long_m5e_str:tt => ($long_m5e_presentation_attr:expr, $long_m5e_field:ident: $long_m5e_name:ident ),)+
197 }
198
199 non_properties: {
200 $($nonprop_field:ident: $nonprop_name:ident,)+
201 }
202 }=> {
203 #[repr(u8)]
209 #[derive(Copy, Clone, PartialEq)]
210 enum PropertyId {
211 $($short_name,)+
212 $($long_name,)+
213 $($long_m5e_name,)+
214 $($nonprop_name,)+
215
216 UnsetProperty,
217 }
218
219 impl PropertyId {
220 fn is_shorthand(self) -> bool {
221 match self {
222 $(PropertyId::$short_name => true,)+
223 _ => false,
224 }
225 }
226 }
227
228 #[derive(Clone)]
230 pub enum ParsedProperty {
231 $($short_name(SpecifiedValue<$short_name>),)+
233 $($long_name(SpecifiedValue<$long_name>),)+
234 $($long_m5e_name(SpecifiedValue<$long_m5e_name>),)+
235 $($nonprop_name(SpecifiedValue<$nonprop_name>),)+
236 }
237
238 enum ComputedValue {
239 $(
240 $long_name($long_name),
241 )+
242
243 $(
244 $long_m5e_name($long_m5e_name),
245 )+
246
247 $(
248 $nonprop_name($nonprop_name),
249 )+
250 }
251
252 #[derive(Debug, Default, Clone)]
254 pub struct ComputedValues {
255 $(
256 $long_field: $long_name,
257 )+
258
259 $(
260 $long_m5e_field: $long_m5e_name,
261 )+
262
263 $(
264 $nonprop_field: $nonprop_name,
265 )+
266
267 transform: Transform,
268 }
269
270 impl ParsedProperty {
271 fn get_property_id(&self) -> PropertyId {
272 match *self {
273 $(ParsedProperty::$long_name(_) => PropertyId::$long_name,)+
274 $(ParsedProperty::$long_m5e_name(_) => PropertyId::$long_m5e_name,)+
275 $(ParsedProperty::$short_name(_) => PropertyId::$short_name,)+
276 $(ParsedProperty::$nonprop_name(_) => PropertyId::$nonprop_name,)+
277 }
278 }
279
280 fn unspecified(id: PropertyId) -> Self {
281 use SpecifiedValue::Unspecified;
282
283 match id {
284 $(PropertyId::$long_name => ParsedProperty::$long_name(Unspecified),)+
285 $(PropertyId::$long_m5e_name => ParsedProperty::$long_m5e_name(Unspecified),)+
286 $(PropertyId::$short_name => ParsedProperty::$short_name(Unspecified),)+
287 $(PropertyId::$nonprop_name => ParsedProperty::$nonprop_name(Unspecified),)+
288
289 PropertyId::UnsetProperty => unreachable!(),
290 }
291 }
292 }
293
294 impl ComputedValues {
295 $(
296 pub fn $long_field(&self) -> $long_name {
297 if let ComputedValue::$long_name(v) = self.get_value(PropertyId::$long_name) {
298 v
299 } else {
300 unreachable!();
301 }
302 }
303 )+
304
305 $(
306 pub fn $long_m5e_field(&self) -> $long_m5e_name {
307 if let ComputedValue::$long_m5e_name(v) = self.get_value(PropertyId::$long_m5e_name) {
308 v
309 } else {
310 unreachable!();
311 }
312 }
313 )+
314
315 $(
316 pub fn $nonprop_field(&self) -> $nonprop_name {
317 if let ComputedValue::$nonprop_name(v) = self.get_value(PropertyId::$nonprop_name) {
318 v
319 } else {
320 unreachable!();
321 }
322 }
323 )+
324
325 fn set_value(&mut self, computed: ComputedValue) {
326 match computed {
327 $(ComputedValue::$long_name(v) => self.$long_field = v,)+
328 $(ComputedValue::$long_m5e_name(v) => self.$long_m5e_field = v,)+
329 $(ComputedValue::$nonprop_name(v) => self.$nonprop_field = v,)+
330 }
331 }
332
333 fn get_value(&self, id: PropertyId) -> ComputedValue {
334 assert!(!id.is_shorthand());
335
336 match id {
337 $(
338 PropertyId::$long_name =>
339 ComputedValue::$long_name(self.$long_field.clone()),
340 )+
341 $(
342 PropertyId::$long_m5e_name =>
343 ComputedValue::$long_m5e_name(self.$long_m5e_field.clone()),
344 )+
345 $(
346 PropertyId::$nonprop_name =>
347 ComputedValue::$nonprop_name(self.$nonprop_field.clone()),
348 )+
349 _ => unreachable!(),
350 }
351 }
352 }
353
354 pub fn parse_value<'i>(
356 prop_name: &QualName,
357 input: &mut Parser<'i, '_>,
358 parse_as: ParseAs,
359 ) -> Result<ParsedProperty, ParseError<'i>> {
360 match prop_name.expanded() {
361 $(
362 expanded_name!("", $long_str) if !(parse_as == ParseAs::PresentationAttr && $long_presentation_attr == PresentationAttr::No) => {
363 Ok(ParsedProperty::$long_name(parse_input(input)?))
364 }
365 )+
366
367 $(
368 e if e == ExpandedName {
369 ns: &ns!(),
370 local: &LocalName::from($long_m5e_str),
371 } && !(parse_as == ParseAs::PresentationAttr && $long_m5e_presentation_attr == PresentationAttr::No) => {
372 Ok(ParsedProperty::$long_m5e_name(parse_input(input)?))
373 }
374 )+
375
376 $(
377 expanded_name!("", $short_str) if parse_as == ParseAs::Property => {
378 assert!($short_presentation_attr == PresentationAttr::No);
380
381 Ok(ParsedProperty::$short_name(parse_input(input)?))
382 }
383 )+
384
385 _ => {
386 let loc = input.current_source_location();
387 Err(loc.new_custom_error(ValueErrorKind::UnknownProperty))
388 }
389 }
390 }
391 };
392}
393
394#[rustfmt::skip]
395make_properties! {
396 shorthands: {
397 "font" => (PresentationAttr::No, font : Font),
399 "marker" => (PresentationAttr::No, marker : Marker),
400 }
401
402 longhands: {
406 "baseline-shift" => (PresentationAttr::Yes, baseline_shift : BaselineShift),
408 "clip-path" => (PresentationAttr::Yes, clip_path : ClipPath),
409 "clip-rule" => (PresentationAttr::Yes, clip_rule : ClipRule),
410 "color" => (PresentationAttr::Yes, color : Color),
411 "color-interpolation-filters" => (PresentationAttr::Yes, color_interpolation_filters : ColorInterpolationFilters),
413 "cx" => (PresentationAttr::Yes, cx: CX),
415 "cy" => (PresentationAttr::Yes, cy: CY),
416 "direction" => (PresentationAttr::Yes, direction : Direction),
417 "display" => (PresentationAttr::Yes, display : Display),
418 "dominant-baseline" => (PresentationAttr::Yes, dominant_baseline : DominantBaseline),
419 "enable-background" => (PresentationAttr::Yes, enable_background : EnableBackground),
420
421 "fill" => (PresentationAttr::Yes, fill : Fill),
424
425 "fill-opacity" => (PresentationAttr::Yes, fill_opacity : FillOpacity),
426 "fill-rule" => (PresentationAttr::Yes, fill_rule : FillRule),
427 "filter" => (PresentationAttr::Yes, filter : Filter),
428 "flood-color" => (PresentationAttr::Yes, flood_color : FloodColor),
429 "flood-opacity" => (PresentationAttr::Yes, flood_opacity : FloodOpacity),
430 "font-family" => (PresentationAttr::Yes, font_family : FontFamily),
431 "font-size" => (PresentationAttr::Yes, font_size : FontSize),
432 "font-stretch" => (PresentationAttr::Yes, font_stretch : FontStretch),
434 "font-style" => (PresentationAttr::Yes, font_style : FontStyle),
435 "font-variant" => (PresentationAttr::Yes, font_variant : FontVariant),
436 "font-weight" => (PresentationAttr::Yes, font_weight : FontWeight),
437
438 "glyph-orientation-vertical" => (PresentationAttr::Yes, glyph_orientation_vertical : GlyphOrientationVertical),
449 "height" => (PresentationAttr::Yes, height: Height),
450
451 "image-rendering" => (PresentationAttr::Yes, image_rendering : ImageRendering),
452 "letter-spacing" => (PresentationAttr::Yes, letter_spacing : LetterSpacing),
453 "lighting-color" => (PresentationAttr::Yes, lighting_color : LightingColor),
454 "marker-end" => (PresentationAttr::Yes, marker_end : MarkerEnd),
455 "marker-mid" => (PresentationAttr::Yes, marker_mid : MarkerMid),
456 "marker-start" => (PresentationAttr::Yes, marker_start : MarkerStart),
457 "mask" => (PresentationAttr::Yes, mask : Mask),
458 "opacity" => (PresentationAttr::Yes, opacity : Opacity),
459 "overflow" => (PresentationAttr::Yes, overflow : Overflow),
460 "r" => (PresentationAttr::Yes, r: R),
462 "rx" => (PresentationAttr::Yes, rx: RX),
463 "ry" => (PresentationAttr::Yes, ry: RY),
464 "shape-rendering" => (PresentationAttr::Yes, shape_rendering : ShapeRendering),
465 "stop-color" => (PresentationAttr::Yes, stop_color : StopColor),
466 "stop-opacity" => (PresentationAttr::Yes, stop_opacity : StopOpacity),
467 "stroke" => (PresentationAttr::Yes, stroke : Stroke),
468 "stroke-dasharray" => (PresentationAttr::Yes, stroke_dasharray : StrokeDasharray),
469 "stroke-dashoffset" => (PresentationAttr::Yes, stroke_dashoffset : StrokeDashoffset),
470 "stroke-linecap" => (PresentationAttr::Yes, stroke_line_cap : StrokeLinecap),
471 "stroke-linejoin" => (PresentationAttr::Yes, stroke_line_join : StrokeLinejoin),
472 "stroke-miterlimit" => (PresentationAttr::Yes, stroke_miterlimit : StrokeMiterlimit),
473 "stroke-opacity" => (PresentationAttr::Yes, stroke_opacity : StrokeOpacity),
474 "stroke-width" => (PresentationAttr::Yes, stroke_width : StrokeWidth),
475 "text-anchor" => (PresentationAttr::Yes, text_anchor : TextAnchor),
476 "text-decoration" => (PresentationAttr::Yes, text_decoration : TextDecoration),
477 "text-rendering" => (PresentationAttr::Yes, text_rendering : TextRendering),
479
480 "transform" => (PresentationAttr::No, transform_property : TransformProperty),
485
486 "unicode-bidi" => (PresentationAttr::Yes, unicode_bidi : UnicodeBidi),
489 "visibility" => (PresentationAttr::Yes, visibility : Visibility),
490 "width" => (PresentationAttr::Yes, width: Width),
492 "writing-mode" => (PresentationAttr::Yes, writing_mode : WritingMode),
493 "x" => (PresentationAttr::Yes, x: X),
494 "y" => (PresentationAttr::Yes, y: Y),
495 }
496
497 longhands_not_supported_by_markup5ever: {
498 "image-orientation" => (PresentationAttr::No, image_orientation : ImageOrientation),
499 "isolation" => (PresentationAttr::No, isolation : Isolation),
500 "line-height" => (PresentationAttr::No, line_height : LineHeight),
501 "mask-type" => (PresentationAttr::Yes, mask_type : MaskType),
502 "mix-blend-mode" => (PresentationAttr::No, mix_blend_mode : MixBlendMode),
503 "paint-order" => (PresentationAttr::Yes, paint_order : PaintOrder),
504 "text-orientation" => (PresentationAttr::No, text_orientation : TextOrientation),
505 "vector-effect" => (PresentationAttr::Yes, vector_effect : VectorEffect),
506 "white-space" => (PresentationAttr::Yes, white_space : WhiteSpace),
507 }
508
509 non_properties: {
513 xml_lang: XmlLang,
514 xml_space: XmlSpace,
515 }
516}
517
518impl SpecifiedValues {
519 fn property_index(&self, id: PropertyId) -> Option<usize> {
520 let v = self.indices[id.as_usize()];
521
522 if v == PropertyId::UnsetProperty.as_u8() {
523 None
524 } else {
525 Some(v as usize)
526 }
527 }
528
529 fn set_property(&mut self, prop: &ParsedProperty, replace: bool) {
530 let id = prop.get_property_id();
531 assert!(!id.is_shorthand());
532
533 if let Some(index) = self.property_index(id) {
534 if replace {
535 self.props[index] = prop.clone();
536 }
537 } else {
538 self.props.push(prop.clone());
539 let pos = self.props.len() - 1;
540 self.indices[id.as_usize()] = pos as u8;
541 }
542 }
543
544 fn get_property(&self, id: PropertyId) -> ParsedProperty {
545 assert!(!id.is_shorthand());
546
547 if let Some(index) = self.property_index(id) {
548 self.props[index].clone()
549 } else {
550 ParsedProperty::unspecified(id)
551 }
552 }
553
554 fn set_property_expanding_shorthands(&mut self, prop: &ParsedProperty, replace: bool) {
555 match *prop {
556 ParsedProperty::Font(SpecifiedValue::Specified(ref f)) => {
557 self.expand_font_shorthand(f, replace)
558 }
559 ParsedProperty::Marker(SpecifiedValue::Specified(ref m)) => {
560 self.expand_marker_shorthand(m, replace)
561 }
562 ParsedProperty::Font(SpecifiedValue::Inherit) => {
563 self.expand_font_shorthand_inherit(replace)
564 }
565 ParsedProperty::Marker(SpecifiedValue::Inherit) => {
566 self.expand_marker_shorthand_inherit(replace)
567 }
568
569 _ => self.set_property(prop, replace),
570 }
571 }
572
573 fn expand_font_shorthand(&mut self, font: &Font, replace: bool) {
574 let FontSpec {
575 style,
576 variant,
577 weight,
578 stretch,
579 size,
580 line_height,
581 family,
582 } = font.to_font_spec();
583
584 self.set_property(
585 &ParsedProperty::FontStyle(SpecifiedValue::Specified(style)),
586 replace,
587 );
588 self.set_property(
589 &ParsedProperty::FontVariant(SpecifiedValue::Specified(variant)),
590 replace,
591 );
592 self.set_property(
593 &ParsedProperty::FontWeight(SpecifiedValue::Specified(weight)),
594 replace,
595 );
596 self.set_property(
597 &ParsedProperty::FontStretch(SpecifiedValue::Specified(stretch)),
598 replace,
599 );
600 self.set_property(
601 &ParsedProperty::FontSize(SpecifiedValue::Specified(size)),
602 replace,
603 );
604 self.set_property(
605 &ParsedProperty::LineHeight(SpecifiedValue::Specified(line_height)),
606 replace,
607 );
608 self.set_property(
609 &ParsedProperty::FontFamily(SpecifiedValue::Specified(family)),
610 replace,
611 );
612 }
613
614 fn expand_marker_shorthand(&mut self, marker: &Marker, replace: bool) {
615 let Marker(v) = marker;
616
617 self.set_property(
618 &ParsedProperty::MarkerStart(SpecifiedValue::Specified(MarkerStart(v.clone()))),
619 replace,
620 );
621 self.set_property(
622 &ParsedProperty::MarkerMid(SpecifiedValue::Specified(MarkerMid(v.clone()))),
623 replace,
624 );
625 self.set_property(
626 &ParsedProperty::MarkerEnd(SpecifiedValue::Specified(MarkerEnd(v.clone()))),
627 replace,
628 );
629 }
630
631 fn expand_font_shorthand_inherit(&mut self, replace: bool) {
632 self.set_property(&ParsedProperty::FontStyle(SpecifiedValue::Inherit), replace);
633 self.set_property(
634 &ParsedProperty::FontVariant(SpecifiedValue::Inherit),
635 replace,
636 );
637 self.set_property(
638 &ParsedProperty::FontWeight(SpecifiedValue::Inherit),
639 replace,
640 );
641 self.set_property(
642 &ParsedProperty::FontStretch(SpecifiedValue::Inherit),
643 replace,
644 );
645 self.set_property(&ParsedProperty::FontSize(SpecifiedValue::Inherit), replace);
646 self.set_property(
647 &ParsedProperty::LineHeight(SpecifiedValue::Inherit),
648 replace,
649 );
650 self.set_property(
651 &ParsedProperty::FontFamily(SpecifiedValue::Inherit),
652 replace,
653 );
654 }
655
656 fn expand_marker_shorthand_inherit(&mut self, replace: bool) {
657 self.set_property(
658 &ParsedProperty::MarkerStart(SpecifiedValue::Inherit),
659 replace,
660 );
661 self.set_property(&ParsedProperty::MarkerMid(SpecifiedValue::Inherit), replace);
662 self.set_property(&ParsedProperty::MarkerEnd(SpecifiedValue::Inherit), replace);
663 }
664
665 pub fn set_parsed_property(&mut self, prop: &ParsedProperty) {
666 self.set_property_expanding_shorthands(prop, true);
667 }
668
669 pub fn set_parsed_property_user_agent(&mut self, prop: &ParsedProperty) {
671 self.set_property_expanding_shorthands(prop, false);
672 }
673
674 pub fn to_computed_values(&self, computed: &mut ComputedValues) {
675 macro_rules! compute {
676 ($name:ident, $field:ident) => {{
677 let prop_val = self.get_property(PropertyId::$name);
682 if let ParsedProperty::$name(s) = prop_val {
683 computed.set_value(ComputedValue::$name(
684 s.compute(&computed.$field(), computed),
685 ));
686 } else {
687 unreachable!();
688 }
689 }};
690 }
691
692 compute!(FontSize, font_size);
698
699 compute!(BaselineShift, baseline_shift);
702 compute!(ClipPath, clip_path);
703 compute!(ClipRule, clip_rule);
704 compute!(Color, color);
705 compute!(ColorInterpolationFilters, color_interpolation_filters);
706 compute!(CX, cx);
707 compute!(CY, cy);
708 compute!(Direction, direction);
709 compute!(Display, display);
710 compute!(DominantBaseline, dominant_baseline);
711 compute!(EnableBackground, enable_background);
712 compute!(Fill, fill);
713 compute!(FillOpacity, fill_opacity);
714 compute!(FillRule, fill_rule);
715 compute!(Filter, filter);
716 compute!(FloodColor, flood_color);
717 compute!(FloodOpacity, flood_opacity);
718 compute!(FontFamily, font_family);
719 compute!(FontStretch, font_stretch);
720 compute!(FontStyle, font_style);
721 compute!(FontVariant, font_variant);
722 compute!(FontWeight, font_weight);
723 compute!(GlyphOrientationVertical, glyph_orientation_vertical);
724 compute!(Height, height);
725 compute!(ImageOrientation, image_orientation);
726 compute!(ImageRendering, image_rendering);
727 compute!(Isolation, isolation);
728 compute!(LetterSpacing, letter_spacing);
729 compute!(LightingColor, lighting_color);
730 compute!(MarkerEnd, marker_end);
731 compute!(MarkerMid, marker_mid);
732 compute!(MarkerStart, marker_start);
733 compute!(Mask, mask);
734 compute!(MaskType, mask_type);
735 compute!(MixBlendMode, mix_blend_mode);
736 compute!(Opacity, opacity);
737 compute!(Overflow, overflow);
738 compute!(PaintOrder, paint_order);
739 compute!(R, r);
740 compute!(RX, rx);
741 compute!(RY, ry);
742 compute!(ShapeRendering, shape_rendering);
743 compute!(StopColor, stop_color);
744 compute!(StopOpacity, stop_opacity);
745 compute!(Stroke, stroke);
746 compute!(StrokeDasharray, stroke_dasharray);
747 compute!(StrokeDashoffset, stroke_dashoffset);
748 compute!(StrokeLinecap, stroke_line_cap);
749 compute!(StrokeLinejoin, stroke_line_join);
750 compute!(StrokeOpacity, stroke_opacity);
751 compute!(StrokeMiterlimit, stroke_miterlimit);
752 compute!(StrokeWidth, stroke_width);
753 compute!(TextAnchor, text_anchor);
754 compute!(TextDecoration, text_decoration);
755 compute!(TextOrientation, text_orientation);
756 compute!(TextRendering, text_rendering);
757 compute!(TransformProperty, transform_property);
758 compute!(UnicodeBidi, unicode_bidi);
759 compute!(VectorEffect, vector_effect);
760 compute!(Visibility, visibility);
761 compute!(Width, width);
762 compute!(WhiteSpace, white_space);
763 compute!(WritingMode, writing_mode);
764 compute!(X, x);
765 compute!(XmlSpace, xml_space);
766 compute!(XmlLang, xml_lang);
767 compute!(Y, y);
768
769 computed.transform = self.transform.unwrap_or_else(|| {
770 match self.get_property(PropertyId::TransformProperty) {
771 ParsedProperty::TransformProperty(SpecifiedValue::Specified(ref t)) => {
772 t.to_transform()
773 }
774 _ => Transform::identity(),
775 }
776 });
777 }
778
779 pub fn inherit_xml_lang(
784 &self,
785 computed: &mut ComputedValues,
786 parent: Option<crate::node::Node>,
787 ) {
788 use crate::node::NodeBorrow;
789 let prop_val = self.get_property(PropertyId::XmlLang);
790 if let ParsedProperty::XmlLang(s) = prop_val {
791 if let Some(parent) = parent {
792 computed.set_value(ComputedValue::XmlLang(
793 parent.borrow_element().get_computed_values().xml_lang(),
794 ));
795 }
796 computed.set_value(ComputedValue::XmlLang(
797 s.compute(&computed.xml_lang(), computed),
798 ));
799 } else {
800 unreachable!();
801 }
802 }
803
804 fn parse_one_presentation_attribute(&mut self, session: &Session, attr: QualName, value: &str) {
805 let mut input = ParserInput::new(value);
806 let mut parser = Parser::new(&mut input);
807
808 match parse_value(&attr, &mut parser, ParseAs::PresentationAttr) {
809 Ok(prop) => {
810 if parser.expect_exhausted().is_ok() {
811 self.set_parsed_property(&prop);
812 } else {
813 rsvg_log!(
814 session,
815 "(ignoring invalid presentation attribute {:?}\n value=\"{}\")\n",
816 attr.expanded(),
817 value,
818 );
819 }
820 }
821
822 Err(ParseError {
824 kind: ParseErrorKind::Custom(ValueErrorKind::UnknownProperty),
825 ..
826 }) => (),
827
828 Err(ParseError {
832 kind: ParseErrorKind::Basic(BasicParseErrorKind::UnexpectedToken(ref t)),
833 ..
834 }) => {
835 let mut tok = String::new();
836
837 t.to_css(&mut tok).unwrap(); rsvg_log!(
839 session,
840 "(ignoring invalid presentation attribute {:?}\n value=\"{}\"\n \
841 unexpected token '{}')",
842 attr.expanded(),
843 value,
844 tok,
845 );
846 }
847
848 Err(ParseError {
849 kind: ParseErrorKind::Basic(BasicParseErrorKind::EndOfInput),
850 ..
851 }) => {
852 rsvg_log!(
853 session,
854 "(ignoring invalid presentation attribute {:?}\n value=\"{}\"\n \
855 unexpected end of input)",
856 attr.expanded(),
857 value,
858 );
859 }
860
861 Err(ParseError {
862 kind: ParseErrorKind::Basic(_),
863 ..
864 }) => {
865 rsvg_log!(
866 session,
867 "(ignoring invalid presentation attribute {:?}\n value=\"{}\"\n \
868 unexpected error)",
869 attr.expanded(),
870 value,
871 );
872 }
873
874 Err(ParseError {
875 kind: ParseErrorKind::Custom(ref v),
876 ..
877 }) => {
878 rsvg_log!(
879 session,
880 "(ignoring invalid presentation attribute {:?}\n value=\"{}\"\n {})",
881 attr.expanded(),
882 value,
883 v
884 );
885 }
886 }
887 }
888
889 pub fn parse_presentation_attributes(&mut self, session: &Session, attrs: &Attributes) {
890 for (attr, value) in attrs.iter() {
891 match attr.expanded() {
892 expanded_name!("", "transform") => {
893 let transform_attr = TransformAttribute::parse_str(value)
897 .unwrap_or_else(|_| TransformAttribute::default());
898 self.transform = Some(transform_attr.to_transform());
899 }
900
901 expanded_name!(xml "lang") => {
902 let parse_result: Result<XmlLang, _> = attr.parse(value);
906 match parse_result {
907 Ok(lang) => {
908 self.set_parsed_property(&ParsedProperty::XmlLang(
909 SpecifiedValue::Specified(lang),
910 ));
911 }
912
913 Err(e) => {
914 rsvg_log!(session, "ignoring attribute with invalid value: {}", e);
915 }
916 }
917 }
918
919 expanded_name!(xml "space") => {
920 let parse_result: Result<XmlSpace, _> = attr.parse(value);
924 match parse_result {
925 Ok(space) => {
926 self.set_parsed_property(&ParsedProperty::XmlSpace(
927 SpecifiedValue::Specified(space),
928 ));
929 }
930
931 Err(e) => {
932 rsvg_log!(session, "ignoring attribute with invalid value: {}", e);
933 }
934 }
935 }
936
937 _ => self.parse_one_presentation_attribute(session, attr, value),
938 }
939 }
940 }
941
942 pub fn set_property_from_declaration(
943 &mut self,
944 declaration: &Declaration,
945 origin: Origin,
946 important_styles: &mut HashSet<QualName>,
947 ) {
948 if !declaration.important && important_styles.contains(&declaration.prop_name) {
949 return;
950 }
951
952 if declaration.important {
953 important_styles.insert(declaration.prop_name.clone());
954 }
955
956 if origin == Origin::UserAgent {
957 self.set_parsed_property_user_agent(&declaration.property);
958 } else {
959 self.set_parsed_property(&declaration.property);
960 }
961 }
962
963 pub fn parse_style_declarations(
964 &mut self,
965 declarations: &str,
966 origin: Origin,
967 important_styles: &mut HashSet<QualName>,
968 session: &Session,
969 ) {
970 let mut input = ParserInput::new(declarations);
971 let mut parser = Parser::new(&mut input);
972
973 RuleBodyParser::new(&mut parser, &mut DeclParser)
974 .filter_map(|r| match r {
975 Ok(RuleBodyItem::Decl(decl)) => Some(decl),
976 Ok(RuleBodyItem::Rule(_)) => None,
977 Err(e) => {
978 rsvg_log!(session, "Invalid declaration; ignoring: {:?}", e);
979 None
980 }
981 })
982 .for_each(|decl| self.set_property_from_declaration(&decl, origin, important_styles));
983 }
984}
985
986fn parse_input<'i, T>(input: &mut Parser<'i, '_>) -> Result<SpecifiedValue<T>, ParseError<'i>>
988where
989 T: Property + Clone + Default + Parse,
990{
991 if input
992 .try_parse(|p| p.expect_ident_matching("inherit"))
993 .is_ok()
994 {
995 Ok(SpecifiedValue::Inherit)
996 } else {
997 Parse::parse(input).map(SpecifiedValue::Specified)
998 }
999}
1000
1001#[cfg(test)]
1002mod tests {
1003 use super::*;
1004 use crate::iri::Iri;
1005 use crate::length::*;
1006
1007 #[test]
1008 fn empty_values_computes_to_defaults() {
1009 let specified = SpecifiedValues::default();
1010
1011 let mut computed = ComputedValues::default();
1012 specified.to_computed_values(&mut computed);
1013
1014 assert_eq!(computed.stroke_width(), StrokeWidth::default());
1015 }
1016
1017 #[test]
1018 fn set_one_property() {
1019 let length = Length::<Both>::new(42.0, LengthUnit::Px);
1020
1021 let mut specified = SpecifiedValues::default();
1022 specified.set_parsed_property(&ParsedProperty::StrokeWidth(SpecifiedValue::Specified(
1023 StrokeWidth(length),
1024 )));
1025
1026 let mut computed = ComputedValues::default();
1027 specified.to_computed_values(&mut computed);
1028
1029 assert_eq!(computed.stroke_width(), StrokeWidth(length));
1030 }
1031
1032 #[test]
1033 fn replace_existing_property() {
1034 let length1 = Length::<Both>::new(42.0, LengthUnit::Px);
1035 let length2 = Length::<Both>::new(42.0, LengthUnit::Px);
1036
1037 let mut specified = SpecifiedValues::default();
1038
1039 specified.set_parsed_property(&ParsedProperty::StrokeWidth(SpecifiedValue::Specified(
1040 StrokeWidth(length1),
1041 )));
1042
1043 specified.set_parsed_property(&ParsedProperty::StrokeWidth(SpecifiedValue::Specified(
1044 StrokeWidth(length2),
1045 )));
1046
1047 let mut computed = ComputedValues::default();
1048 specified.to_computed_values(&mut computed);
1049
1050 assert_eq!(computed.stroke_width(), StrokeWidth(length2));
1051 }
1052
1053 #[test]
1054 fn expands_marker_shorthand() {
1055 let mut specified = SpecifiedValues::default();
1056 let iri = Iri::parse_str("url(#foo)").unwrap();
1057
1058 let marker = Marker(iri.clone());
1059 specified.set_parsed_property(&ParsedProperty::Marker(SpecifiedValue::Specified(marker)));
1060
1061 let mut computed = ComputedValues::default();
1062 specified.to_computed_values(&mut computed);
1063
1064 assert_eq!(computed.marker_start(), MarkerStart(iri.clone()));
1065 assert_eq!(computed.marker_mid(), MarkerMid(iri.clone()));
1066 assert_eq!(computed.marker_end(), MarkerEnd(iri.clone()));
1067 }
1068
1069 #[test]
1070 fn replaces_marker_shorthand() {
1071 let mut specified = SpecifiedValues::default();
1072 let iri1 = Iri::parse_str("url(#foo)").unwrap();
1073 let iri2 = Iri::None;
1074
1075 let marker1 = Marker(iri1.clone());
1076 specified.set_parsed_property(&ParsedProperty::Marker(SpecifiedValue::Specified(marker1)));
1077
1078 let marker2 = Marker(iri2.clone());
1079 specified.set_parsed_property(&ParsedProperty::Marker(SpecifiedValue::Specified(marker2)));
1080
1081 let mut computed = ComputedValues::default();
1082 specified.to_computed_values(&mut computed);
1083
1084 assert_eq!(computed.marker_start(), MarkerStart(iri2.clone()));
1085 assert_eq!(computed.marker_mid(), MarkerMid(iri2.clone()));
1086 assert_eq!(computed.marker_end(), MarkerEnd(iri2.clone()));
1087 }
1088
1089 #[test]
1090 fn computes_property_that_does_not_inherit_automatically() {
1091 assert!(!<Opacity as Property>::inherits_automatically());
1092
1093 let half_opacity = Opacity::parse_str("0.5").unwrap();
1094
1095 let mut with_opacity = SpecifiedValues::default();
1098 with_opacity.set_parsed_property(&ParsedProperty::Opacity(SpecifiedValue::Specified(
1099 half_opacity.clone(),
1100 )));
1101
1102 let mut computed_0_5 = ComputedValues::default();
1103 with_opacity.to_computed_values(&mut computed_0_5);
1104
1105 assert_eq!(computed_0_5.opacity(), half_opacity.clone());
1106
1107 let without_opacity = SpecifiedValues::default();
1110
1111 let mut computed = computed_0_5.clone();
1112 without_opacity.to_computed_values(&mut computed);
1113
1114 assert_eq!(computed.opacity(), Opacity::default());
1115
1116 let mut with_inherit_opacity = SpecifiedValues::default();
1119 with_inherit_opacity.set_parsed_property(&ParsedProperty::Opacity(SpecifiedValue::Inherit));
1120
1121 let mut computed = computed_0_5.clone();
1122 with_inherit_opacity.to_computed_values(&mut computed);
1123
1124 assert_eq!(computed.opacity(), half_opacity.clone());
1125 }
1126}