[librsvg/librsvg-2.42: 4/17] Rustfmt.
- From: Federico Mena Quintero <federico src gnome org>
- To: commits-list gnome org
- Cc:
- Subject: [librsvg/librsvg-2.42: 4/17] Rustfmt.
- Date: Fri, 2 Mar 2018 20:33:35 +0000 (UTC)
commit b2f5b0f4356a994912ab6f298a4aa485fb528c8f
Author: Jordan Petridis <jordanpetridis protonmail com>
Date: Wed Feb 28 13:25:26 2018 +0200
Rustfmt.
rsvg_internals/build.rs | 296 ++++----
rsvg_internals/src/aspect_ratio.rs | 448 ++++++++----
rsvg_internals/src/attributes.rs | 23 +-
rsvg_internals/src/bbox.rs | 119 +--
rsvg_internals/src/clip_path.rs | 29 +-
rsvg_internals/src/cnode.rs | 93 ++-
rsvg_internals/src/color.rs | 255 ++++---
rsvg_internals/src/coord_units.rs | 30 +-
rsvg_internals/src/drawing_ctx.rs | 343 ++++-----
rsvg_internals/src/error.rs | 78 +-
rsvg_internals/src/gradient.rs | 598 ++++++++-------
rsvg_internals/src/image.rs | 114 +--
rsvg_internals/src/length.rs | 595 ++++++++-------
rsvg_internals/src/lib.rs | 228 ++----
rsvg_internals/src/link.rs | 53 +-
rsvg_internals/src/marker.rs | 1156 +++++++++++++++--------------
rsvg_internals/src/mask.rs | 128 ++--
rsvg_internals/src/node.rs | 425 +++++------
rsvg_internals/src/opacity.rs | 186 +++--
rsvg_internals/src/paint_server.rs | 257 +++----
rsvg_internals/src/parsers.rs | 340 ++++-----
rsvg_internals/src/path_builder.rs | 175 ++---
rsvg_internals/src/path_parser.rs | 1420 +++++++++++++++---------------------
rsvg_internals/src/pattern.rs | 423 ++++++-----
rsvg_internals/src/property_bag.rs | 49 +-
rsvg_internals/src/shapes.rs | 456 ++++++------
rsvg_internals/src/space.rs | 60 +-
rsvg_internals/src/state.rs | 44 +-
rsvg_internals/src/stop.rs | 121 ++-
rsvg_internals/src/structure.rs | 523 ++++++-------
rsvg_internals/src/text.rs | 35 +-
rsvg_internals/src/transform.rs | 351 +++++----
rsvg_internals/src/util.rs | 10 +-
rsvg_internals/src/viewbox.rs | 66 +-
rsvg_internals/src/viewport.rs | 94 +--
35 files changed, 4817 insertions(+), 4804 deletions(-)
---
diff --git a/rsvg_internals/build.rs b/rsvg_internals/build.rs
index 421f39b0..12d2b99a 100644
--- a/rsvg_internals/build.rs
+++ b/rsvg_internals/build.rs
@@ -14,154 +14,152 @@ fn generate_phf_of_svg_attributes() {
// (attribute name, Rust enum value)
//
// Keep this in sync with rsvg-attributes.h
- let attribute_defs = [
- ( "alternate", "Alternate" ),
- ( "amplitude", "Amplitude" ),
- ( "azimuth", "Azimuth" ),
- ( "baseFrequency", "BaseFrequency" ),
- ( "baseline-shift", "BaselineShift" ),
- ( "bias", "Bias" ),
- ( "class", "Class" ),
- ( "clip-path", "ClipPath" ),
- ( "clip-rule", "ClipRule" ),
- ( "clipPathUnits", "ClipPathUnits" ),
- ( "color", "Color" ),
- ( "comp-op", "CompOp" ),
- ( "cx", "Cx" ),
- ( "cy", "Cy" ),
- ( "d", "D" ),
- ( "diffuseConstant", "DiffuseConstant" ),
- ( "direction", "Direction" ),
- ( "display", "Display" ),
- ( "divisor", "Divisor" ),
- ( "dx", "Dx" ),
- ( "dy", "Dy" ),
- ( "edgeMode", "EdgeMode" ),
- ( "elevation", "Elevation" ),
- ( "enable-background", "EnableBackground" ),
- ( "encoding", "Encoding" ),
- ( "exponent", "Exponent" ),
- ( "fill", "Fill" ),
- ( "fill-opacity", "FillOpacity" ),
- ( "fill-rule", "FillRule" ),
- ( "filter", "Filter" ),
- ( "filterUnits", "FilterUnits" ),
- ( "flood-color", "FloodColor" ),
- ( "flood-opacity", "FloodOpacity" ),
- ( "font-family", "FontFamily" ),
- ( "font-size", "FontSize" ),
- ( "font-stretch", "FontStretch" ),
- ( "font-style", "FontStyle" ),
- ( "font-variant", "FontVariant" ),
- ( "font-weight", "FontWeight" ),
- ( "fx", "Fx" ),
- ( "fy", "Fy" ),
- ( "gradientTransform", "GradientTransform" ),
- ( "gradientUnits", "GradientUnits" ),
- ( "height", "Height" ),
- ( "href", "Href" ),
- ( "id", "Id" ),
- ( "in", "In" ),
- ( "in2", "In2" ),
- ( "intercept", "Intercept" ),
- ( "k1", "K1" ),
- ( "k2", "K2" ),
- ( "k3", "K3" ),
- ( "k4", "K4" ),
- ( "kernelMatrix", "KernelMatrix" ),
- ( "kernelUnitLength", "KernelUnitLength" ),
- ( "letter-spacing", "LetterSpacing" ),
- ( "lighting-color", "LightingColor" ),
- ( "limitingConeAngle", "LimitingConeAngle" ),
- ( "marker", "Marker" ),
- ( "marker-end", "MarkerEnd" ),
- ( "marker-mid", "MarkerMid" ),
- ( "marker-start", "MarkerStart" ),
- ( "markerHeight", "MarkerHeight" ),
- ( "markerUnits", "MarkerUnits" ),
- ( "markerWidth", "MarkerWidth" ),
- ( "mask", "Mask" ),
- ( "maskContentUnits", "MaskContentUnits" ),
- ( "maskUnits", "MaskUnits" ),
- ( "mode", "Mode" ),
- ( "numOctaves", "NumOctaves" ),
- ( "offset", "Offset" ),
- ( "opacity", "Opacity" ),
- ( "operator", "Operator" ),
- ( "order", "Order" ),
- ( "orient", "Orient" ),
- ( "overflow", "Overflow" ),
- ( "parse", "Parse" ),
- ( "path", "Path" ),
- ( "patternContentUnits", "PatternContentUnits" ),
- ( "patternTransform", "PatternTransform" ),
- ( "patternUnits", "PatternUnits" ),
- ( "points", "Points" ),
- ( "pointsAtX", "PointsAtX" ),
- ( "pointsAtY", "PointsAtY" ),
- ( "pointsAtZ", "PointsAtZ" ),
- ( "preserveAlpha", "PreserveAlpha" ),
- ( "preserveAspectRatio", "PreserveAspectRatio" ),
- ( "primitiveUnits", "PrimitiveUnits" ),
- ( "r", "R" ),
- ( "radius", "Radius" ),
- ( "refX", "RefX" ),
- ( "refY", "RefY" ),
- ( "requiredExtensions", "RequiredExtensions" ),
- ( "requiredFeatures", "RequiredFeatures" ),
- ( "result", "Result" ),
- ( "rx", "Rx" ),
- ( "ry", "Ry" ),
- ( "scale", "Scale" ),
- ( "seed", "Seed" ),
- ( "shape-rendering", "ShapeRendering" ),
- ( "slope", "Slope" ),
- ( "specularConstant", "SpecularConstant" ),
- ( "specularExponent", "SpecularExponent" ),
- ( "spreadMethod", "SpreadMethod" ),
- ( "stdDeviation", "StdDeviation" ),
- ( "stitchTiles", "StitchTiles" ),
- ( "stop-color", "StopColor" ),
- ( "stop-opacity", "StopOpacity" ),
- ( "stroke", "Stroke" ),
- ( "stroke-dasharray", "StrokeDasharray" ),
- ( "stroke-dashoffset", "StrokeDashoffset" ),
- ( "stroke-linecap", "StrokeLinecap" ),
- ( "stroke-linejoin", "StrokeLinejoin" ),
- ( "stroke-miterlimit", "StrokeMiterlimit" ),
- ( "stroke-opacity", "StrokeOpacity" ),
- ( "stroke-width", "StrokeWidth" ),
- ( "style", "Style" ),
- ( "surfaceScale", "SurfaceScale" ),
- ( "systemLanguage", "SystemLanguage" ),
- ( "tableValues", "TableValues" ),
- ( "targetX", "TargetX" ),
- ( "targetY", "TargetY" ),
- ( "text-anchor", "TextAnchor" ),
- ( "text-decoration", "TextDecoration" ),
- ( "text-rendering", "TextRendering" ),
- ( "transform", "Transform" ),
- ( "type", "Type" ),
- ( "unicode-bidi", "UnicodeBidi" ),
- ( "values", "Values" ),
- ( "verts", "Verts" ),
- ( "viewBox", "ViewBox" ),
- ( "visibility", "Visibility" ),
- ( "width", "Width" ),
- ( "writing-mode", "WritingMode" ),
- ( "x", "X" ),
- ( "x1", "X1" ),
- ( "y1", "Y1" ),
- ( "x2", "X2" ),
- ( "y2", "Y2" ),
- ( "xChannelSelector", "XChannelSelector" ),
- ( "xlink:href", "XlinkHref" ),
- ( "xml:lang", "XmlLang" ),
- ( "xml:space", "XmlSpace" ),
- ( "y", "Y" ),
- ( "yChannelSelector", "YChannelSelector" ),
- ( "z", "Z" ),
- ];
+ let attribute_defs = [("alternate", "Alternate"),
+ ("amplitude", "Amplitude"),
+ ("azimuth", "Azimuth"),
+ ("baseFrequency", "BaseFrequency"),
+ ("baseline-shift", "BaselineShift"),
+ ("bias", "Bias"),
+ ("class", "Class"),
+ ("clip-path", "ClipPath"),
+ ("clip-rule", "ClipRule"),
+ ("clipPathUnits", "ClipPathUnits"),
+ ("color", "Color"),
+ ("comp-op", "CompOp"),
+ ("cx", "Cx"),
+ ("cy", "Cy"),
+ ("d", "D"),
+ ("diffuseConstant", "DiffuseConstant"),
+ ("direction", "Direction"),
+ ("display", "Display"),
+ ("divisor", "Divisor"),
+ ("dx", "Dx"),
+ ("dy", "Dy"),
+ ("edgeMode", "EdgeMode"),
+ ("elevation", "Elevation"),
+ ("enable-background", "EnableBackground"),
+ ("encoding", "Encoding"),
+ ("exponent", "Exponent"),
+ ("fill", "Fill"),
+ ("fill-opacity", "FillOpacity"),
+ ("fill-rule", "FillRule"),
+ ("filter", "Filter"),
+ ("filterUnits", "FilterUnits"),
+ ("flood-color", "FloodColor"),
+ ("flood-opacity", "FloodOpacity"),
+ ("font-family", "FontFamily"),
+ ("font-size", "FontSize"),
+ ("font-stretch", "FontStretch"),
+ ("font-style", "FontStyle"),
+ ("font-variant", "FontVariant"),
+ ("font-weight", "FontWeight"),
+ ("fx", "Fx"),
+ ("fy", "Fy"),
+ ("gradientTransform", "GradientTransform"),
+ ("gradientUnits", "GradientUnits"),
+ ("height", "Height"),
+ ("href", "Href"),
+ ("id", "Id"),
+ ("in", "In"),
+ ("in2", "In2"),
+ ("intercept", "Intercept"),
+ ("k1", "K1"),
+ ("k2", "K2"),
+ ("k3", "K3"),
+ ("k4", "K4"),
+ ("kernelMatrix", "KernelMatrix"),
+ ("kernelUnitLength", "KernelUnitLength"),
+ ("letter-spacing", "LetterSpacing"),
+ ("lighting-color", "LightingColor"),
+ ("limitingConeAngle", "LimitingConeAngle"),
+ ("marker", "Marker"),
+ ("marker-end", "MarkerEnd"),
+ ("marker-mid", "MarkerMid"),
+ ("marker-start", "MarkerStart"),
+ ("markerHeight", "MarkerHeight"),
+ ("markerUnits", "MarkerUnits"),
+ ("markerWidth", "MarkerWidth"),
+ ("mask", "Mask"),
+ ("maskContentUnits", "MaskContentUnits"),
+ ("maskUnits", "MaskUnits"),
+ ("mode", "Mode"),
+ ("numOctaves", "NumOctaves"),
+ ("offset", "Offset"),
+ ("opacity", "Opacity"),
+ ("operator", "Operator"),
+ ("order", "Order"),
+ ("orient", "Orient"),
+ ("overflow", "Overflow"),
+ ("parse", "Parse"),
+ ("path", "Path"),
+ ("patternContentUnits", "PatternContentUnits"),
+ ("patternTransform", "PatternTransform"),
+ ("patternUnits", "PatternUnits"),
+ ("points", "Points"),
+ ("pointsAtX", "PointsAtX"),
+ ("pointsAtY", "PointsAtY"),
+ ("pointsAtZ", "PointsAtZ"),
+ ("preserveAlpha", "PreserveAlpha"),
+ ("preserveAspectRatio", "PreserveAspectRatio"),
+ ("primitiveUnits", "PrimitiveUnits"),
+ ("r", "R"),
+ ("radius", "Radius"),
+ ("refX", "RefX"),
+ ("refY", "RefY"),
+ ("requiredExtensions", "RequiredExtensions"),
+ ("requiredFeatures", "RequiredFeatures"),
+ ("result", "Result"),
+ ("rx", "Rx"),
+ ("ry", "Ry"),
+ ("scale", "Scale"),
+ ("seed", "Seed"),
+ ("shape-rendering", "ShapeRendering"),
+ ("slope", "Slope"),
+ ("specularConstant", "SpecularConstant"),
+ ("specularExponent", "SpecularExponent"),
+ ("spreadMethod", "SpreadMethod"),
+ ("stdDeviation", "StdDeviation"),
+ ("stitchTiles", "StitchTiles"),
+ ("stop-color", "StopColor"),
+ ("stop-opacity", "StopOpacity"),
+ ("stroke", "Stroke"),
+ ("stroke-dasharray", "StrokeDasharray"),
+ ("stroke-dashoffset", "StrokeDashoffset"),
+ ("stroke-linecap", "StrokeLinecap"),
+ ("stroke-linejoin", "StrokeLinejoin"),
+ ("stroke-miterlimit", "StrokeMiterlimit"),
+ ("stroke-opacity", "StrokeOpacity"),
+ ("stroke-width", "StrokeWidth"),
+ ("style", "Style"),
+ ("surfaceScale", "SurfaceScale"),
+ ("systemLanguage", "SystemLanguage"),
+ ("tableValues", "TableValues"),
+ ("targetX", "TargetX"),
+ ("targetY", "TargetY"),
+ ("text-anchor", "TextAnchor"),
+ ("text-decoration", "TextDecoration"),
+ ("text-rendering", "TextRendering"),
+ ("transform", "Transform"),
+ ("type", "Type"),
+ ("unicode-bidi", "UnicodeBidi"),
+ ("values", "Values"),
+ ("verts", "Verts"),
+ ("viewBox", "ViewBox"),
+ ("visibility", "Visibility"),
+ ("width", "Width"),
+ ("writing-mode", "WritingMode"),
+ ("x", "X"),
+ ("x1", "X1"),
+ ("y1", "Y1"),
+ ("x2", "X2"),
+ ("y2", "Y2"),
+ ("xChannelSelector", "XChannelSelector"),
+ ("xlink:href", "XlinkHref"),
+ ("xml:lang", "XmlLang"),
+ ("xml:space", "XmlSpace"),
+ ("y", "Y"),
+ ("yChannelSelector", "YChannelSelector"),
+ ("z", "Z")];
let path = Path::new(&env::var("OUT_DIR").unwrap()).join("attributes-codegen.rs");
let mut file = BufWriter::new(File::create(&path).unwrap());
@@ -173,7 +171,7 @@ fn generate_phf_of_svg_attributes() {
for &(_, valname) in attribute_defs.iter() {
writeln!(&mut file, " {},", valname).unwrap();
}
-
+
writeln!(&mut file, "}}").unwrap();
writeln!(&mut file, "static ATTRIBUTES: phf::Map<&'static str, Attribute> = ").unwrap();
diff --git a/rsvg_internals/src/aspect_ratio.rs b/rsvg_internals/src/aspect_ratio.rs
index aea983eb..32490ff4 100644
--- a/rsvg_internals/src/aspect_ratio.rs
+++ b/rsvg_internals/src/aspect_ratio.rs
@@ -4,23 +4,23 @@
//! We have an [`AspectRatio`] struct which encapsulates such a value.
//!
//! ```
-//! assert_eq! (AspectRatio::parse ("xMidYMid", ()),
-//! Ok (AspectRatio { defer: false,
-//! align: Align::Aligned { align: AlignMode::XmidYmid,
-//! fit: FitMode::Meet } }));
+//! assert_eq!(AspectRatio::parse("xMidYMid", ()),
+//! Ok(AspectRatio { defer: false,
+//! align: Align::Aligned { align: AlignMode::XmidYmid,
+//! fit: FitMode::Meet, }, }));
//! ```
//!
//! [`AspectRatio`]: struct.AspectRatio.html
//! [spec]: https://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute
+use error::*;
use parsers::Parse;
use parsers::ParseError;
-use error::*;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum FitMode {
Meet,
- Slice
+ Slice,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
@@ -33,49 +33,47 @@ pub enum AlignMode {
XmaxYmid,
XminYmax,
XmidYmax,
- XmaxYmax
+ XmaxYmax,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Align {
None,
- Aligned {
- align: AlignMode,
- fit: FitMode
- }
+ Aligned { align: AlignMode, fit: FitMode },
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct AspectRatio {
pub defer: bool,
- pub align: Align
+ pub align: Align,
}
#[derive(Debug, Copy, Clone)]
enum Align1D {
Min,
Mid,
- Max
+ Max,
}
-fn align_1d (a: Align1D, dest_pos: f64, dest_size: f64, obj_size: f64) -> f64 {
+fn align_1d(a: Align1D, dest_pos: f64, dest_size: f64, obj_size: f64) -> f64 {
match a {
- Align1D::Min => { dest_pos },
- Align1D::Mid => { dest_pos + (dest_size - obj_size) / 2.0 },
- Align1D::Max => { dest_pos + dest_size - obj_size }
+ Align1D::Min => dest_pos,
+ Align1D::Mid => dest_pos + (dest_size - obj_size) / 2.0,
+ Align1D::Max => dest_pos + dest_size - obj_size,
}
}
impl AspectRatio {
- pub fn compute (&self,
- object_width: f64,
- object_height: f64,
- dest_x: f64,
- dest_y: f64,
- dest_width: f64,
- dest_height: f64) -> (f64, f64, f64, f64) {
+ pub fn compute(&self,
+ object_width: f64,
+ object_height: f64,
+ dest_x: f64,
+ dest_y: f64,
+ dest_width: f64,
+ dest_height: f64)
+ -> (f64, f64, f64, f64) {
match self.align {
- Align::None => { (dest_x, dest_y, dest_width, dest_height) }
+ Align::None => (dest_x, dest_y, dest_width, dest_height),
Align::Aligned { align, fit } => {
let w_factor = dest_width / object_width;
@@ -83,8 +81,12 @@ impl AspectRatio {
let factor: f64;
match fit {
- FitMode::Meet => { factor = w_factor.min (h_factor); }
- FitMode::Slice => { factor = w_factor.max (h_factor); }
+ FitMode::Meet => {
+ factor = w_factor.min(h_factor);
+ }
+ FitMode::Slice => {
+ factor = w_factor.max(h_factor);
+ }
}
let w = object_width * factor;
@@ -94,19 +96,46 @@ impl AspectRatio {
let yalign: Align1D;
match align {
- AlignMode::XminYmin => { xalign = Align1D::Min; yalign = Align1D::Min; },
- AlignMode::XminYmid => { xalign = Align1D::Min; yalign = Align1D::Mid; },
- AlignMode::XminYmax => { xalign = Align1D::Min; yalign = Align1D::Max; },
- AlignMode::XmidYmin => { xalign = Align1D::Mid; yalign = Align1D::Min; },
- AlignMode::XmidYmid => { xalign = Align1D::Mid; yalign = Align1D::Mid; },
- AlignMode::XmidYmax => { xalign = Align1D::Mid; yalign = Align1D::Max; },
- AlignMode::XmaxYmin => { xalign = Align1D::Max; yalign = Align1D::Min; },
- AlignMode::XmaxYmid => { xalign = Align1D::Max; yalign = Align1D::Mid; },
- AlignMode::XmaxYmax => { xalign = Align1D::Max; yalign = Align1D::Max; }
+ AlignMode::XminYmin => {
+ xalign = Align1D::Min;
+ yalign = Align1D::Min;
+ }
+ AlignMode::XminYmid => {
+ xalign = Align1D::Min;
+ yalign = Align1D::Mid;
+ }
+ AlignMode::XminYmax => {
+ xalign = Align1D::Min;
+ yalign = Align1D::Max;
+ }
+ AlignMode::XmidYmin => {
+ xalign = Align1D::Mid;
+ yalign = Align1D::Min;
+ }
+ AlignMode::XmidYmid => {
+ xalign = Align1D::Mid;
+ yalign = Align1D::Mid;
+ }
+ AlignMode::XmidYmax => {
+ xalign = Align1D::Mid;
+ yalign = Align1D::Max;
+ }
+ AlignMode::XmaxYmin => {
+ xalign = Align1D::Max;
+ yalign = Align1D::Min;
+ }
+ AlignMode::XmaxYmid => {
+ xalign = Align1D::Max;
+ yalign = Align1D::Mid;
+ }
+ AlignMode::XmaxYmax => {
+ xalign = Align1D::Max;
+ yalign = Align1D::Max;
+ }
}
- let xpos = align_1d (xalign, dest_x, dest_width, w);
- let ypos = align_1d (yalign, dest_y, dest_height, h);
+ let xpos = align_1d(xalign, dest_x, dest_width, w);
+ let ypos = align_1d(yalign, dest_y, dest_height, h);
(xpos, ypos, w, h)
}
@@ -115,44 +144,67 @@ impl AspectRatio {
}
impl Default for Align {
- fn default () -> Align {
- Align::Aligned {
- align: AlignMode::XmidYmid,
- fit: FitMode::Meet
- }
+ fn default() -> Align {
+ Align::Aligned { align: AlignMode::XmidYmid,
+ fit: FitMode::Meet, }
}
}
impl Default for AspectRatio {
- fn default () -> AspectRatio {
- AspectRatio {
- defer: false,
- align: Default::default ()
- }
+ fn default() -> AspectRatio {
+ AspectRatio { defer: false,
+ align: Default::default(), }
}
}
-fn parse_align_mode (s: &str) -> Option<Align> {
+fn parse_align_mode(s: &str) -> Option<Align> {
match s {
- "none" => { Some (Align::None) },
- "xMinYMin" => { Some (Align::Aligned { align: AlignMode::XminYmin, fit: FitMode::Meet } ) },
- "xMidYMin" => { Some (Align::Aligned { align: AlignMode::XmidYmin, fit: FitMode::Meet } ) },
- "xMaxYMin" => { Some (Align::Aligned { align: AlignMode::XmaxYmin, fit: FitMode::Meet } ) },
- "xMinYMid" => { Some (Align::Aligned { align: AlignMode::XminYmid, fit: FitMode::Meet } ) },
- "xMidYMid" => { Some (Align::Aligned { align: AlignMode::XmidYmid, fit: FitMode::Meet } ) },
- "xMaxYMid" => { Some (Align::Aligned { align: AlignMode::XmaxYmid, fit: FitMode::Meet } ) },
- "xMinYMax" => { Some (Align::Aligned { align: AlignMode::XminYmax, fit: FitMode::Meet } ) },
- "xMidYMax" => { Some (Align::Aligned { align: AlignMode::XmidYmax, fit: FitMode::Meet } ) },
- "xMaxYMax" => { Some (Align::Aligned { align: AlignMode::XmaxYmax, fit: FitMode::Meet } ) },
- _ => { None }
+ "none" => Some(Align::None),
+ "xMinYMin" => {
+ Some(Align::Aligned { align: AlignMode::XminYmin,
+ fit: FitMode::Meet, })
+ }
+ "xMidYMin" => {
+ Some(Align::Aligned { align: AlignMode::XmidYmin,
+ fit: FitMode::Meet, })
+ }
+ "xMaxYMin" => {
+ Some(Align::Aligned { align: AlignMode::XmaxYmin,
+ fit: FitMode::Meet, })
+ }
+ "xMinYMid" => {
+ Some(Align::Aligned { align: AlignMode::XminYmid,
+ fit: FitMode::Meet, })
+ }
+ "xMidYMid" => {
+ Some(Align::Aligned { align: AlignMode::XmidYmid,
+ fit: FitMode::Meet, })
+ }
+ "xMaxYMid" => {
+ Some(Align::Aligned { align: AlignMode::XmaxYmid,
+ fit: FitMode::Meet, })
+ }
+ "xMinYMax" => {
+ Some(Align::Aligned { align: AlignMode::XminYmax,
+ fit: FitMode::Meet, })
+ }
+ "xMidYMax" => {
+ Some(Align::Aligned { align: AlignMode::XmidYmax,
+ fit: FitMode::Meet, })
+ }
+ "xMaxYMax" => {
+ Some(Align::Aligned { align: AlignMode::XmaxYmax,
+ fit: FitMode::Meet, })
+ }
+ _ => None,
}
}
-fn parse_fit_mode (s: &str) -> Option<FitMode> {
+fn parse_fit_mode(s: &str) -> Option<FitMode> {
match s {
- "meet" => { Some (FitMode::Meet) },
- "slice" => { Some (FitMode::Slice) },
- _ => { None }
+ "meet" => Some(FitMode::Meet),
+ "slice" => Some(FitMode::Slice),
+ _ => None,
}
}
@@ -160,11 +212,11 @@ enum ParseState {
Defer,
Align,
Fit,
- Finished
+ Finished,
}
-fn make_err () -> AttributeError {
- AttributeError::Parse (ParseError::new ("expected \"[defer] <align> [meet | slice]\""))
+fn make_err() -> AttributeError {
+ AttributeError::Parse(ParseError::new("expected \"[defer] <align> [meet | slice]\""))
}
impl Parse for AspectRatio {
@@ -173,46 +225,45 @@ impl Parse for AspectRatio {
fn parse(s: &str, _: ()) -> Result<AspectRatio, AttributeError> {
let mut defer = false;
- let mut align: Align = Default::default ();
+ let mut align: Align = Default::default();
let mut fit_mode = FitMode::Meet;
let mut state = ParseState::Defer;
- for v in s.split_whitespace () {
-
+ for v in s.split_whitespace() {
match state {
ParseState::Defer => {
if v == "defer" {
defer = true;
state = ParseState::Align;
- } else if let Some (parsed_align) = parse_align_mode (v) {
+ } else if let Some(parsed_align) = parse_align_mode(v) {
align = parsed_align;
state = ParseState::Fit;
} else {
- return Err(make_err ());
+ return Err(make_err());
}
- },
+ }
ParseState::Align => {
- if let Some (parsed_align) = parse_align_mode (v) {
+ if let Some(parsed_align) = parse_align_mode(v) {
align = parsed_align;
state = ParseState::Fit;
} else {
- return Err(make_err ());
+ return Err(make_err());
}
- },
+ }
ParseState::Fit => {
- if let Some (parsed_fit) = parse_fit_mode (v) {
+ if let Some(parsed_fit) = parse_fit_mode(v) {
fit_mode = parsed_fit;
state = ParseState::Finished;
} else {
- return Err(make_err ());
+ return Err(make_err());
}
- },
+ }
_ => {
- return Err(make_err ());
+ return Err(make_err());
}
}
}
@@ -221,22 +272,20 @@ impl Parse for AspectRatio {
// Since the meet|slice is optional, we can end up in either
// of the following states:
match state {
- ParseState::Fit | ParseState::Finished => {},
- _ => { return Err(make_err ()); }
+ ParseState::Fit | ParseState::Finished => {}
+ _ => {
+ return Err(make_err());
+ }
}
- Ok (AspectRatio {
- defer: defer,
- align: match align {
- Align::None => { Align::None },
- Align::Aligned { align, .. } => {
- Align::Aligned {
- align: align,
- fit: fit_mode
- }
- }
- }
- })
+ Ok(AspectRatio { defer,
+ align: match align {
+ Align::None => Align::None,
+ Align::Aligned { align, .. } => {
+ Align::Aligned { align,
+ fit: fit_mode, }
+ }
+ }, })
}
}
@@ -245,83 +294,164 @@ mod tests {
use super::*;
#[test]
- fn parsing_invalid_strings_yields_error () {
- assert! (AspectRatio::parse ("", ()).is_err ());
+ fn parsing_invalid_strings_yields_error() {
+ assert!(AspectRatio::parse("", ()).is_err());
- assert! (AspectRatio::parse ("defer", ()).is_err ());
+ assert!(AspectRatio::parse("defer", ()).is_err());
- assert! (AspectRatio::parse ("defer foo", ()).is_err ());
+ assert!(AspectRatio::parse("defer foo", ()).is_err());
- assert! (AspectRatio::parse ("defer xmidymid", ()).is_err ());
+ assert!(AspectRatio::parse("defer xmidymid", ()).is_err());
- assert! (AspectRatio::parse ("defer xMidYMid foo", ()).is_err ());
+ assert!(AspectRatio::parse("defer xMidYMid foo", ()).is_err());
- assert! (AspectRatio::parse ("xmidymid", ()).is_err ());
+ assert!(AspectRatio::parse("xmidymid", ()).is_err());
- assert! (AspectRatio::parse ("xMidYMid foo", ()).is_err ());
+ assert!(AspectRatio::parse("xMidYMid foo", ()).is_err());
- assert! (AspectRatio::parse ("defer xMidYMid meet foo", ()).is_err ());
+ assert!(AspectRatio::parse("defer xMidYMid meet foo", ()).is_err());
}
#[test]
- fn parses_valid_strings () {
- assert_eq! (AspectRatio::parse ("defer none", ()),
- Ok (AspectRatio { defer: true,
- align: Align::None }));
-
- assert_eq! (AspectRatio::parse ("xMidYMid", ()),
- Ok (AspectRatio { defer: false,
- align: Align::Aligned { align: AlignMode::XmidYmid,
- fit: FitMode::Meet } }));
-
- assert_eq! (AspectRatio::parse ("defer xMidYMid", ()),
- Ok (AspectRatio { defer: true,
- align: Align::Aligned { align: AlignMode::XmidYmid,
- fit: FitMode::Meet } }));
-
- assert_eq! (AspectRatio::parse ("defer xMinYMax", ()),
- Ok (AspectRatio { defer: true,
- align: Align::Aligned { align: AlignMode::XminYmax,
- fit: FitMode::Meet } }));
-
- assert_eq! (AspectRatio::parse ("defer xMaxYMid meet", ()),
- Ok (AspectRatio { defer: true,
- align: Align::Aligned { align: AlignMode::XmaxYmid,
- fit: FitMode::Meet } }));
-
- assert_eq! (AspectRatio::parse ("defer xMinYMax slice", ()),
- Ok (AspectRatio { defer: true,
- align: Align::Aligned { align: AlignMode::XminYmax,
- fit: FitMode::Slice } }));
+ fn parses_valid_strings() {
+ assert_eq!(AspectRatio::parse("defer none", ()),
+ Ok(AspectRatio { defer: true,
+ align: Align::None, }));
+
+ assert_eq!(AspectRatio::parse("xMidYMid", ()),
+ Ok(AspectRatio { defer: false,
+ align: Align::Aligned { align: AlignMode::XmidYmid,
+ fit: FitMode::Meet, }, }));
+
+ assert_eq!(AspectRatio::parse("defer xMidYMid", ()),
+ Ok(AspectRatio { defer: true,
+ align: Align::Aligned { align: AlignMode::XmidYmid,
+ fit: FitMode::Meet, }, }));
+
+ assert_eq!(AspectRatio::parse("defer xMinYMax", ()),
+ Ok(AspectRatio { defer: true,
+ align: Align::Aligned { align: AlignMode::XminYmax,
+ fit: FitMode::Meet, }, }));
+
+ assert_eq!(AspectRatio::parse("defer xMaxYMid meet", ()),
+ Ok(AspectRatio { defer: true,
+ align: Align::Aligned { align: AlignMode::XmaxYmid,
+ fit: FitMode::Meet, }, }));
+
+ assert_eq!(AspectRatio::parse("defer xMinYMax slice", ()),
+ Ok(AspectRatio { defer: true,
+ align: Align::Aligned { align: AlignMode::XminYmax,
+ fit: FitMode::Slice, }, }));
}
#[test]
- fn aligns () {
- assert_eq! (AspectRatio::parse ("xMinYMin meet", ()).unwrap().compute (1.0, 10.0, 0.0, 0.0, 10.0,
1.0), (0.0, 0.0, 0.1, 1.0));
- assert_eq! (AspectRatio::parse ("xMinYMin slice", ()).unwrap().compute (1.0, 10.0, 0.0, 0.0, 10.0,
1.0), (0.0, 0.0, 10.0, 100.0));
-
- assert_eq! (AspectRatio::parse ("xMinYMid meet", ()).unwrap().compute (1.0, 10.0, 0.0, 0.0, 10.0,
1.0), (0.0, 0.0, 0.1, 1.0));
- assert_eq! (AspectRatio::parse ("xMinYMid slice", ()).unwrap().compute (1.0, 10.0, 0.0, 0.0, 10.0,
1.0), (0.0, -49.5, 10.0, 100.0));
-
- assert_eq! (AspectRatio::parse ("xMinYMax meet", ()).unwrap().compute (1.0, 10.0, 0.0, 0.0, 10.0,
1.0), (0.0, 0.0, 0.1, 1.0));
- assert_eq! (AspectRatio::parse ("xMinYMax slice", ()).unwrap().compute (1.0, 10.0, 0.0, 0.0, 10.0,
1.0), (0.0, -99.0, 10.0, 100.0));
-
- assert_eq! (AspectRatio::parse ("xMidYMin meet", ()).unwrap().compute (1.0, 10.0, 0.0, 0.0, 10.0,
1.0), (4.95, 0.0, 0.1, 1.0));
- assert_eq! (AspectRatio::parse ("xMidYMin slice", ()).unwrap().compute (1.0, 10.0, 0.0, 0.0, 10.0,
1.0), (0.0, 0.0, 10.0, 100.0));
-
- assert_eq! (AspectRatio::parse ("xMidYMid meet", ()).unwrap().compute (1.0, 10.0, 0.0, 0.0, 10.0,
1.0), (4.95, 0.0, 0.1, 1.0));
- assert_eq! (AspectRatio::parse ("xMidYMid slice", ()).unwrap().compute (1.0, 10.0, 0.0, 0.0, 10.0,
1.0), (0.0, -49.5, 10.0, 100.0));
-
- assert_eq! (AspectRatio::parse ("xMidYMax meet", ()).unwrap().compute (1.0, 10.0, 0.0, 0.0, 10.0,
1.0), (4.95, 0.0, 0.1, 1.0));
- assert_eq! (AspectRatio::parse ("xMidYMax slice", ()).unwrap().compute (1.0, 10.0, 0.0, 0.0, 10.0,
1.0), (0.0, -99.0, 10.0, 100.0));
-
- assert_eq! (AspectRatio::parse ("xMaxYMin meet", ()).unwrap().compute (1.0, 10.0, 0.0, 0.0, 10.0,
1.0), (9.9, 0.0, 0.1, 1.0));
- assert_eq! (AspectRatio::parse ("xMaxYMin slice", ()).unwrap().compute (1.0, 10.0, 0.0, 0.0, 10.0,
1.0), (0.0, 0.0, 10.0, 100.0));
-
- assert_eq! (AspectRatio::parse ("xMaxYMid meet", ()).unwrap().compute (1.0, 10.0, 0.0, 0.0, 10.0,
1.0), (9.9, 0.0, 0.1, 1.0));
- assert_eq! (AspectRatio::parse ("xMaxYMid slice", ()).unwrap().compute (1.0, 10.0, 0.0, 0.0, 10.0,
1.0), (0.0, -49.5, 10.0, 100.0));
-
- assert_eq! (AspectRatio::parse ("xMaxYMax meet", ()).unwrap().compute (1.0, 10.0, 0.0, 0.0, 10.0,
1.0), (9.9, 0.0, 0.1, 1.0));
- assert_eq! (AspectRatio::parse ("xMaxYMax slice", ()).unwrap().compute (1.0, 10.0, 0.0, 0.0, 10.0,
1.0), (0.0, -99.0, 10.0, 100.0));
+ fn aligns() {
+ assert_eq!(AspectRatio::parse("xMinYMin meet", ()).unwrap()
+ .compute(1.0, 10.0, 0.0, 0.0, 10.0, 1.0),
+ (0.0, 0.0, 0.1, 1.0));
+ assert_eq!(AspectRatio::parse("xMinYMin slice", ()).unwrap()
+ .compute(1.0,
+ 10.0,
+ 0.0,
+ 0.0,
+ 10.0,
+ 1.0),
+ (0.0, 0.0, 10.0, 100.0));
+
+ assert_eq!(AspectRatio::parse("xMinYMid meet", ()).unwrap()
+ .compute(1.0, 10.0, 0.0, 0.0, 10.0, 1.0),
+ (0.0, 0.0, 0.1, 1.0));
+ assert_eq!(AspectRatio::parse("xMinYMid slice", ()).unwrap()
+ .compute(1.0,
+ 10.0,
+ 0.0,
+ 0.0,
+ 10.0,
+ 1.0),
+ (0.0, -49.5, 10.0, 100.0));
+
+ assert_eq!(AspectRatio::parse("xMinYMax meet", ()).unwrap()
+ .compute(1.0, 10.0, 0.0, 0.0, 10.0, 1.0),
+ (0.0, 0.0, 0.1, 1.0));
+ assert_eq!(AspectRatio::parse("xMinYMax slice", ()).unwrap()
+ .compute(1.0,
+ 10.0,
+ 0.0,
+ 0.0,
+ 10.0,
+ 1.0),
+ (0.0, -99.0, 10.0, 100.0));
+
+ assert_eq!(AspectRatio::parse("xMidYMin meet", ()).unwrap()
+ .compute(1.0, 10.0, 0.0, 0.0, 10.0, 1.0),
+ (4.95, 0.0, 0.1, 1.0));
+ assert_eq!(AspectRatio::parse("xMidYMin slice", ()).unwrap()
+ .compute(1.0,
+ 10.0,
+ 0.0,
+ 0.0,
+ 10.0,
+ 1.0),
+ (0.0, 0.0, 10.0, 100.0));
+
+ assert_eq!(AspectRatio::parse("xMidYMid meet", ()).unwrap()
+ .compute(1.0, 10.0, 0.0, 0.0, 10.0, 1.0),
+ (4.95, 0.0, 0.1, 1.0));
+ assert_eq!(AspectRatio::parse("xMidYMid slice", ()).unwrap()
+ .compute(1.0,
+ 10.0,
+ 0.0,
+ 0.0,
+ 10.0,
+ 1.0),
+ (0.0, -49.5, 10.0, 100.0));
+
+ assert_eq!(AspectRatio::parse("xMidYMax meet", ()).unwrap()
+ .compute(1.0, 10.0, 0.0, 0.0, 10.0, 1.0),
+ (4.95, 0.0, 0.1, 1.0));
+ assert_eq!(AspectRatio::parse("xMidYMax slice", ()).unwrap()
+ .compute(1.0,
+ 10.0,
+ 0.0,
+ 0.0,
+ 10.0,
+ 1.0),
+ (0.0, -99.0, 10.0, 100.0));
+
+ assert_eq!(AspectRatio::parse("xMaxYMin meet", ()).unwrap()
+ .compute(1.0, 10.0, 0.0, 0.0, 10.0, 1.0),
+ (9.9, 0.0, 0.1, 1.0));
+ assert_eq!(AspectRatio::parse("xMaxYMin slice", ()).unwrap()
+ .compute(1.0,
+ 10.0,
+ 0.0,
+ 0.0,
+ 10.0,
+ 1.0),
+ (0.0, 0.0, 10.0, 100.0));
+
+ assert_eq!(AspectRatio::parse("xMaxYMid meet", ()).unwrap()
+ .compute(1.0, 10.0, 0.0, 0.0, 10.0, 1.0),
+ (9.9, 0.0, 0.1, 1.0));
+ assert_eq!(AspectRatio::parse("xMaxYMid slice", ()).unwrap()
+ .compute(1.0,
+ 10.0,
+ 0.0,
+ 0.0,
+ 10.0,
+ 1.0),
+ (0.0, -49.5, 10.0, 100.0));
+
+ assert_eq!(AspectRatio::parse("xMaxYMax meet", ()).unwrap()
+ .compute(1.0, 10.0, 0.0, 0.0, 10.0, 1.0),
+ (9.9, 0.0, 0.1, 1.0));
+ assert_eq!(AspectRatio::parse("xMaxYMax slice", ()).unwrap()
+ .compute(1.0,
+ 10.0,
+ 0.0,
+ 0.0,
+ 10.0,
+ 1.0),
+ (0.0, -99.0, 10.0, 100.0));
}
}
diff --git a/rsvg_internals/src/attributes.rs b/rsvg_internals/src/attributes.rs
index 02630a8a..65a55d4f 100644
--- a/rsvg_internals/src/attributes.rs
+++ b/rsvg_internals/src/attributes.rs
@@ -1,7 +1,7 @@
extern crate phf;
-use glib_sys;
use glib::translate::*;
+use glib_sys;
use libc;
use std::str::FromStr;
@@ -18,26 +18,27 @@ impl FromStr for Attribute {
}
#[no_mangle]
-pub extern fn rsvg_attribute_from_name(raw_name: *const libc::c_char,
- out_attr: *mut Attribute) -> glib_sys::gboolean {
+pub extern "C" fn rsvg_attribute_from_name(raw_name: *const libc::c_char,
+ out_attr: *mut Attribute)
+ -> glib_sys::gboolean {
let name = unsafe { utf8_cstr(raw_name) };
match Attribute::from_str(name) {
Ok(a) => {
- unsafe { *out_attr = a; }
+ unsafe {
+ *out_attr = a;
+ }
true.to_glib()
- },
-
- Err(_) => {
- false.to_glib()
}
+
+ Err(_) => false.to_glib(),
}
}
#[cfg(test)]
mod tests {
- use std::mem;
use super::*;
+ use std::mem;
#[test]
fn parses_attributes() {
@@ -52,8 +53,8 @@ mod tests {
#[test]
fn c_attribute_from_name() {
let mut a: Attribute = unsafe { mem::uninitialized() };
- let res: bool = from_glib(rsvg_attribute_from_name("width".to_glib_none().0,
- &mut a as *mut Attribute));
+ let res: bool =
+ from_glib(rsvg_attribute_from_name("width".to_glib_none().0, &mut a as *mut Attribute));
assert!(res);
assert_eq!(a, Attribute::Width);
}
diff --git a/rsvg_internals/src/bbox.rs b/rsvg_internals/src/bbox.rs
index 6fa5d4e9..ada8b041 100644
--- a/rsvg_internals/src/bbox.rs
+++ b/rsvg_internals/src/bbox.rs
@@ -1,65 +1,63 @@
use cairo;
use glib_sys;
-use glib::translate::*;
use cairo::MatrixTrait;
+use glib::translate::*;
use util::*;
/* Keep this in sync with ../../rsvg-private.h:RsvgBbox */
#[repr(C)]
#[derive(Copy, Clone)]
pub struct RsvgBbox {
- pub rect: cairo::Rectangle,
+ pub rect: cairo::Rectangle,
pub affine: cairo::Matrix,
- virgin: glib_sys::gboolean
+ virgin: glib_sys::gboolean,
}
impl RsvgBbox {
- pub fn is_virgin (&self) -> bool {
- from_glib (self.virgin)
+ pub fn is_virgin(&self) -> bool {
+ from_glib(self.virgin)
}
pub fn is_empty(&self) -> bool {
- from_glib(self.virgin) || double_equals(self.rect.width, 0.0) || double_equals(self.rect.height, 0.0)
+ from_glib(self.virgin) || double_equals(self.rect.width, 0.0)
+ || double_equals(self.rect.height, 0.0)
}
}
#[no_mangle]
-pub extern fn rsvg_bbox_init (raw_bbox: *mut RsvgBbox, raw_matrix: *const cairo::Matrix) {
- assert! (!raw_bbox.is_null ());
- assert! (!raw_matrix.is_null ());
+pub extern "C" fn rsvg_bbox_init(raw_bbox: *mut RsvgBbox, raw_matrix: *const cairo::Matrix) {
+ assert!(!raw_bbox.is_null());
+ assert!(!raw_matrix.is_null());
let bbox: &mut RsvgBbox = unsafe { &mut (*raw_bbox) };
- bbox.virgin = true.to_glib ();
+ bbox.virgin = true.to_glib();
bbox.affine = unsafe { *raw_matrix };
}
#[no_mangle]
-pub extern fn rsvg_bbox_insert (raw_dst: *mut RsvgBbox, raw_src: *const RsvgBbox) {
- assert! (!raw_dst.is_null ());
- assert! (!raw_src.is_null ());
+pub extern "C" fn rsvg_bbox_insert(raw_dst: *mut RsvgBbox, raw_src: *const RsvgBbox) {
+ assert!(!raw_dst.is_null());
+ assert!(!raw_src.is_null());
let dst: &mut RsvgBbox = unsafe { &mut (*raw_dst) };
let src: &RsvgBbox = unsafe { &*raw_src };
- if src.is_virgin () {
+ if src.is_virgin() {
return;
}
- let (mut xmin, mut ymin, mut xmax, mut ymax) = if !dst.is_virgin () {
- (dst.rect.x,
- dst.rect.y,
- (dst.rect.x + dst.rect.width),
- (dst.rect.y + dst.rect.height))
+ let (mut xmin, mut ymin, mut xmax, mut ymax) = if !dst.is_virgin() {
+ (dst.rect.x, dst.rect.y, (dst.rect.x + dst.rect.width), (dst.rect.y + dst.rect.height))
} else {
(0.0, 0.0, 0.0, 0.0)
};
let mut affine = dst.affine;
- affine.invert (); // this will panic!() if it's not invertible... should we check on our own?
- affine = cairo::Matrix::multiply (&src.affine, &affine);
+ affine.invert(); // this will panic!() if it's not invertible... should we check on our own?
+ affine = cairo::Matrix::multiply(&src.affine, &affine);
/* This is a trick. We want to transform each of the corners of
* the rectangle defined by src.rect with the affine
@@ -71,20 +69,28 @@ pub extern fn rsvg_bbox_insert (raw_dst: *mut RsvgBbox, raw_src: *const RsvgBbox
for i in 0..4 {
let rx: f64 = src.rect.x + src.rect.width * f64::from(i % 2);
let ry: f64 = src.rect.y + src.rect.height * f64::from(i / 2);
- let x: f64 = affine.xx * rx + affine.xy * ry + affine.x0;
- let y: f64 = affine.yx * rx + affine.yy * ry + affine.y0;
+ let x: f64 = affine.xx * rx + affine.xy * ry + affine.x0;
+ let y: f64 = affine.yx * rx + affine.yy * ry + affine.y0;
- if dst.is_virgin () {
+ if dst.is_virgin() {
xmin = x;
xmax = x;
ymin = y;
ymax = y;
- dst.virgin = false.to_glib ();
+ dst.virgin = false.to_glib();
} else {
- if x < xmin { xmin = x; }
- if x > xmax { xmax = x; }
- if y < ymin { ymin = y; }
- if y > ymax { ymax = y; }
+ if x < xmin {
+ xmin = x;
+ }
+ if x > xmax {
+ xmax = x;
+ }
+ if y < ymin {
+ ymin = y;
+ }
+ if y > ymax {
+ ymax = y;
+ }
}
}
@@ -95,30 +101,27 @@ pub extern fn rsvg_bbox_insert (raw_dst: *mut RsvgBbox, raw_src: *const RsvgBbox
}
#[no_mangle]
-pub extern fn rsvg_bbox_clip (raw_dst: *mut RsvgBbox, raw_src: *const RsvgBbox) {
- assert! (!raw_dst.is_null ());
- assert! (!raw_src.is_null ());
+pub extern "C" fn rsvg_bbox_clip(raw_dst: *mut RsvgBbox, raw_src: *const RsvgBbox) {
+ assert!(!raw_dst.is_null());
+ assert!(!raw_src.is_null());
let dst: &mut RsvgBbox = unsafe { &mut (*raw_dst) };
let src: &RsvgBbox = unsafe { &*raw_src };
- if src.is_virgin () {
+ if src.is_virgin() {
return;
}
- let (mut xmin, mut ymin, mut xmax, mut ymax) = if !dst.is_virgin () {
- ((dst.rect.x + dst.rect.width),
- (dst.rect.y + dst.rect.height),
- dst.rect.x,
- dst.rect.y)
+ let (mut xmin, mut ymin, mut xmax, mut ymax) = if !dst.is_virgin() {
+ ((dst.rect.x + dst.rect.width), (dst.rect.y + dst.rect.height), dst.rect.x, dst.rect.y)
} else {
(0.0, 0.0, 0.0, 0.0)
};
let mut affine = dst.affine;
- affine.invert ();
- affine = cairo::Matrix::multiply (&src.affine, &affine);
+ affine.invert();
+ affine = cairo::Matrix::multiply(&src.affine, &affine);
/* This is a trick. See rsvg_bbox_insert() for a description of how it works. */
for i in 0..4 {
@@ -127,25 +130,41 @@ pub extern fn rsvg_bbox_clip (raw_dst: *mut RsvgBbox, raw_src: *const RsvgBbox)
let x = affine.xx * rx + affine.xy * ry + affine.x0;
let y = affine.yx * rx + affine.yy * ry + affine.y0;
- if dst.is_virgin () {
+ if dst.is_virgin() {
xmin = x;
xmax = x;
ymin = y;
ymax = y;
- dst.virgin = false.to_glib ();
+ dst.virgin = false.to_glib();
} else {
- if x < xmin { xmin = x; }
- if x > xmax { xmax = x; }
- if y < ymin { ymin = y; }
- if y > ymax { ymax = y; }
+ if x < xmin {
+ xmin = x;
+ }
+ if x > xmax {
+ xmax = x;
+ }
+ if y < ymin {
+ ymin = y;
+ }
+ if y > ymax {
+ ymax = y;
+ }
}
}
- if xmin < dst.rect.x { xmin = dst.rect.x; }
- if ymin < dst.rect.y { ymin = dst.rect.y; }
+ if xmin < dst.rect.x {
+ xmin = dst.rect.x;
+ }
+ if ymin < dst.rect.y {
+ ymin = dst.rect.y;
+ }
- if xmax > dst.rect.x + dst.rect.width { xmax = dst.rect.x + dst.rect.width; }
- if ymax > dst.rect.y + dst.rect.height { ymax = dst.rect.y + dst.rect.height; }
+ if xmax > dst.rect.x + dst.rect.width {
+ xmax = dst.rect.x + dst.rect.width;
+ }
+ if ymax > dst.rect.y + dst.rect.height {
+ ymax = dst.rect.y + dst.rect.height;
+ }
dst.rect.x = xmin;
dst.rect.width = xmax - xmin;
diff --git a/rsvg_internals/src/clip_path.rs b/rsvg_internals/src/clip_path.rs
index 27b58327..fbb03fb9 100644
--- a/rsvg_internals/src/clip_path.rs
+++ b/rsvg_internals/src/clip_path.rs
@@ -2,24 +2,22 @@ use libc;
use std::cell::Cell;
use attributes::Attribute;
+use coord_units::CoordUnits;
use drawing_ctx::RsvgDrawingCtx;
use handle::RsvgHandle;
-use node::{NodeResult, NodeTrait, NodeType, RsvgCNodeImpl, RsvgNode, boxed_node_new};
-use coord_units::CoordUnits;
+use node::{boxed_node_new, NodeResult, NodeTrait, NodeType, RsvgCNodeImpl, RsvgNode};
use parsers::parse;
use property_bag::PropertyBag;
coord_units!(ClipPathUnits, CoordUnits::UserSpaceOnUse);
struct NodeClipPath {
- units: Cell<ClipPathUnits>
+ units: Cell<ClipPathUnits>,
}
impl NodeClipPath {
fn new() -> NodeClipPath {
- NodeClipPath {
- units: Cell::new(ClipPathUnits::default())
- }
+ NodeClipPath { units: Cell::new(ClipPathUnits::default()), }
}
}
@@ -27,8 +25,9 @@ impl NodeTrait for NodeClipPath {
fn set_atts(&self, _: &RsvgNode, _: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
for (_key, attr, value) in pbag.iter() {
match attr {
- Attribute::ClipPathUnits =>
- self.units.set(parse("clipPathUnits", value, (), None)?),
+ Attribute::ClipPathUnits => {
+ self.units.set(parse("clipPathUnits", value, (), None)?)
+ }
_ => (),
}
@@ -47,22 +46,24 @@ impl NodeTrait for NodeClipPath {
}
#[no_mangle]
-pub extern fn rsvg_node_clip_path_new(_: *const libc::c_char, raw_parent: *const RsvgNode) -> *const
RsvgNode {
+pub extern "C" fn rsvg_node_clip_path_new(_: *const libc::c_char,
+ raw_parent: *const RsvgNode)
+ -> *const RsvgNode {
boxed_node_new(NodeType::ClipPath,
raw_parent,
Box::new(NodeClipPath::new()))
}
#[no_mangle]
-pub extern fn rsvg_node_clip_path_get_units(raw_node: *const RsvgNode) -> CoordUnits {
- assert! (!raw_node.is_null ());
- let node: &RsvgNode = unsafe { & *raw_node };
+pub extern "C" fn rsvg_node_clip_path_get_units(raw_node: *const RsvgNode) -> CoordUnits {
+ assert!(!raw_node.is_null());
+ let node: &RsvgNode = unsafe { &*raw_node };
let mut units = ClipPathUnits::default();
node.with_impl(|clip_path: &NodeClipPath| {
- units = clip_path.units.get();
- });
+ units = clip_path.units.get();
+ });
CoordUnits::from(units)
}
diff --git a/rsvg_internals/src/cnode.rs b/rsvg_internals/src/cnode.rs
index 3b6be21a..728349a9 100644
--- a/rsvg_internals/src/cnode.rs
+++ b/rsvg_internals/src/cnode.rs
@@ -6,68 +6,89 @@ use state::RsvgState;
use std::rc::*;
-type CNodeSetAtts = unsafe extern "C" fn (node: *const RsvgNode, node_impl: *const RsvgCNodeImpl, handle:
*const RsvgHandle, pbag: *const PropertyBag);
-type CNodeDraw = unsafe extern "C" fn (node: *const RsvgNode, node_impl: *const RsvgCNodeImpl, draw_ctx:
*const RsvgDrawingCtx, dominate: i32);
-type CNodeFree = unsafe extern "C" fn (node_impl: *const RsvgCNodeImpl);
+type CNodeSetAtts = unsafe extern "C" fn(node: *const RsvgNode,
+ node_impl: *const RsvgCNodeImpl,
+ handle: *const RsvgHandle,
+ pbag: *const PropertyBag);
+type CNodeDraw = unsafe extern "C" fn(node: *const RsvgNode,
+ node_impl: *const RsvgCNodeImpl,
+ draw_ctx: *const RsvgDrawingCtx,
+ dominate: i32);
+type CNodeFree = unsafe extern "C" fn(node_impl: *const RsvgCNodeImpl);
struct CNode {
c_node_impl: *const RsvgCNodeImpl,
set_atts_fn: CNodeSetAtts,
- draw_fn: CNodeDraw,
- free_fn: CNodeFree,
+ draw_fn: CNodeDraw,
+ free_fn: CNodeFree,
}
impl NodeTrait for CNode {
- fn set_atts (&self, node: &RsvgNode, handle: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
- unsafe { (self.set_atts_fn) (node as *const RsvgNode, self.c_node_impl, handle, pbag.ffi()); }
+ fn set_atts(&self,
+ node: &RsvgNode,
+ handle: *const RsvgHandle,
+ pbag: &PropertyBag)
+ -> NodeResult {
+ unsafe {
+ (self.set_atts_fn)(node as *const RsvgNode,
+ self.c_node_impl,
+ handle,
+ pbag.ffi());
+ }
- Ok (())
+ Ok(())
}
- fn draw (&self, node: &RsvgNode, draw_ctx: *const RsvgDrawingCtx, dominate: i32) {
- unsafe { (self.draw_fn) (node as *const RsvgNode, self.c_node_impl, draw_ctx, dominate); }
+ fn draw(&self, node: &RsvgNode, draw_ctx: *const RsvgDrawingCtx, dominate: i32) {
+ unsafe {
+ (self.draw_fn)(node as *const RsvgNode,
+ self.c_node_impl,
+ draw_ctx,
+ dominate);
+ }
}
- fn get_c_impl (&self) -> *const RsvgCNodeImpl {
+ fn get_c_impl(&self) -> *const RsvgCNodeImpl {
self.c_node_impl
}
}
impl Drop for CNode {
- fn drop (&mut self) {
- unsafe { (self.free_fn) (self.c_node_impl); }
+ fn drop(&mut self) {
+ unsafe {
+ (self.free_fn)(self.c_node_impl);
+ }
}
}
#[no_mangle]
-pub extern fn rsvg_rust_cnode_new (node_type: NodeType,
- raw_parent: *const RsvgNode,
- state: *mut RsvgState,
- c_node_impl: *const RsvgCNodeImpl,
- set_atts_fn: CNodeSetAtts,
- draw_fn: CNodeDraw,
- free_fn: CNodeFree) -> *const RsvgNode {
- assert! (!state.is_null ());
- assert! (!c_node_impl.is_null ());
+pub extern "C" fn rsvg_rust_cnode_new(node_type: NodeType,
+ raw_parent: *const RsvgNode,
+ state: *mut RsvgState,
+ c_node_impl: *const RsvgCNodeImpl,
+ set_atts_fn: CNodeSetAtts,
+ draw_fn: CNodeDraw,
+ free_fn: CNodeFree)
+ -> *const RsvgNode {
+ assert!(!state.is_null());
+ assert!(!c_node_impl.is_null());
- let cnode = CNode {
- c_node_impl: c_node_impl,
- set_atts_fn: set_atts_fn,
- draw_fn: draw_fn,
- free_fn: free_fn
- };
+ let cnode = CNode { c_node_impl,
+ set_atts_fn,
+ draw_fn,
+ free_fn, };
- box_node (Rc::new (Node::new (node_type,
- node_ptr_to_weak (raw_parent),
- state,
- Box::new (cnode))))
+ box_node(Rc::new(Node::new(node_type,
+ node_ptr_to_weak(raw_parent),
+ state,
+ Box::new(cnode))))
}
#[no_mangle]
-pub extern fn rsvg_rust_cnode_get_impl (raw_node: *const RsvgNode) -> *const RsvgCNodeImpl {
- assert! (!raw_node.is_null ());
- let node: &RsvgNode = unsafe { & *raw_node };
+pub extern "C" fn rsvg_rust_cnode_get_impl(raw_node: *const RsvgNode) -> *const RsvgCNodeImpl {
+ assert!(!raw_node.is_null());
+ let node: &RsvgNode = unsafe { &*raw_node };
- node.get_c_impl ()
+ node.get_c_impl()
}
diff --git a/rsvg_internals/src/color.rs b/rsvg_internals/src/color.rs
index a1b9a007..50a69e31 100644
--- a/rsvg_internals/src/color.rs
+++ b/rsvg_internals/src/color.rs
@@ -1,9 +1,9 @@
use cssparser;
use libc;
+use error::*;
use parsers::Parse;
use parsers::ParseError;
-use error::*;
use util::utf8_cstr;
// There are two quirks here:
@@ -26,7 +26,7 @@ pub enum ColorKind {
Inherit,
CurrentColor,
ARGB,
- ParseError
+ ParseError,
}
// Keep this in sync with rsvg-css.h:RsvgCssColorSpec
@@ -34,7 +34,7 @@ pub enum ColorKind {
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct ColorSpec {
kind: ColorKind,
- argb: u32
+ argb: u32,
}
// Keep in sync with rsvg-css.h:AllowInherit
@@ -42,7 +42,7 @@ pub struct ColorSpec {
#[derive(PartialEq, Debug)]
pub enum AllowInherit {
No,
- Yes
+ Yes,
}
// Keep in sync with rsvg-css.h:AllowCurrentColor
@@ -50,7 +50,7 @@ pub enum AllowInherit {
#[derive(PartialEq, Debug)]
pub enum AllowCurrentColor {
No,
- Yes
+ Yes,
}
// This is the Rust version of the above
@@ -58,116 +58,117 @@ pub enum AllowCurrentColor {
pub enum Color {
Inherit,
CurrentColor,
- RGBA (cssparser::RGBA)
+ RGBA(cssparser::RGBA),
}
impl Parse for Color {
type Data = (AllowInherit, AllowCurrentColor);
type Err = AttributeError;
- fn parse (s: &str, (allow_inherit, allow_current_color): (AllowInherit, AllowCurrentColor)) ->
Result<Color, AttributeError> {
+ fn parse(s: &str,
+ (allow_inherit, allow_current_color): (AllowInherit, AllowCurrentColor))
+ -> Result<Color, AttributeError> {
if s == "inherit" {
if allow_inherit == AllowInherit::Yes {
- Ok (Color::Inherit)
+ Ok(Color::Inherit)
} else {
- Err (AttributeError::Value ("inherit is not allowed here".to_string ()))
+ Err(AttributeError::Value("inherit is not allowed here".to_string()))
}
} else {
- let mut input = cssparser::ParserInput::new (s);
- match cssparser::Color::parse (&mut cssparser::Parser::new (&mut input)) {
- Ok (cssparser::Color::CurrentColor) => {
+ let mut input = cssparser::ParserInput::new(s);
+ match cssparser::Color::parse(&mut cssparser::Parser::new(&mut input)) {
+ Ok(cssparser::Color::CurrentColor) => {
if allow_current_color == AllowCurrentColor::Yes {
- Ok (Color::CurrentColor)
+ Ok(Color::CurrentColor)
} else {
- Err (AttributeError::Value ("currentColor is not allowed here".to_string ()))
+ Err(AttributeError::Value("currentColor is not allowed here".to_string()))
}
- },
+ }
- Ok (csscolor) => Ok (Color::from (csscolor)),
+ Ok(csscolor) => Ok(Color::from(csscolor)),
- _ => Err (AttributeError::Parse (ParseError::new ("invalid syntax for color")))
+ _ => Err(AttributeError::Parse(ParseError::new("invalid syntax for color"))),
}
}
}
-
}
impl Color {
- pub fn from_color_spec (spec: &ColorSpec) -> Result <Color, AttributeError> {
+ pub fn from_color_spec(spec: &ColorSpec) -> Result<Color, AttributeError> {
match *spec {
- ColorSpec { kind: ColorKind::Inherit, .. } => Ok (Color::Inherit),
+ ColorSpec { kind: ColorKind::Inherit,
+ .. } => Ok(Color::Inherit),
- ColorSpec { kind: ColorKind::CurrentColor, .. } => Ok (Color::CurrentColor),
+ ColorSpec { kind: ColorKind::CurrentColor,
+ .. } => Ok(Color::CurrentColor),
- ColorSpec { kind: ColorKind::ARGB, argb } => Ok (Color::RGBA (rgba_from_argb (argb))),
+ ColorSpec { kind: ColorKind::ARGB,
+ argb, } => Ok(Color::RGBA(rgba_from_argb(argb))),
- ColorSpec { kind: ColorKind::ParseError, .. } => Err (AttributeError::Parse (ParseError::new
("parse error")))
+ ColorSpec { kind: ColorKind::ParseError,
+ .. } => Err(AttributeError::Parse(ParseError::new("parse error"))),
}
}
}
-fn rgba_from_argb (argb: u32) -> cssparser::RGBA {
- cssparser::RGBA::new (((argb & 0x00ff_0000) >> 16) as u8,
- ((argb & 0x0000_ff00) >> 8) as u8,
- (argb & 0x0000_00ff) as u8,
- ((argb & 0xff00_0000) >> 24) as u8)
+fn rgba_from_argb(argb: u32) -> cssparser::RGBA {
+ cssparser::RGBA::new(((argb & 0x00ff_0000) >> 16) as u8,
+ ((argb & 0x0000_ff00) >> 8) as u8,
+ (argb & 0x0000_00ff) as u8,
+ ((argb & 0xff00_0000) >> 24) as u8)
}
impl From<cssparser::Color> for Color {
- fn from (c: cssparser::Color) -> Color {
+ fn from(c: cssparser::Color) -> Color {
match c {
cssparser::Color::CurrentColor => Color::CurrentColor,
- cssparser::Color::RGBA (rgba) => Color::RGBA (rgba)
+ cssparser::Color::RGBA(rgba) => Color::RGBA(rgba),
}
}
}
impl From<u32> for Color {
- fn from (argb: u32) -> Color {
- Color::RGBA (rgba_from_argb (argb))
+ fn from(argb: u32) -> Color {
+ Color::RGBA(rgba_from_argb(argb))
}
}
impl From<Result<Color, AttributeError>> for ColorSpec {
- fn from (result: Result<Color, AttributeError>) -> ColorSpec {
+ fn from(result: Result<Color, AttributeError>) -> ColorSpec {
match result {
- Ok (Color::Inherit) =>
- ColorSpec {
- kind: ColorKind::Inherit,
- argb: 0
- },
-
- Ok (Color::CurrentColor) =>
- ColorSpec {
- kind: ColorKind::CurrentColor,
- argb: 0
- },
-
- Ok (Color::RGBA (rgba)) =>
- ColorSpec {
- kind: ColorKind::ARGB,
- argb: (u32::from(rgba.alpha) << 24 |
- u32::from(rgba.red) << 16 |
- u32::from(rgba.green) << 8 |
- u32::from(rgba.blue))
- },
-
- _ =>
- ColorSpec {
- kind: ColorKind::ParseError,
- argb: 0
- }
+ Ok(Color::Inherit) => {
+ ColorSpec { kind: ColorKind::Inherit,
+ argb: 0, }
+ }
+
+ Ok(Color::CurrentColor) => {
+ ColorSpec { kind: ColorKind::CurrentColor,
+ argb: 0, }
+ }
+
+ Ok(Color::RGBA(rgba)) => {
+ ColorSpec { kind: ColorKind::ARGB,
+ argb: (u32::from(rgba.alpha) << 24 | u32::from(rgba.red) << 16
+ | u32::from(rgba.green) << 8
+ | u32::from(rgba.blue)), }
+ }
+
+ _ => {
+ ColorSpec { kind: ColorKind::ParseError,
+ argb: 0, }
+ }
}
}
}
#[no_mangle]
-pub extern fn rsvg_css_parse_color (string: *const libc::c_char,
- allow_inherit: AllowInherit,
- allow_current_color: AllowCurrentColor) -> ColorSpec {
+pub extern "C" fn rsvg_css_parse_color(string: *const libc::c_char,
+ allow_inherit: AllowInherit,
+ allow_current_color: AllowCurrentColor)
+ -> ColorSpec {
let s = unsafe { utf8_cstr(string) };
- ColorSpec::from (Color::parse (s, (allow_inherit, allow_current_color)))
+ ColorSpec::from(Color::parse(s, (allow_inherit, allow_current_color)))
}
#[cfg(test)]
@@ -175,95 +176,119 @@ mod tests {
use super::*;
use glib::translate::*;
- fn parse (s: &str) -> ColorSpec {
+ fn parse(s: &str) -> ColorSpec {
// ColorSpec::from (Color::parse (s, (AllowInherit::Yes, AllowCurrentColor::Yes)))
- rsvg_css_parse_color (s.to_glib_none ().0, AllowInherit::Yes, AllowCurrentColor::Yes)
+ rsvg_css_parse_color(s.to_glib_none().0,
+ AllowInherit::Yes,
+ AllowCurrentColor::Yes)
}
#[test]
- fn parses_hash_hex_colors () {
- assert_eq! (parse ("#AB10fa20"), ColorSpec { kind: ColorKind::ARGB, argb: 0x20ab10fa });
- assert_eq! (parse ("#10fa20"), ColorSpec { kind: ColorKind::ARGB, argb: 0xff10fa20 });
- assert_eq! (parse ("#abcd"), ColorSpec { kind: ColorKind::ARGB, argb: 0xddaabbcc });
- assert_eq! (parse ("#123"), ColorSpec { kind: ColorKind::ARGB, argb: 0xff112233 });
+ fn parses_hash_hex_colors() {
+ assert_eq!(parse("#AB10fa20"),
+ ColorSpec { kind: ColorKind::ARGB,
+ argb: 0x20ab10fa, });
+ assert_eq!(parse("#10fa20"),
+ ColorSpec { kind: ColorKind::ARGB,
+ argb: 0xff10fa20, });
+ assert_eq!(parse("#abcd"),
+ ColorSpec { kind: ColorKind::ARGB,
+ argb: 0xddaabbcc, });
+ assert_eq!(parse("#123"),
+ ColorSpec { kind: ColorKind::ARGB,
+ argb: 0xff112233, });
}
#[test]
- fn parses_color_keywords () {
- assert_eq! (parse ("red"), ColorSpec { kind: ColorKind::ARGB, argb: 0xffff0000 });
- assert_eq! (parse ("lime"), ColorSpec { kind: ColorKind::ARGB, argb: 0xff00ff00 });
- assert_eq! (parse ("blue"), ColorSpec { kind: ColorKind::ARGB, argb: 0xff0000ff });
+ fn parses_color_keywords() {
+ assert_eq!(parse("red"),
+ ColorSpec { kind: ColorKind::ARGB,
+ argb: 0xffff0000, });
+ assert_eq!(parse("lime"),
+ ColorSpec { kind: ColorKind::ARGB,
+ argb: 0xff00ff00, });
+ assert_eq!(parse("blue"),
+ ColorSpec { kind: ColorKind::ARGB,
+ argb: 0xff0000ff, });
}
#[test]
- fn parses_color_functions () {
- assert_eq! (parse ("rgb(255, 0, 0)"), ColorSpec { kind: ColorKind::ARGB, argb: 0xffff0000 });
- assert_eq! (parse ("rgb(0, 255, 0)"), ColorSpec { kind: ColorKind::ARGB, argb: 0xff00ff00 });
- assert_eq! (parse ("rgb(0, 0, 255)"), ColorSpec { kind: ColorKind::ARGB, argb: 0xff0000ff });
+ fn parses_color_functions() {
+ assert_eq!(parse("rgb(255, 0, 0)"),
+ ColorSpec { kind: ColorKind::ARGB,
+ argb: 0xffff0000, });
+ assert_eq!(parse("rgb(0, 255, 0)"),
+ ColorSpec { kind: ColorKind::ARGB,
+ argb: 0xff00ff00, });
+ assert_eq!(parse("rgb(0, 0, 255)"),
+ ColorSpec { kind: ColorKind::ARGB,
+ argb: 0xff0000ff, });
}
#[test]
- fn parses_current_color () {
- assert_eq! (parse ("currentColor"), ColorSpec { kind: ColorKind::CurrentColor, argb: 0 });
+ fn parses_current_color() {
+ assert_eq!(parse("currentColor"),
+ ColorSpec { kind: ColorKind::CurrentColor,
+ argb: 0, });
}
- fn make_error () -> ColorSpec {
- ColorSpec {
- kind: ColorKind::ParseError,
- argb: 0
- }
+ fn make_error() -> ColorSpec {
+ ColorSpec { kind: ColorKind::ParseError,
+ argb: 0, }
}
#[test]
- fn invalid_hash_hex_colors_yield_error () {
- assert_eq! (parse ("#"), make_error ());
- assert_eq! (parse ("#xyz"), make_error ());
- assert_eq! (parse ("#112233gg"), make_error ());
+ fn invalid_hash_hex_colors_yield_error() {
+ assert_eq!(parse("#"), make_error());
+ assert_eq!(parse("#xyz"), make_error());
+ assert_eq!(parse("#112233gg"), make_error());
}
#[test]
- fn invalid_colors_yield_error () {
- assert_eq! (parse (""), make_error ());
- assert_eq! (parse ("foo"), make_error ());
- assert_eq! (parse ("rgb(chilaquil)"), make_error ());
- assert_eq! (parse ("rgb(1, 2, 3, 4, 5)"), make_error ());
+ fn invalid_colors_yield_error() {
+ assert_eq!(parse(""), make_error());
+ assert_eq!(parse("foo"), make_error());
+ assert_eq!(parse("rgb(chilaquil)"), make_error());
+ assert_eq!(parse("rgb(1, 2, 3, 4, 5)"), make_error());
}
#[test]
- fn yields_error_on_disallowed_current_color () {
- assert_eq! (ColorSpec::from (Color::parse ("currentColor", (AllowInherit::Yes,
AllowCurrentColor::No))),
- make_error ());
+ fn yields_error_on_disallowed_current_color() {
+ assert_eq!(ColorSpec::from(Color::parse("currentColor",
+ (AllowInherit::Yes, AllowCurrentColor::No))),
+ make_error());
}
#[test]
- fn yields_error_on_disallowed_inherit () {
- assert_eq! (ColorSpec::from (Color::parse ("inherit", (AllowInherit::No, AllowCurrentColor::Yes))),
- make_error ());
+ fn yields_error_on_disallowed_inherit() {
+ assert_eq!(ColorSpec::from(Color::parse("inherit",
+ (AllowInherit::No, AllowCurrentColor::Yes))),
+ make_error());
}
- fn test_roundtrip (s: &str) {
- let result = Color::parse (s, (AllowInherit::Yes, AllowCurrentColor::Yes));
- let result2 = result.clone ();
- let spec = ColorSpec::from (result2);
+ fn test_roundtrip(s: &str) {
+ let result = Color::parse(s, (AllowInherit::Yes, AllowCurrentColor::Yes));
+ let result2 = result.clone();
+ let spec = ColorSpec::from(result2);
- if result.is_ok () {
- assert_eq! (Color::from_color_spec (&spec), result);
+ if result.is_ok() {
+ assert_eq!(Color::from_color_spec(&spec), result);
} else {
- assert! (Color::from_color_spec (&spec).is_err ());
+ assert!(Color::from_color_spec(&spec).is_err());
}
}
#[test]
- fn roundtrips () {
- test_roundtrip ("inherit");
- test_roundtrip ("currentColor");
- test_roundtrip ("#aabbccdd");
- test_roundtrip ("papadzul");
+ fn roundtrips() {
+ test_roundtrip("inherit");
+ test_roundtrip("currentColor");
+ test_roundtrip("#aabbccdd");
+ test_roundtrip("papadzul");
}
#[test]
- fn from_argb () {
- assert_eq! (Color::from (0xaabbccdd),
- Color::RGBA (cssparser::RGBA::new (0xbb, 0xcc, 0xdd, 0xaa)));
+ fn from_argb() {
+ assert_eq!(Color::from(0xaabbccdd),
+ Color::RGBA(cssparser::RGBA::new(0xbb, 0xcc, 0xdd, 0xaa)));
}
}
diff --git a/rsvg_internals/src/coord_units.rs b/rsvg_internals/src/coord_units.rs
index 845961dd..feaa7cb7 100644
--- a/rsvg_internals/src/coord_units.rs
+++ b/rsvg_internals/src/coord_units.rs
@@ -10,18 +10,21 @@ use parsers::{Parse, ParseError};
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum CoordUnits {
UserSpaceOnUse,
- ObjectBoundingBox
+ ObjectBoundingBox,
}
impl Parse for CoordUnits {
type Data = ();
type Err = AttributeError;
- fn parse (s: &str, _: ()) -> Result<CoordUnits, AttributeError> {
+ fn parse(s: &str, _: ()) -> Result<CoordUnits, AttributeError> {
match s {
- "userSpaceOnUse" => Ok (CoordUnits::UserSpaceOnUse),
- "objectBoundingBox" => Ok (CoordUnits::ObjectBoundingBox),
- _ => Err (AttributeError::Parse (ParseError::new ("expected 'userSpaceOnUse'
or 'objectBoundingBox'")))
+ "userSpaceOnUse" => Ok(CoordUnits::UserSpaceOnUse),
+ "objectBoundingBox" => Ok(CoordUnits::ObjectBoundingBox),
+ _ => {
+ Err(AttributeError::Parse(ParseError::new("expected 'userSpaceOnUse' or \
+ 'objectBoundingBox'")))
+ }
}
}
}
@@ -70,15 +73,17 @@ mod tests {
coord_units!(MyUnits, CoordUnits::ObjectBoundingBox);
#[test]
- fn parsing_invalid_strings_yields_error () {
- assert! (MyUnits::parse ("", ()).is_err ());
- assert! (MyUnits::parse ("foo", ()).is_err ());
+ fn parsing_invalid_strings_yields_error() {
+ assert!(MyUnits::parse("", ()).is_err());
+ assert!(MyUnits::parse("foo", ()).is_err());
}
#[test]
- fn parses_paint_server_units () {
- assert_eq! (MyUnits::parse ("userSpaceOnUse", ()), Ok (MyUnits(CoordUnits::UserSpaceOnUse)));
- assert_eq! (MyUnits::parse ("objectBoundingBox", ()), Ok (MyUnits(CoordUnits::ObjectBoundingBox)));
+ fn parses_paint_server_units() {
+ assert_eq!(MyUnits::parse("userSpaceOnUse", ()),
+ Ok(MyUnits(CoordUnits::UserSpaceOnUse)));
+ assert_eq!(MyUnits::parse("objectBoundingBox", ()),
+ Ok(MyUnits(CoordUnits::ObjectBoundingBox)));
}
#[test]
@@ -88,6 +93,7 @@ mod tests {
#[test]
fn converts_to_coord_units() {
- assert_eq!(CoordUnits::from(MyUnits(CoordUnits::ObjectBoundingBox)), CoordUnits::ObjectBoundingBox);
+ assert_eq!(CoordUnits::from(MyUnits(CoordUnits::ObjectBoundingBox)),
+ CoordUnits::ObjectBoundingBox);
}
}
diff --git a/rsvg_internals/src/drawing_ctx.rs b/rsvg_internals/src/drawing_ctx.rs
index 93ae444c..80f26871 100644
--- a/rsvg_internals/src/drawing_ctx.rs
+++ b/rsvg_internals/src/drawing_ctx.rs
@@ -1,301 +1,314 @@
use cairo;
use cairo_sys;
-use glib_sys;
use glib::translate::*;
+use glib_sys;
use libc;
-use pango_sys;
use pango;
+use pango_sys;
use color::*;
use error::*;
-use opacity::*;
-use node::RsvgNode;
use node::NodeType;
+use node::RsvgNode;
+use opacity::*;
use path_builder::RsvgPathBuilder;
use state::RsvgState;
pub enum RsvgDrawingCtx {}
extern "C" {
- fn rsvg_drawing_ctx_get_dpi (draw_ctx: *const RsvgDrawingCtx,
- out_dpi_x: *mut f64,
- out_dpi_y: *mut f64);
+ fn rsvg_drawing_ctx_get_dpi(draw_ctx: *const RsvgDrawingCtx,
+ out_dpi_x: *mut f64,
+ out_dpi_y: *mut f64);
- fn rsvg_drawing_ctx_get_normalized_font_size (draw_ctx: *const RsvgDrawingCtx) -> f64;
+ fn rsvg_drawing_ctx_get_normalized_font_size(draw_ctx: *const RsvgDrawingCtx) -> f64;
- fn rsvg_drawing_ctx_get_view_box_size (draw_ctx: *const RsvgDrawingCtx,
- out_x: *mut f64,
- out_y: *mut f64);
+ fn rsvg_drawing_ctx_get_view_box_size(draw_ctx: *const RsvgDrawingCtx,
+ out_x: *mut f64,
+ out_y: *mut f64);
- fn rsvg_drawing_ctx_push_view_box (draw_ctx: *const RsvgDrawingCtx,
- width: f64,
- height: f64);
+ fn rsvg_drawing_ctx_push_view_box(draw_ctx: *const RsvgDrawingCtx, width: f64, height: f64);
- fn rsvg_drawing_ctx_pop_view_box (draw_ctx: *const RsvgDrawingCtx);
+ fn rsvg_drawing_ctx_pop_view_box(draw_ctx: *const RsvgDrawingCtx);
- fn rsvg_drawing_ctx_acquire_node (draw_ctx: *const RsvgDrawingCtx,
- url: *const libc::c_char) -> *mut RsvgNode;
+ fn rsvg_drawing_ctx_acquire_node(draw_ctx: *const RsvgDrawingCtx,
+ url: *const libc::c_char)
+ -> *mut RsvgNode;
- fn rsvg_drawing_ctx_acquire_node_of_type (draw_ctx: *const RsvgDrawingCtx,
- url: *const libc::c_char,
- node_type: NodeType) -> *mut RsvgNode;
+ fn rsvg_drawing_ctx_acquire_node_of_type(draw_ctx: *const RsvgDrawingCtx,
+ url: *const libc::c_char,
+ node_type: NodeType)
+ -> *mut RsvgNode;
- fn rsvg_drawing_ctx_release_node (draw_ctx: *const RsvgDrawingCtx,
- node: *mut RsvgNode);
+ fn rsvg_drawing_ctx_release_node(draw_ctx: *const RsvgDrawingCtx, node: *mut RsvgNode);
- fn rsvg_drawing_ctx_get_current_state_affine (draw_ctx: *const RsvgDrawingCtx) -> cairo::Matrix;
+ fn rsvg_drawing_ctx_get_current_state_affine(draw_ctx: *const RsvgDrawingCtx) -> cairo::Matrix;
- fn rsvg_drawing_ctx_set_current_state_affine (draw_ctx: *const RsvgDrawingCtx,
- affine: *const cairo::Matrix);
+ fn rsvg_drawing_ctx_set_current_state_affine(draw_ctx: *const RsvgDrawingCtx,
+ affine: *const cairo::Matrix);
- fn rsvg_drawing_ctx_get_pango_context(draw_ctx: *const RsvgDrawingCtx) -> *mut pango_sys::PangoContext;
+ fn rsvg_drawing_ctx_get_pango_context(draw_ctx: *const RsvgDrawingCtx)
+ -> *mut pango_sys::PangoContext;
- fn rsvg_drawing_ctx_add_clipping_rect (draw_ctx: *const RsvgDrawingCtx,
- x: f64,
- y: f64,
- w: f64,
- h: f64);
+ fn rsvg_drawing_ctx_add_clipping_rect(draw_ctx: *const RsvgDrawingCtx,
+ x: f64,
+ y: f64,
+ w: f64,
+ h: f64);
- fn rsvg_drawing_ctx_draw_node_from_stack (draw_ctx: *const RsvgDrawingCtx,
- node: *const RsvgNode,
- dominate: i32);
+ fn rsvg_drawing_ctx_draw_node_from_stack(draw_ctx: *const RsvgDrawingCtx,
+ node: *const RsvgNode,
+ dominate: i32);
- fn rsvg_current_state (draw_ctx: *const RsvgDrawingCtx) -> *mut RsvgState;
- fn rsvg_state_new () -> *mut RsvgState;
- fn rsvg_state_free (state: *mut RsvgState);
- fn rsvg_state_reinit (state: *mut RsvgState);
- fn rsvg_state_reconstruct (state: *mut RsvgState, node: *const RsvgNode);
- fn rsvg_state_is_overflow (state: *const RsvgState) -> glib_sys::gboolean;
- fn rsvg_state_has_overflow (state: *const RsvgState) -> glib_sys::gboolean;
- fn rsvg_state_get_cond_true (state: *const RsvgState) -> glib_sys::gboolean;
- fn rsvg_state_set_cond_true (state: *const RsvgState, cond_true: glib_sys::gboolean);
- fn rsvg_state_get_stop_color (state: *const RsvgState) -> *const ColorSpec;
- fn rsvg_state_get_stop_opacity (state: *const RsvgState) -> *const OpacitySpec;
- fn rsvg_state_get_current_color (state: *const RsvgState) -> u32;
+ fn rsvg_current_state(draw_ctx: *const RsvgDrawingCtx) -> *mut RsvgState;
+ fn rsvg_state_new() -> *mut RsvgState;
+ fn rsvg_state_free(state: *mut RsvgState);
+ fn rsvg_state_reinit(state: *mut RsvgState);
+ fn rsvg_state_reconstruct(state: *mut RsvgState, node: *const RsvgNode);
+ fn rsvg_state_is_overflow(state: *const RsvgState) -> glib_sys::gboolean;
+ fn rsvg_state_has_overflow(state: *const RsvgState) -> glib_sys::gboolean;
+ fn rsvg_state_get_cond_true(state: *const RsvgState) -> glib_sys::gboolean;
+ fn rsvg_state_set_cond_true(state: *const RsvgState, cond_true: glib_sys::gboolean);
+ fn rsvg_state_get_stop_color(state: *const RsvgState) -> *const ColorSpec;
+ fn rsvg_state_get_stop_opacity(state: *const RsvgState) -> *const OpacitySpec;
+ fn rsvg_state_get_current_color(state: *const RsvgState) -> u32;
- fn rsvg_state_push (draw_ctx: *const RsvgDrawingCtx);
- fn rsvg_state_pop (draw_ctx: *const RsvgDrawingCtx);
+ fn rsvg_state_push(draw_ctx: *const RsvgDrawingCtx);
+ fn rsvg_state_pop(draw_ctx: *const RsvgDrawingCtx);
- fn rsvg_state_reinherit_top (draw_ctx: *const RsvgDrawingCtx,
- state: *mut RsvgState,
- dominate: libc::c_int);
+ fn rsvg_state_reinherit_top(draw_ctx: *const RsvgDrawingCtx,
+ state: *mut RsvgState,
+ dominate: libc::c_int);
- fn rsvg_push_discrete_layer (draw_ctx: *const RsvgDrawingCtx);
- fn rsvg_pop_discrete_layer (draw_ctx: *const RsvgDrawingCtx);
+ fn rsvg_push_discrete_layer(draw_ctx: *const RsvgDrawingCtx);
+ fn rsvg_pop_discrete_layer(draw_ctx: *const RsvgDrawingCtx);
- fn rsvg_render_path_builder (draw_ctx: *const RsvgDrawingCtx,
- builder: *const RsvgPathBuilder);
- fn rsvg_render_surface (draw_ctx: *const RsvgDrawingCtx,
- surface: *const cairo_sys::cairo_surface_t,
- x: f64,
- y: f64,
- w: f64,
- h: f64);
+ fn rsvg_render_path_builder(draw_ctx: *const RsvgDrawingCtx, builder: *const RsvgPathBuilder);
+ fn rsvg_render_surface(draw_ctx: *const RsvgDrawingCtx,
+ surface: *const cairo_sys::cairo_surface_t,
+ x: f64,
+ y: f64,
+ w: f64,
+ h: f64);
- fn rsvg_cairo_get_cairo_context (draw_ctx: *const RsvgDrawingCtx) -> *mut cairo_sys::cairo_t;
- fn rsvg_cairo_set_cairo_context (draw_ctx: *const RsvgDrawingCtx, cr: *const cairo_sys::cairo_t);
+ fn rsvg_cairo_get_cairo_context(draw_ctx: *const RsvgDrawingCtx) -> *mut cairo_sys::cairo_t;
+ fn rsvg_cairo_set_cairo_context(draw_ctx: *const RsvgDrawingCtx, cr: *const cairo_sys::cairo_t);
}
-pub fn get_dpi (draw_ctx: *const RsvgDrawingCtx) -> (f64, f64) {
+pub fn get_dpi(draw_ctx: *const RsvgDrawingCtx) -> (f64, f64) {
let mut dpi_x: f64 = 0.0;
let mut dpi_y: f64 = 0.0;
- unsafe { rsvg_drawing_ctx_get_dpi (draw_ctx, &mut dpi_x, &mut dpi_y); }
+ unsafe {
+ rsvg_drawing_ctx_get_dpi(draw_ctx, &mut dpi_x, &mut dpi_y);
+ }
(dpi_x, dpi_y)
}
-
-pub fn get_normalized_font_size (draw_ctx: *const RsvgDrawingCtx) -> f64 {
- unsafe { rsvg_drawing_ctx_get_normalized_font_size (draw_ctx) }
+pub fn get_normalized_font_size(draw_ctx: *const RsvgDrawingCtx) -> f64 {
+ unsafe { rsvg_drawing_ctx_get_normalized_font_size(draw_ctx) }
}
-pub fn get_view_box_size (draw_ctx: *const RsvgDrawingCtx) -> (f64, f64) {
+pub fn get_view_box_size(draw_ctx: *const RsvgDrawingCtx) -> (f64, f64) {
let mut w: f64 = 0.0;
let mut h: f64 = 0.0;
- unsafe { rsvg_drawing_ctx_get_view_box_size (draw_ctx, &mut w, &mut h); }
+ unsafe {
+ rsvg_drawing_ctx_get_view_box_size(draw_ctx, &mut w, &mut h);
+ }
(w, h)
}
-pub fn push_view_box (draw_ctx: *const RsvgDrawingCtx,
- width: f64,
- height: f64)
-{
- unsafe { rsvg_drawing_ctx_push_view_box (draw_ctx, width, height); }
+pub fn push_view_box(draw_ctx: *const RsvgDrawingCtx, width: f64, height: f64) {
+ unsafe {
+ rsvg_drawing_ctx_push_view_box(draw_ctx, width, height);
+ }
}
-pub fn pop_view_box (draw_ctx: *const RsvgDrawingCtx) {
- unsafe { rsvg_drawing_ctx_pop_view_box (draw_ctx); }
+pub fn pop_view_box(draw_ctx: *const RsvgDrawingCtx) {
+ unsafe {
+ rsvg_drawing_ctx_pop_view_box(draw_ctx);
+ }
}
-pub fn acquire_node (draw_ctx: *const RsvgDrawingCtx,
- url: &str) -> *mut RsvgNode {
- unsafe { rsvg_drawing_ctx_acquire_node (draw_ctx, str::to_glib_none (url).0) }
+pub fn acquire_node(draw_ctx: *const RsvgDrawingCtx, url: &str) -> *mut RsvgNode {
+ unsafe { rsvg_drawing_ctx_acquire_node(draw_ctx, str::to_glib_none(url).0) }
}
-pub fn acquire_node_of_type (draw_ctx: *const RsvgDrawingCtx,
- url: &str,
- node_type: NodeType) -> *mut RsvgNode {
- unsafe { rsvg_drawing_ctx_acquire_node_of_type (draw_ctx, str::to_glib_none (url).0, node_type) }
+pub fn acquire_node_of_type(draw_ctx: *const RsvgDrawingCtx,
+ url: &str,
+ node_type: NodeType)
+ -> *mut RsvgNode {
+ unsafe { rsvg_drawing_ctx_acquire_node_of_type(draw_ctx, str::to_glib_none(url).0, node_type) }
}
-pub fn release_node (draw_ctx: *const RsvgDrawingCtx,
- node: *mut RsvgNode) {
- unsafe { rsvg_drawing_ctx_release_node (draw_ctx, node); }
+pub fn release_node(draw_ctx: *const RsvgDrawingCtx, node: *mut RsvgNode) {
+ unsafe {
+ rsvg_drawing_ctx_release_node(draw_ctx, node);
+ }
}
-pub fn state_reinherit_top (draw_ctx: *const RsvgDrawingCtx,
- state: *mut RsvgState,
- dominate: i32) {
- unsafe { rsvg_state_reinherit_top (draw_ctx, state, dominate); }
+pub fn state_reinherit_top(draw_ctx: *const RsvgDrawingCtx, state: *mut RsvgState, dominate: i32) {
+ unsafe {
+ rsvg_state_reinherit_top(draw_ctx, state, dominate);
+ }
}
-pub fn push_discrete_layer (draw_ctx: *const RsvgDrawingCtx) {
- unsafe { rsvg_push_discrete_layer (draw_ctx); }
+pub fn push_discrete_layer(draw_ctx: *const RsvgDrawingCtx) {
+ unsafe {
+ rsvg_push_discrete_layer(draw_ctx);
+ }
}
-pub fn pop_discrete_layer (draw_ctx: *const RsvgDrawingCtx) {
- unsafe { rsvg_pop_discrete_layer (draw_ctx); }
+pub fn pop_discrete_layer(draw_ctx: *const RsvgDrawingCtx) {
+ unsafe {
+ rsvg_pop_discrete_layer(draw_ctx);
+ }
}
-pub fn render_path_builder (draw_ctx: *const RsvgDrawingCtx,
- builder: &RsvgPathBuilder) {
- unsafe { rsvg_render_path_builder (draw_ctx, builder); }
+pub fn render_path_builder(draw_ctx: *const RsvgDrawingCtx, builder: &RsvgPathBuilder) {
+ unsafe {
+ rsvg_render_path_builder(draw_ctx, builder);
+ }
}
-pub fn render_surface (draw_ctx: *const RsvgDrawingCtx,
- surface: &cairo::ImageSurface,
- x: f64,
- y: f64,
- w: f64,
- h: f64) {
- unsafe { rsvg_render_surface (draw_ctx, surface.to_raw_none(), x, y, w, h); }
+pub fn render_surface(draw_ctx: *const RsvgDrawingCtx,
+ surface: &cairo::ImageSurface,
+ x: f64,
+ y: f64,
+ w: f64,
+ h: f64) {
+ unsafe {
+ rsvg_render_surface(draw_ctx, surface.to_raw_none(), x, y, w, h);
+ }
}
-pub fn get_cairo_context (draw_ctx: *const RsvgDrawingCtx) -> cairo::Context {
+pub fn get_cairo_context(draw_ctx: *const RsvgDrawingCtx) -> cairo::Context {
unsafe {
- let raw_cr = rsvg_cairo_get_cairo_context (draw_ctx);
+ let raw_cr = rsvg_cairo_get_cairo_context(draw_ctx);
- cairo::Context::from_glib_none (raw_cr)
+ cairo::Context::from_glib_none(raw_cr)
}
}
-pub fn set_cairo_context (draw_ctx: *const RsvgDrawingCtx, cr: &cairo::Context) {
+pub fn set_cairo_context(draw_ctx: *const RsvgDrawingCtx, cr: &cairo::Context) {
unsafe {
- let raw_cr = cr.to_glib_none ().0;
+ let raw_cr = cr.to_glib_none().0;
- rsvg_cairo_set_cairo_context (draw_ctx, raw_cr);
+ rsvg_cairo_set_cairo_context(draw_ctx, raw_cr);
}
}
-pub fn get_current_state_affine (draw_ctx: *const RsvgDrawingCtx) -> cairo::Matrix {
- unsafe {
- rsvg_drawing_ctx_get_current_state_affine (draw_ctx)
- }
+pub fn get_current_state_affine(draw_ctx: *const RsvgDrawingCtx) -> cairo::Matrix {
+ unsafe { rsvg_drawing_ctx_get_current_state_affine(draw_ctx) }
}
-pub fn set_current_state_affine (draw_ctx: *const RsvgDrawingCtx, affine: cairo::Matrix) {
+pub fn set_current_state_affine(draw_ctx: *const RsvgDrawingCtx, affine: cairo::Matrix) {
unsafe {
- rsvg_drawing_ctx_set_current_state_affine (draw_ctx, &affine);
+ rsvg_drawing_ctx_set_current_state_affine(draw_ctx, &affine);
}
}
pub fn get_pango_context(draw_ctx: *const RsvgDrawingCtx) -> pango::Context {
- unsafe {
- from_glib_full(rsvg_drawing_ctx_get_pango_context(draw_ctx))
- }
+ unsafe { from_glib_full(rsvg_drawing_ctx_get_pango_context(draw_ctx)) }
}
-pub fn add_clipping_rect (draw_ctx: *const RsvgDrawingCtx,
- x: f64,
- y: f64,
- w: f64,
- h: f64) {
- unsafe { rsvg_drawing_ctx_add_clipping_rect (draw_ctx, x, y, w, h); }
+pub fn add_clipping_rect(draw_ctx: *const RsvgDrawingCtx, x: f64, y: f64, w: f64, h: f64) {
+ unsafe {
+ rsvg_drawing_ctx_add_clipping_rect(draw_ctx, x, y, w, h);
+ }
}
-pub fn draw_node_from_stack (draw_ctx: *const RsvgDrawingCtx,
- node: *const RsvgNode,
- dominate: i32) {
- unsafe { rsvg_drawing_ctx_draw_node_from_stack (draw_ctx, node, dominate); }
+pub fn draw_node_from_stack(draw_ctx: *const RsvgDrawingCtx, node: *const RsvgNode, dominate: i32) {
+ unsafe {
+ rsvg_drawing_ctx_draw_node_from_stack(draw_ctx, node, dominate);
+ }
}
-pub fn get_current_state (draw_ctx: *const RsvgDrawingCtx) -> *mut RsvgState {
- unsafe { rsvg_current_state (draw_ctx) }
+pub fn get_current_state(draw_ctx: *const RsvgDrawingCtx) -> *mut RsvgState {
+ unsafe { rsvg_current_state(draw_ctx) }
}
-pub fn state_new () -> *mut RsvgState {
- unsafe { rsvg_state_new () }
+pub fn state_new() -> *mut RsvgState {
+ unsafe { rsvg_state_new() }
}
-pub fn state_free (state: *mut RsvgState) {
- unsafe { rsvg_state_free (state); }
+pub fn state_free(state: *mut RsvgState) {
+ unsafe {
+ rsvg_state_free(state);
+ }
}
-pub fn state_reinit (state: *mut RsvgState) {
- unsafe { rsvg_state_reinit (state); }
+pub fn state_reinit(state: *mut RsvgState) {
+ unsafe {
+ rsvg_state_reinit(state);
+ }
}
-pub fn state_reconstruct (state: *mut RsvgState, node: *const RsvgNode) {
- unsafe { rsvg_state_reconstruct (state, node); }
+pub fn state_reconstruct(state: *mut RsvgState, node: *const RsvgNode) {
+ unsafe {
+ rsvg_state_reconstruct(state, node);
+ }
}
-pub fn state_is_overflow (state: *const RsvgState) -> bool {
- unsafe { from_glib (rsvg_state_is_overflow (state)) }
+pub fn state_is_overflow(state: *const RsvgState) -> bool {
+ unsafe { from_glib(rsvg_state_is_overflow(state)) }
}
-pub fn state_has_overflow (state: *const RsvgState) -> bool {
- unsafe { from_glib (rsvg_state_has_overflow (state)) }
+pub fn state_has_overflow(state: *const RsvgState) -> bool {
+ unsafe { from_glib(rsvg_state_has_overflow(state)) }
}
-pub fn state_get_cond_true (state: *const RsvgState) -> bool {
- unsafe { from_glib (rsvg_state_get_cond_true (state)) }
+pub fn state_get_cond_true(state: *const RsvgState) -> bool {
+ unsafe { from_glib(rsvg_state_get_cond_true(state)) }
}
-pub fn state_set_cond_true (state: *const RsvgState, cond_true: bool) {
- unsafe { rsvg_state_set_cond_true (state, cond_true.to_glib()); }
+pub fn state_set_cond_true(state: *const RsvgState, cond_true: bool) {
+ unsafe {
+ rsvg_state_set_cond_true(state, cond_true.to_glib());
+ }
}
-pub fn state_push (draw_ctx: *const RsvgDrawingCtx) {
+pub fn state_push(draw_ctx: *const RsvgDrawingCtx) {
unsafe {
- rsvg_state_push (draw_ctx);
+ rsvg_state_push(draw_ctx);
}
}
-pub fn state_pop (draw_ctx: *const RsvgDrawingCtx) {
+pub fn state_pop(draw_ctx: *const RsvgDrawingCtx) {
unsafe {
- rsvg_state_pop (draw_ctx);
+ rsvg_state_pop(draw_ctx);
}
}
-pub fn state_get_stop_color (state: *const RsvgState) -> Result<Option<Color>, AttributeError> {
+pub fn state_get_stop_color(state: *const RsvgState) -> Result<Option<Color>, AttributeError> {
unsafe {
- let spec_ptr = rsvg_state_get_stop_color (state);
+ let spec_ptr = rsvg_state_get_stop_color(state);
- if spec_ptr.is_null () {
- Ok (None)
+ if spec_ptr.is_null() {
+ Ok(None)
} else {
- Color::from_color_spec (&*spec_ptr).map (Some)
+ Color::from_color_spec(&*spec_ptr).map(Some)
}
}
}
-pub fn state_get_stop_opacity (state: *const RsvgState) -> Result<Option<Opacity>, AttributeError> {
+pub fn state_get_stop_opacity(state: *const RsvgState) -> Result<Option<Opacity>, AttributeError> {
unsafe {
- let opacity_ptr = rsvg_state_get_stop_opacity (state);
+ let opacity_ptr = rsvg_state_get_stop_opacity(state);
- if opacity_ptr.is_null () {
- Ok (None)
+ if opacity_ptr.is_null() {
+ Ok(None)
} else {
- Opacity::from_opacity_spec (&*opacity_ptr).map (Some)
+ Opacity::from_opacity_spec(&*opacity_ptr).map(Some)
}
}
}
-pub fn state_get_current_color (state: *const RsvgState) -> Color {
- let argb = unsafe { rsvg_state_get_current_color (state) };
+pub fn state_get_current_color(state: *const RsvgState) -> Color {
+ let argb = unsafe { rsvg_state_get_current_color(state) };
- Color::from (argb)
+ Color::from(argb)
}
diff --git a/rsvg_internals/src/error.rs b/rsvg_internals/src/error.rs
index 615415c1..cb9e7420 100644
--- a/rsvg_internals/src/error.rs
+++ b/rsvg_internals/src/error.rs
@@ -1,97 +1,93 @@
-use std::fmt;
use std::error;
+use std::fmt;
-use cssparser::{BasicParseError};
+use cssparser::BasicParseError;
use parsers::ParseError;
#[derive(Debug, Clone, PartialEq)]
pub enum AttributeError {
// parse error
- Parse (ParseError),
+ Parse(ParseError),
// invalid value
- Value (String)
+ Value(String),
}
#[derive(Debug, Clone, PartialEq)]
pub struct NodeError {
attr_name: String,
- err: AttributeError
+ err: AttributeError,
}
impl NodeError {
- pub fn parse_error (attr_name: &str, error: ParseError) -> NodeError {
- NodeError {
- attr_name: attr_name.to_string (),
- err: AttributeError::Parse (error)
- }
+ pub fn parse_error(attr_name: &str, error: ParseError) -> NodeError {
+ NodeError { attr_name: attr_name.to_string(),
+ err: AttributeError::Parse(error), }
}
- pub fn value_error (attr_name: &str, description: &str) -> NodeError {
- NodeError {
- attr_name: attr_name.to_string (),
- err: AttributeError::Value (description.to_string ())
- }
+ pub fn value_error(attr_name: &str, description: &str) -> NodeError {
+ NodeError { attr_name: attr_name.to_string(),
+ err: AttributeError::Value(description.to_string()), }
}
- pub fn attribute_error (attr_name: &str, error: AttributeError) -> NodeError {
- NodeError {
- attr_name: attr_name.to_string (),
- err: error
- }
+ pub fn attribute_error(attr_name: &str, error: AttributeError) -> NodeError {
+ NodeError { attr_name: attr_name.to_string(),
+ err: error, }
}
}
impl error::Error for NodeError {
- fn description (&self) -> &str {
+ fn description(&self) -> &str {
match self.err {
- AttributeError::Parse (_) => "parse error",
- AttributeError::Value (_) => "invalid attribute value"
+ AttributeError::Parse(_) => "parse error",
+ AttributeError::Value(_) => "invalid attribute value",
}
}
}
impl fmt::Display for NodeError {
- fn fmt (&self, f: &mut fmt::Formatter) -> fmt::Result {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.err {
- AttributeError::Parse (ref n) => write! (f,
- "error parsing value for attribute \"{}\": {}",
- self.attr_name,
- n.display),
+ AttributeError::Parse(ref n) => {
+ write!(f,
+ "error parsing value for attribute \"{}\": {}",
+ self.attr_name, n.display)
+ }
- AttributeError::Value (ref s) => write! (f,
- "invalid value for attribute \"{}\": {}",
- self.attr_name,
- s)
+ AttributeError::Value(ref s) => {
+ write!(f,
+ "invalid value for attribute \"{}\": {}",
+ self.attr_name, s)
+ }
}
}
}
impl From<ParseError> for AttributeError {
- fn from (pe: ParseError) -> AttributeError {
- AttributeError::Parse (pe)
+ fn from(pe: ParseError) -> AttributeError {
+ AttributeError::Parse(pe)
}
}
impl<'a> From<BasicParseError<'a>> for AttributeError {
- fn from (e: BasicParseError) -> AttributeError {
+ fn from(e: BasicParseError) -> AttributeError {
AttributeError::from(ParseError::from(e))
}
}
#[cfg(test)]
-pub fn is_parse_error<T> (r: &Result<T, AttributeError>) -> bool {
+pub fn is_parse_error<T>(r: &Result<T, AttributeError>) -> bool {
match *r {
- Err (AttributeError::Parse (_)) => true,
- _ => false
+ Err(AttributeError::Parse(_)) => true,
+ _ => false,
}
}
#[cfg(test)]
-pub fn is_value_error<T> (r: &Result<T, AttributeError>) -> bool {
+pub fn is_value_error<T>(r: &Result<T, AttributeError>) -> bool {
match *r {
- Err (AttributeError::Value (_)) => true,
- _ => false
+ Err(AttributeError::Value(_)) => true,
+ _ => false,
}
}
diff --git a/rsvg_internals/src/gradient.rs b/rsvg_internals/src/gradient.rs
index d62f76ba..4a10f9df 100644
--- a/rsvg_internals/src/gradient.rs
+++ b/rsvg_internals/src/gradient.rs
@@ -14,16 +14,15 @@ use handle::RsvgHandle;
use length::*;
use node::*;
use paint_server::*;
-use parsers::{Parse, parse};
+use parsers::{parse, Parse};
use property_bag::PropertyBag;
use stop::*;
use util::*;
-
#[derive(Copy, Clone)]
struct ColorStop {
pub offset: f64,
- pub rgba: u32
+ pub rgba: u32,
}
coord_units!(GradientUnits, CoordUnits::ObjectBoundingBox);
@@ -34,11 +33,11 @@ coord_units!(GradientUnits, CoordUnits::ObjectBoundingBox);
*/
#[derive(Clone)]
struct GradientCommon {
- pub units: Option<GradientUnits>,
- pub affine: Option<cairo::Matrix>,
- pub spread: Option<PaintServerSpread>,
+ pub units: Option<GradientUnits>,
+ pub affine: Option<cairo::Matrix>,
+ pub spread: Option<PaintServerSpread>,
pub fallback: Option<String>,
- pub stops: Option<Vec<ColorStop>>
+ pub stops: Option<Vec<ColorStop>>,
}
#[derive(Copy, Clone)]
@@ -47,33 +46,31 @@ enum GradientVariant {
x1: Option<RsvgLength>,
y1: Option<RsvgLength>,
x2: Option<RsvgLength>,
- y2: Option<RsvgLength>
+ y2: Option<RsvgLength>,
},
Radial {
cx: Option<RsvgLength>,
cy: Option<RsvgLength>,
- r: Option<RsvgLength>,
+ r: Option<RsvgLength>,
fx: Option<RsvgLength>,
fy: Option<RsvgLength>,
- }
+ },
}
#[derive(Clone)]
struct Gradient {
pub common: GradientCommon,
- pub variant: GradientVariant
+ pub variant: GradientVariant,
}
impl Default for GradientCommon {
- fn default () -> GradientCommon {
- GradientCommon {
- units: Some(GradientUnits::default()),
- affine: Some(cairo::Matrix::identity()),
- spread: Some(PaintServerSpread::default()),
- fallback: None,
- stops: Some(Vec::<ColorStop>::new()),
- }
+ fn default() -> GradientCommon {
+ GradientCommon { units: Some(GradientUnits::default()),
+ affine: Some(cairo::Matrix::identity()),
+ spread: Some(PaintServerSpread::default()),
+ fallback: None,
+ stops: Some(Vec::<ColorStop>::new()), }
}
}
@@ -102,51 +99,47 @@ macro_rules! fallback_to (
impl GradientCommon {
fn unresolved() -> GradientCommon {
- GradientCommon {
- units: None,
- affine: None,
- spread: None,
- fallback: None,
- stops: None,
- }
+ GradientCommon { units: None,
+ affine: None,
+ spread: None,
+ fallback: None,
+ stops: None, }
}
- fn clone_stops (&self) -> Option<Vec<ColorStop>> {
- if let Some (ref stops) = self.stops {
- Some (stops.clone ())
+ fn clone_stops(&self) -> Option<Vec<ColorStop>> {
+ if let Some(ref stops) = self.stops {
+ Some(stops.clone())
} else {
None
}
}
- fn is_resolved (&self) -> bool {
- self.units.is_some() &&
- self.affine.is_some () &&
- self.spread.is_some () &&
- self.stops.is_some()
+ fn is_resolved(&self) -> bool {
+ self.units.is_some() && self.affine.is_some() && self.spread.is_some()
+ && self.stops.is_some()
}
- fn resolve_from_defaults (&mut self) {
+ fn resolve_from_defaults(&mut self) {
self.resolve_from_fallback(&GradientCommon::default());
}
- fn resolve_from_fallback (&mut self, fallback: &GradientCommon) {
- fallback_to! (self.units, fallback.units);
- fallback_to! (self.affine, fallback.affine);
- fallback_to! (self.spread, fallback.spread);
- fallback_to! (self.stops, fallback.clone_stops ());
+ fn resolve_from_fallback(&mut self, fallback: &GradientCommon) {
+ fallback_to!(self.units, fallback.units);
+ fallback_to!(self.affine, fallback.affine);
+ fallback_to!(self.spread, fallback.spread);
+ fallback_to!(self.stops, fallback.clone_stops());
- self.fallback = clone_fallback_name (&fallback.fallback);
+ self.fallback = clone_fallback_name(&fallback.fallback);
}
- fn add_color_stop (&mut self, mut offset: f64, rgba: u32) {
- if self.stops.is_none () {
- self.stops = Some (Vec::<ColorStop>::new ());
+ fn add_color_stop(&mut self, mut offset: f64, rgba: u32) {
+ if self.stops.is_none() {
+ self.stops = Some(Vec::<ColorStop>::new());
}
- if let Some (ref mut stops) = self.stops {
+ if let Some(ref mut stops) = self.stops {
let last_offset: f64 = if !stops.is_empty() {
- stops[stops.len () - 1].offset
+ stops[stops.len() - 1].offset
} else {
0.0
};
@@ -155,49 +148,37 @@ impl GradientCommon {
offset = last_offset;
}
- stops.push (ColorStop { offset: offset,
- rgba: rgba });
+ stops.push(ColorStop { offset, rgba });
} else {
- unreachable! ();
+ unreachable!();
}
}
}
impl GradientVariant {
fn unresolved_linear() -> Self {
- GradientVariant::Linear {
- x1: None,
- y1: None,
- x2: None,
- y2: None,
- }
+ GradientVariant::Linear { x1: None,
+ y1: None,
+ x2: None,
+ y2: None, }
}
fn unresolved_radial() -> Self {
- GradientVariant::Radial {
- cx: None,
- cy: None,
- r: None,
- fx: None,
- fy: None,
- }
+ GradientVariant::Radial { cx: None,
+ cy: None,
+ r: None,
+ fx: None,
+ fy: None, }
}
- fn is_resolved (&self) -> bool {
+ fn is_resolved(&self) -> bool {
match *self {
GradientVariant::Linear { x1, y1, x2, y2 } => {
- x1.is_some () &&
- y1.is_some () &&
- x2.is_some () &&
- y2.is_some ()
- },
+ x1.is_some() && y1.is_some() && x2.is_some() && y2.is_some()
+ }
GradientVariant::Radial { cx, cy, r, fx, fy } => {
- cx.is_some () &&
- cy.is_some () &&
- r.is_some () &&
- fx.is_some () &&
- fy.is_some ()
+ cx.is_some() && cy.is_some() && r.is_some() && fx.is_some() && fy.is_some()
}
}
}
@@ -216,53 +197,75 @@ impl GradientVariant {
fn default_radial() -> Self {
// https://www.w3.org/TR/SVG/pservers.html#RadialGradients
- GradientVariant::Radial {
- cx: Some(RsvgLength::parse("50%", LengthDir::Horizontal).unwrap()),
- cy: Some(RsvgLength::parse("50%", LengthDir::Vertical).unwrap()),
- r: Some(RsvgLength::parse("50%", LengthDir::Both).unwrap()),
+ GradientVariant::Radial { cx:
+ Some(RsvgLength::parse("50%", LengthDir::Horizontal).unwrap()),
+ cy:
+ Some(RsvgLength::parse("50%", LengthDir::Vertical).unwrap()),
+ r: Some(RsvgLength::parse("50%", LengthDir::Both).unwrap()),
- fx: None,
- fy: None,
- }
+ fx: None,
+ fy: None, }
}
- fn resolve_from_defaults (&mut self) {
+ fn resolve_from_defaults(&mut self) {
/* These are per the spec */
match *self {
- GradientVariant::Linear { .. } =>
- self.resolve_from_fallback(&GradientVariant::default_linear()),
+ GradientVariant::Linear { .. } => {
+ self.resolve_from_fallback(&GradientVariant::default_linear())
+ }
GradientVariant::Radial { .. } => {
self.resolve_from_fallback(&GradientVariant::default_radial());
- },
+ }
}
- if let GradientVariant::Radial { cx, cy, ref mut fx, ref mut fy, .. } = *self {
+ if let GradientVariant::Radial { cx,
+ cy,
+ ref mut fx,
+ ref mut fy,
+ .. } = *self
+ {
// fx and fy fall back to the presentational value of cx and cy
fallback_to!(*fx, cx);
fallback_to!(*fy, cy);
}
}
- fn resolve_from_fallback (&mut self, fallback: &GradientVariant) {
+ fn resolve_from_fallback(&mut self, fallback: &GradientVariant) {
match *self {
- GradientVariant::Linear { ref mut x1, ref mut y1, ref mut x2, ref mut y2 } => {
- if let GradientVariant::Linear { x1: x1f, y1: y1f, x2: x2f, y2: y2f } = *fallback {
- fallback_to! (*x1, x1f);
- fallback_to! (*y1, y1f);
- fallback_to! (*x2, x2f);
- fallback_to! (*y2, y2f);
+ GradientVariant::Linear { ref mut x1,
+ ref mut y1,
+ ref mut x2,
+ ref mut y2, } => {
+ if let GradientVariant::Linear { x1: x1f,
+ y1: y1f,
+ x2: x2f,
+ y2: y2f, } = *fallback
+ {
+ fallback_to!(*x1, x1f);
+ fallback_to!(*y1, y1f);
+ fallback_to!(*x2, x2f);
+ fallback_to!(*y2, y2f);
}
- },
-
- GradientVariant::Radial { ref mut cx, ref mut cy, ref mut r, ref mut fx, ref mut fy } => {
- if let GradientVariant::Radial { cx: cxf, cy: cyf, r: rf, fx: fxf, fy: fyf } = *fallback {
- fallback_to! (*cx, cxf);
- fallback_to! (*cy, cyf);
- fallback_to! (*r, rf);
- fallback_to! (*fx, fxf);
- fallback_to! (*fy, fyf);
+ }
+
+ GradientVariant::Radial { ref mut cx,
+ ref mut cy,
+ ref mut r,
+ ref mut fx,
+ ref mut fy, } => {
+ if let GradientVariant::Radial { cx: cxf,
+ cy: cyf,
+ r: rf,
+ fx: fxf,
+ fy: fyf, } = *fallback
+ {
+ fallback_to!(*cx, cxf);
+ fallback_to!(*cy, cyf);
+ fallback_to!(*r, rf);
+ fallback_to!(*fx, fxf);
+ fallback_to!(*fy, fyf);
}
}
}
@@ -270,22 +273,23 @@ impl GradientVariant {
}
impl Gradient {
- fn is_resolved (&self) -> bool {
- self.common.is_resolved () && self.variant.is_resolved ()
+ fn is_resolved(&self) -> bool {
+ self.common.is_resolved() && self.variant.is_resolved()
}
- fn resolve_from_defaults (&mut self) {
- self.common.resolve_from_defaults ();
- self.variant.resolve_from_defaults ();
+ fn resolve_from_defaults(&mut self) {
+ self.common.resolve_from_defaults();
+ self.variant.resolve_from_defaults();
}
- fn resolve_from_fallback (&mut self, fallback: &Gradient) {
- self.common.resolve_from_fallback (&fallback.common);
- self.variant.resolve_from_fallback (&fallback.variant);
+ fn resolve_from_fallback(&mut self, fallback: &Gradient) {
+ self.common.resolve_from_fallback(&fallback.common);
+ self.variant.resolve_from_fallback(&fallback.variant);
}
- fn add_color_stops_from_node (&mut self, node: &RsvgNode) {
- assert! (node.get_type () == NodeType::LinearGradient || node.get_type () ==
NodeType::RadialGradient);
+ fn add_color_stops_from_node(&mut self, node: &RsvgNode) {
+ assert!(node.get_type() == NodeType::LinearGradient
+ || node.get_type() == NodeType::RadialGradient);
node.foreach_child(|child| {
if child.get_type () != NodeType::Stop {
@@ -304,47 +308,46 @@ impl Gradient {
});
}
- fn add_color_stop (&mut self, offset: f64, rgba: u32) {
- self.common.add_color_stop (offset, rgba);
+ fn add_color_stop(&mut self, offset: f64, rgba: u32) {
+ self.common.add_color_stop(offset, rgba);
}
- fn add_color_stops_to_pattern (&self,
- pattern: &mut cairo::Gradient,
- opacity: u8) {
- if let Some(stops) = self.common.stops.as_ref () {
+ fn add_color_stops_to_pattern(&self, pattern: &mut cairo::Gradient, opacity: u8) {
+ if let Some(stops) = self.common.stops.as_ref() {
for stop in stops {
let rgba = stop.rgba;
- pattern.add_color_stop_rgba (stop.offset,
- (f64::from((rgba >> 24) & 0xff)) / 255.0,
- (f64::from((rgba >> 16) & 0xff)) / 255.0,
- (f64::from((rgba >> 8) & 0xff)) / 255.0,
- f64::from((rgba & 0xff) * u32::from(opacity)) / 255.0 / 255.0);
+ pattern.add_color_stop_rgba(stop.offset,
+ (f64::from((rgba >> 24) & 0xff)) / 255.0,
+ (f64::from((rgba >> 16) & 0xff)) / 255.0,
+ (f64::from((rgba >> 8) & 0xff)) / 255.0,
+ f64::from((rgba & 0xff) * u32::from(opacity)) / 255.0
+ / 255.0);
}
}
}
}
trait FallbackSource {
- fn get_fallback (&mut self, name: &str) -> Option<RsvgNode>;
+ fn get_fallback(&mut self, name: &str) -> Option<RsvgNode>;
}
-fn resolve_gradient (gradient: &Gradient, fallback_source: &mut FallbackSource) -> Gradient {
- let mut result = gradient.clone ();
+fn resolve_gradient(gradient: &Gradient, fallback_source: &mut FallbackSource) -> Gradient {
+ let mut result = gradient.clone();
- while !result.is_resolved () {
+ while !result.is_resolved() {
let mut opt_fallback: Option<RsvgNode> = None;
- if let Some (ref fallback_name) = result.common.fallback {
- opt_fallback = fallback_source.get_fallback (&**fallback_name);
+ if let Some(ref fallback_name) = result.common.fallback {
+ opt_fallback = fallback_source.get_fallback(&**fallback_name);
}
- if let Some (fallback_node) = opt_fallback {
+ if let Some(fallback_node) = opt_fallback {
fallback_node.with_impl (|i: &NodeGradient| {
let fallback_gradient = i.get_gradient_with_color_stops_from_node (&fallback_node);
result.resolve_from_fallback (&fallback_gradient)
});
} else {
- result.resolve_from_defaults ();
+ result.resolve_from_defaults();
break;
}
}
@@ -354,96 +357,99 @@ fn resolve_gradient (gradient: &Gradient, fallback_source: &mut FallbackSource)
struct NodeFallbackSource {
draw_ctx: *mut RsvgDrawingCtx,
- acquired_nodes: Vec<*mut RsvgNode>
+ acquired_nodes: Vec<*mut RsvgNode>,
}
impl NodeFallbackSource {
- fn new (draw_ctx: *mut RsvgDrawingCtx) -> NodeFallbackSource {
- NodeFallbackSource {
- draw_ctx: draw_ctx,
- acquired_nodes: Vec::<*mut RsvgNode>::new ()
- }
+ fn new(draw_ctx: *mut RsvgDrawingCtx) -> NodeFallbackSource {
+ NodeFallbackSource { draw_ctx,
+ acquired_nodes: Vec::<*mut RsvgNode>::new(), }
}
}
impl Drop for NodeFallbackSource {
- fn drop (&mut self) {
- while let Some (node) = self.acquired_nodes.pop () {
- drawing_ctx::release_node (self.draw_ctx, node);
+ fn drop(&mut self) {
+ while let Some(node) = self.acquired_nodes.pop() {
+ drawing_ctx::release_node(self.draw_ctx, node);
}
}
}
impl FallbackSource for NodeFallbackSource {
- fn get_fallback (&mut self, name: &str) -> Option<RsvgNode> {
- let fallback_node = drawing_ctx::acquire_node (self.draw_ctx, name);
+ fn get_fallback(&mut self, name: &str) -> Option<RsvgNode> {
+ let fallback_node = drawing_ctx::acquire_node(self.draw_ctx, name);
- if fallback_node.is_null () {
+ if fallback_node.is_null() {
return None;
}
- let node: &RsvgNode = unsafe { & *fallback_node };
- if !(node.get_type () == NodeType::LinearGradient || node.get_type () == NodeType::RadialGradient) {
+ let node: &RsvgNode = unsafe { &*fallback_node };
+ if !(node.get_type() == NodeType::LinearGradient
+ || node.get_type() == NodeType::RadialGradient)
+ {
return None;
}
- self.acquired_nodes.push (fallback_node);
+ self.acquired_nodes.push(fallback_node);
- Some (node.clone ())
+ Some(node.clone())
}
}
-fn set_common_on_pattern<P: cairo::Pattern + cairo::Gradient> (gradient: &Gradient,
- draw_ctx: *mut RsvgDrawingCtx,
- pattern: &mut P,
- bbox: &RsvgBbox,
- opacity: u8)
-{
- let cr = drawing_ctx::get_cairo_context (draw_ctx);
+fn set_common_on_pattern<P: cairo::Pattern + cairo::Gradient>(gradient: &Gradient,
+ draw_ctx: *mut RsvgDrawingCtx,
+ pattern: &mut P,
+ bbox: &RsvgBbox,
+ opacity: u8) {
+ let cr = drawing_ctx::get_cairo_context(draw_ctx);
- let mut affine = gradient.common.affine.unwrap ();
+ let mut affine = gradient.common.affine.unwrap();
- let units = gradient.common.units.unwrap ();
+ let units = gradient.common.units.unwrap();
if units == GradientUnits(CoordUnits::ObjectBoundingBox) {
- let bbox_matrix = cairo::Matrix::new (bbox.rect.width, 0.0,
- 0.0, bbox.rect.height,
- bbox.rect.x, bbox.rect.y);
- affine = cairo::Matrix::multiply (&affine, &bbox_matrix);
+ let bbox_matrix = cairo::Matrix::new(bbox.rect.width,
+ 0.0,
+ 0.0,
+ bbox.rect.height,
+ bbox.rect.x,
+ bbox.rect.y);
+ affine = cairo::Matrix::multiply(&affine, &bbox_matrix);
}
- affine.invert ();
- pattern.set_matrix (affine);
- pattern.set_extend (gradient.common.spread.unwrap ().0);
+ affine.invert();
+ pattern.set_matrix(affine);
+ pattern.set_extend(gradient.common.spread.unwrap().0);
- gradient.add_color_stops_to_pattern (pattern, opacity);
+ gradient.add_color_stops_to_pattern(pattern, opacity);
- cr.set_source (pattern);
+ cr.set_source(pattern);
}
-fn set_linear_gradient_on_pattern (gradient: &Gradient,
- draw_ctx: *mut RsvgDrawingCtx,
- bbox: &RsvgBbox,
- opacity: u8) -> bool {
+fn set_linear_gradient_on_pattern(gradient: &Gradient,
+ draw_ctx: *mut RsvgDrawingCtx,
+ bbox: &RsvgBbox,
+ opacity: u8)
+ -> bool {
if let GradientVariant::Linear { x1, y1, x2, y2 } = gradient.variant {
- let units = gradient.common.units.unwrap ();
+ let units = gradient.common.units.unwrap();
if units == GradientUnits(CoordUnits::ObjectBoundingBox) {
- drawing_ctx::push_view_box (draw_ctx, 1.0, 1.0);
+ drawing_ctx::push_view_box(draw_ctx, 1.0, 1.0);
}
- let mut pattern = cairo::LinearGradient::new (x1.as_ref ().unwrap ().normalize (draw_ctx),
- y1.as_ref ().unwrap ().normalize (draw_ctx),
- x2.as_ref ().unwrap ().normalize (draw_ctx),
- y2.as_ref ().unwrap ().normalize (draw_ctx));
+ let mut pattern = cairo::LinearGradient::new(x1.as_ref().unwrap().normalize(draw_ctx),
+ y1.as_ref().unwrap().normalize(draw_ctx),
+ x2.as_ref().unwrap().normalize(draw_ctx),
+ y2.as_ref().unwrap().normalize(draw_ctx));
if units == GradientUnits(CoordUnits::ObjectBoundingBox) {
- drawing_ctx::pop_view_box (draw_ctx);
+ drawing_ctx::pop_view_box(draw_ctx);
}
- set_common_on_pattern (gradient, draw_ctx, &mut pattern, bbox, opacity);
+ set_common_on_pattern(gradient, draw_ctx, &mut pattern, bbox, opacity);
} else {
- unreachable! ();
+ unreachable!();
}
true
@@ -451,33 +457,29 @@ fn set_linear_gradient_on_pattern (gradient: &Gradient,
/* SVG defines radial gradients as being inside a circle (cx, cy, radius). The
* gradient projects out from a focus point (fx, fy), which is assumed to be
- * inside the circle, to the edge of the circle.
- *
- * The description of https://www.w3.org/TR/SVG/pservers.html#RadialGradientElement
- * states:
- *
- * If the point defined by ‘fx’ and ‘fy’ lies outside the circle defined by
- * ‘cx’, ‘cy’ and ‘r’, then the user agent shall set the focal point to the
- * intersection of the line from (‘cx’, ‘cy’) to (‘fx’, ‘fy’) with the circle
- * defined by ‘cx’, ‘cy’ and ‘r’.
- *
- * So, let's do that!
- */
-fn fix_focus_point (mut fx: f64,
- mut fy: f64,
- cx: f64,
- cy: f64,
- radius: f64) -> (f64, f64) {
+ * inside the circle, to the edge of the circle. */
+//
+// The description of https://www.w3.org/TR/SVG/pservers.html#RadialGradientElement
+// states:
+//
+// If the point defined by ‘fx’ and ‘fy’ lies outside the circle defined by
+// ‘cx’, ‘cy’ and ‘r’, then the user agent shall set the focal point to the
+// intersection of the line from (‘cx’, ‘cy’) to (‘fx’, ‘fy’) with the circle
+// defined by ‘cx’, ‘cy’ and ‘r’.
+//
+// So, let's do that!
+//
+fn fix_focus_point(mut fx: f64, mut fy: f64, cx: f64, cy: f64, radius: f64) -> (f64, f64) {
/* Easy case first: the focus point is inside the circle */
if (fx - cx) * (fx - cx) + (fy - cy) * (fy - cy) <= radius * radius {
return (fx, fy);
}
- /* Hard case: focus point is outside the circle.
- *
- * First, translate everything to the origin.
- */
+ /* Hard case: focus point is outside the circle. */
+ //
+ // First, translate everything to the origin.
+ //
fx -= cx;
fy -= cy;
@@ -489,9 +491,10 @@ fn fix_focus_point (mut fx: f64,
/* Find the vector's magnitude */
- let mag = (vx * vx + vy * vy).sqrt ();
+ let mag = (vx * vx + vy * vy).sqrt();
- /* Normalize the vector to have a magnitude equal to radius; (vx, vy) will now be on the edge of the
circle */
+ /* Normalize the vector to have a magnitude equal to radius; (vx, vy) will now be on the
+ * edge of the circle */
let scale = mag / radius;
@@ -503,88 +506,84 @@ fn fix_focus_point (mut fx: f64,
(vx + cx, vy + cy)
}
-fn set_radial_gradient_on_pattern (gradient: &Gradient,
- draw_ctx: *mut RsvgDrawingCtx,
- bbox: &RsvgBbox,
- opacity: u8) -> bool {
+fn set_radial_gradient_on_pattern(gradient: &Gradient,
+ draw_ctx: *mut RsvgDrawingCtx,
+ bbox: &RsvgBbox,
+ opacity: u8)
+ -> bool {
if let GradientVariant::Radial { cx, cy, r, fx, fy } = gradient.variant {
- let units = gradient.common.units.unwrap ();
+ let units = gradient.common.units.unwrap();
if units == GradientUnits(CoordUnits::ObjectBoundingBox) {
- drawing_ctx::push_view_box (draw_ctx, 1.0, 1.0);
+ drawing_ctx::push_view_box(draw_ctx, 1.0, 1.0);
}
- let n_cx = cx.as_ref ().unwrap ().normalize (draw_ctx);
- let n_cy = cy.as_ref ().unwrap ().normalize (draw_ctx);
- let n_r = r.as_ref ().unwrap ().normalize (draw_ctx);
- let n_fx = fx.as_ref ().unwrap ().normalize (draw_ctx);
- let n_fy = fy.as_ref ().unwrap ().normalize (draw_ctx);
+ let n_cx = cx.as_ref().unwrap().normalize(draw_ctx);
+ let n_cy = cy.as_ref().unwrap().normalize(draw_ctx);
+ let n_r = r.as_ref().unwrap().normalize(draw_ctx);
+ let n_fx = fx.as_ref().unwrap().normalize(draw_ctx);
+ let n_fy = fy.as_ref().unwrap().normalize(draw_ctx);
- let (new_fx, new_fy) = fix_focus_point (n_fx, n_fy, n_cx, n_cy, n_r);
+ let (new_fx, new_fy) = fix_focus_point(n_fx, n_fy, n_cx, n_cy, n_r);
- let mut pattern = cairo::RadialGradient::new (new_fx, new_fy, 0.0, n_cx, n_cy, n_r);
+ let mut pattern = cairo::RadialGradient::new(new_fx, new_fy, 0.0, n_cx, n_cy, n_r);
if units == GradientUnits(CoordUnits::ObjectBoundingBox) {
- drawing_ctx::pop_view_box (draw_ctx);
+ drawing_ctx::pop_view_box(draw_ctx);
}
- set_common_on_pattern (gradient, draw_ctx, &mut pattern, bbox, opacity);
+ set_common_on_pattern(gradient, draw_ctx, &mut pattern, bbox, opacity);
} else {
- unreachable! ();
+ unreachable!();
}
true
}
-fn set_pattern_on_draw_context (gradient: &Gradient,
- draw_ctx: *mut RsvgDrawingCtx,
- opacity: u8,
- bbox: &RsvgBbox) -> bool {
- assert! (gradient.is_resolved ());
+fn set_pattern_on_draw_context(gradient: &Gradient,
+ draw_ctx: *mut RsvgDrawingCtx,
+ opacity: u8,
+ bbox: &RsvgBbox)
+ -> bool {
+ assert!(gradient.is_resolved());
match gradient.variant {
GradientVariant::Linear { .. } => {
- set_linear_gradient_on_pattern (gradient, draw_ctx, bbox, opacity)
+ set_linear_gradient_on_pattern(gradient, draw_ctx, bbox, opacity)
}
GradientVariant::Radial { .. } => {
- set_radial_gradient_on_pattern (gradient, draw_ctx, bbox, opacity)
+ set_radial_gradient_on_pattern(gradient, draw_ctx, bbox, opacity)
}
}
}
struct NodeGradient {
- gradient: RefCell <Gradient>
+ gradient: RefCell<Gradient>,
}
impl NodeGradient {
- fn new_linear () -> NodeGradient {
- NodeGradient {
- gradient: RefCell::new (Gradient {
- common: GradientCommon::unresolved (),
- variant: GradientVariant::unresolved_linear(),
- })
- }
+ fn new_linear() -> NodeGradient {
+ NodeGradient { gradient: RefCell::new(Gradient { common: GradientCommon::unresolved(),
+ variant:
+ GradientVariant::unresolved_linear(), }), }
}
- fn new_radial () -> NodeGradient {
- NodeGradient {
- gradient: RefCell::new (Gradient {
- common: GradientCommon::unresolved (),
- variant: GradientVariant::unresolved_radial(),
- })
- }
+ fn new_radial() -> NodeGradient {
+ NodeGradient { gradient: RefCell::new(Gradient { common: GradientCommon::unresolved(),
+ variant:
+ GradientVariant::unresolved_radial(), }), }
}
- fn get_gradient_with_color_stops_from_node (&self, node: &RsvgNode) -> Gradient {
- let mut gradient = self.gradient.borrow ().clone ();
- gradient.add_color_stops_from_node (node);
+ fn get_gradient_with_color_stops_from_node(&self, node: &RsvgNode) -> Gradient {
+ let mut gradient = self.gradient.borrow().clone();
+ gradient.add_color_stops_from_node(node);
gradient
}
}
impl NodeTrait for NodeGradient {
- fn set_atts (&self, node: &RsvgNode, _: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
+ fn set_atts(&self, node: &RsvgNode, _: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
let mut g = self.gradient.borrow_mut();
let mut x1 = None;
@@ -594,29 +593,29 @@ impl NodeTrait for NodeGradient {
let mut cx = None;
let mut cy = None;
- let mut r = None;
+ let mut r = None;
let mut fx = None;
let mut fy = None;
for (_key, attr, value) in pbag.iter() {
match attr {
// Attributes common to linear and radial gradients
+ Attribute::GradientUnits => {
+ g.common.units = Some(parse("gradientUnits", value, (), None)?)
+ }
- Attribute::GradientUnits =>
- g.common.units = Some(parse("gradientUnits", value, (), None)?),
-
- Attribute::GradientTransform =>
- g.common.affine = Some(parse("gradientTransform", value, (), None)?),
+ Attribute::GradientTransform => {
+ g.common.affine = Some(parse("gradientTransform", value, (), None)?)
+ }
- Attribute::SpreadMethod =>
- g.common.spread = Some(parse("spreadMethod", value, (), None)?),
+ Attribute::SpreadMethod => {
+ g.common.spread = Some(parse("spreadMethod", value, (), None)?)
+ }
- Attribute::XlinkHref =>
- g.common.fallback = Some(value.to_owned()),
+ Attribute::XlinkHref => g.common.fallback = Some(value.to_owned()),
// Attributes specific to each gradient type. The defaults mandated by the spec
// are in GradientVariant::resolve_from_defaults()
-
Attribute::X1 => x1 = Some(parse("x1", value, LengthDir::Horizontal, None)?),
Attribute::Y1 => y1 = Some(parse("y1", value, LengthDir::Vertical, None)?),
Attribute::X2 => x2 = Some(parse("x2", value, LengthDir::Horizontal, None)?),
@@ -624,7 +623,7 @@ impl NodeTrait for NodeGradient {
Attribute::Cx => cx = Some(parse("cx", value, LengthDir::Horizontal, None)?),
Attribute::Cy => cy = Some(parse("cy", value, LengthDir::Vertical, None)?),
- Attribute::R => r = Some(parse("r", value, LengthDir::Both, None)?),
+ Attribute::R => r = Some(parse("r", value, LengthDir::Both, None)?),
Attribute::Fx => fx = Some(parse("fx", value, LengthDir::Horizontal, None)?),
Attribute::Fy => fy = Some(parse("fy", value, LengthDir::Vertical, None)?),
@@ -632,82 +631,79 @@ impl NodeTrait for NodeGradient {
}
}
- match node.get_type () {
+ match node.get_type() {
NodeType::LinearGradient => {
- g.variant = GradientVariant::Linear {
- x1: x1,
- y1: y1,
- x2: x2,
- y2: y2,
- };
- },
+ g.variant = GradientVariant::Linear { x1, y1, x2, y2 };
+ }
NodeType::RadialGradient => {
- g.variant = GradientVariant::Radial {
- cx: cx,
- cy: cy,
- r: r,
- fx: fx,
- fy: fy,
- };
- },
-
- _ => unreachable! ()
+ g.variant = GradientVariant::Radial { cx, cy, r, fx, fy };
+ }
+
+ _ => unreachable!(),
}
- Ok (())
+ Ok(())
}
- fn draw (&self, _: &RsvgNode, _: *const RsvgDrawingCtx, _: i32) {
+ fn draw(&self, _: &RsvgNode, _: *const RsvgDrawingCtx, _: i32) {
// nothing; paint servers are handled specially
}
- fn get_c_impl (&self) -> *const RsvgCNodeImpl {
- unreachable! ();
+ fn get_c_impl(&self) -> *const RsvgCNodeImpl {
+ unreachable!();
}
}
#[no_mangle]
-pub extern fn rsvg_node_linear_gradient_new (_: *const libc::c_char, raw_parent: *const RsvgNode) -> *const
RsvgNode {
- boxed_node_new (NodeType::LinearGradient,
- raw_parent,
- Box::new (NodeGradient::new_linear ()))
+pub extern "C" fn rsvg_node_linear_gradient_new(_: *const libc::c_char,
+ raw_parent: *const RsvgNode)
+ -> *const RsvgNode {
+ boxed_node_new(NodeType::LinearGradient,
+ raw_parent,
+ Box::new(NodeGradient::new_linear()))
}
#[no_mangle]
-pub extern fn rsvg_node_radial_gradient_new (_: *const libc::c_char, raw_parent: *const RsvgNode) -> *const
RsvgNode {
- boxed_node_new (NodeType::RadialGradient,
- raw_parent,
- Box::new (NodeGradient::new_radial ()))
+pub extern "C" fn rsvg_node_radial_gradient_new(_: *const libc::c_char,
+ raw_parent: *const RsvgNode)
+ -> *const RsvgNode {
+ boxed_node_new(NodeType::RadialGradient,
+ raw_parent,
+ Box::new(NodeGradient::new_radial()))
}
-fn resolve_fallbacks_and_set_pattern (gradient: &Gradient,
- draw_ctx: *mut RsvgDrawingCtx,
- opacity: u8,
- bbox: &RsvgBbox) -> bool {
- let mut fallback_source = NodeFallbackSource::new (draw_ctx);
+fn resolve_fallbacks_and_set_pattern(gradient: &Gradient,
+ draw_ctx: *mut RsvgDrawingCtx,
+ opacity: u8,
+ bbox: &RsvgBbox)
+ -> bool {
+ let mut fallback_source = NodeFallbackSource::new(draw_ctx);
if bbox.is_empty() {
- return true
+ return true;
}
- let resolved = resolve_gradient (gradient, &mut fallback_source);
+ let resolved = resolve_gradient(gradient, &mut fallback_source);
- set_pattern_on_draw_context (&resolved, draw_ctx, opacity, &bbox)
+ set_pattern_on_draw_context(&resolved, draw_ctx, opacity, &bbox)
}
-pub fn gradient_resolve_fallbacks_and_set_pattern (node: &RsvgNode,
- draw_ctx: *mut RsvgDrawingCtx,
- opacity: u8,
- bbox: &RsvgBbox) -> bool {
- assert! (node.get_type () == NodeType::LinearGradient || node.get_type () == NodeType::RadialGradient);
+pub fn gradient_resolve_fallbacks_and_set_pattern(node: &RsvgNode,
+ draw_ctx: *mut RsvgDrawingCtx,
+ opacity: u8,
+ bbox: &RsvgBbox)
+ -> bool {
+ assert!(node.get_type() == NodeType::LinearGradient
+ || node.get_type() == NodeType::RadialGradient);
let mut did_set_gradient = false;
- node.with_impl (|node_gradient: &NodeGradient| {
- let gradient = node_gradient.get_gradient_with_color_stops_from_node (node);
- did_set_gradient = resolve_fallbacks_and_set_pattern (&gradient, draw_ctx, opacity, &bbox);
- });
+ node.with_impl(|node_gradient: &NodeGradient| {
+ let gradient = node_gradient.get_gradient_with_color_stops_from_node(node);
+ did_set_gradient =
+ resolve_fallbacks_and_set_pattern(&gradient, draw_ctx, opacity, &bbox);
+ });
did_set_gradient
}
diff --git a/rsvg_internals/src/image.rs b/rsvg_internals/src/image.rs
index e5f92d32..8ab643c6 100644
--- a/rsvg_internals/src/image.rs
+++ b/rsvg_internals/src/image.rs
@@ -1,9 +1,9 @@
-use libc;
use cairo;
use cairo_sys;
use glib;
use glib::translate::*;
use glib_sys;
+use libc;
use std::cell::{Cell, RefCell};
use std::ptr;
@@ -19,71 +19,80 @@ use parsers::parse;
use property_bag::PropertyBag;
struct NodeImage {
- aspect: Cell<AspectRatio>,
- x: Cell<RsvgLength>,
- y: Cell<RsvgLength>,
- w: Cell<RsvgLength>,
- h: Cell<RsvgLength>,
- surface: RefCell<Option<cairo::ImageSurface>>
+ aspect: Cell<AspectRatio>,
+ x: Cell<RsvgLength>,
+ y: Cell<RsvgLength>,
+ w: Cell<RsvgLength>,
+ h: Cell<RsvgLength>,
+ surface: RefCell<Option<cairo::ImageSurface>>,
}
impl NodeImage {
- fn new () -> NodeImage {
- NodeImage {
- aspect: Cell::new (AspectRatio::default ()),
- x: Cell::new (RsvgLength::default ()),
- y: Cell::new (RsvgLength::default ()),
- w: Cell::new (RsvgLength::default ()),
- h: Cell::new (RsvgLength::default ()),
- surface: RefCell::new (None)
- }
+ fn new() -> NodeImage {
+ NodeImage { aspect: Cell::new(AspectRatio::default()),
+ x: Cell::new(RsvgLength::default()),
+ y: Cell::new(RsvgLength::default()),
+ w: Cell::new(RsvgLength::default()),
+ h: Cell::new(RsvgLength::default()),
+ surface: RefCell::new(None), }
}
}
impl NodeTrait for NodeImage {
- fn set_atts (&self, _: &RsvgNode, handle: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
+ fn set_atts(&self, _: &RsvgNode, handle: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
for (_key, attr, value) in pbag.iter() {
match attr {
- Attribute::X => self.x.set(parse("x", value, LengthDir::Horizontal, None)?),
- Attribute::Y => self.y.set(parse("y", value, LengthDir::Vertical, None)?),
- Attribute::Width => self.w.set(parse("width", value, LengthDir::Horizontal,
- Some(RsvgLength::check_nonnegative))?),
- Attribute::Height => self.h.set(parse("height", value, LengthDir::Vertical,
- Some(RsvgLength::check_nonnegative))?),
-
- Attribute::PreserveAspectRatio =>
- self.aspect.set(parse("preserveAspectRatio", value, (), None)?),
-
- Attribute::XlinkHref |
- Attribute::Path => {
+ Attribute::X => self.x.set(parse("x", value, LengthDir::Horizontal, None)?),
+ Attribute::Y => self.y.set(parse("y", value, LengthDir::Vertical, None)?),
+ Attribute::Width => {
+ self.w.set(parse("width",
+ value,
+ LengthDir::Horizontal,
+ Some(RsvgLength::check_nonnegative))?)
+ }
+ Attribute::Height => {
+ self.h.set(parse("height",
+ value,
+ LengthDir::Vertical,
+ Some(RsvgLength::check_nonnegative))?)
+ }
+
+ Attribute::PreserveAspectRatio => {
+ self.aspect.set(parse("preserveAspectRatio", value, (), None)?)
+ }
+
+ Attribute::XlinkHref | Attribute::Path => {
// "path" is used by some older Adobe Illustrator versions
- extern "C" { fn rsvg_cairo_surface_new_from_href
- (handle: *const RsvgHandle,
- href: *const libc::c_char,
- error: *mut *mut glib_sys::GError) -> *mut cairo_sys::cairo_surface_t;
+ extern "C" {
+ fn rsvg_cairo_surface_new_from_href(handle: *const RsvgHandle,
+ href: *const libc::c_char,
+ error: *mut *mut glib_sys::GError)
+ -> *mut cairo_sys::cairo_surface_t;
}
let mut error = ptr::null_mut();
- let raw_surface = unsafe { rsvg_cairo_surface_new_from_href (handle,
- value.to_glib_none().0,
- &mut error) };
+ let raw_surface = unsafe {
+ rsvg_cairo_surface_new_from_href(handle, value.to_glib_none().0, &mut error)
+ };
if !raw_surface.is_null() {
- *self.surface.borrow_mut() = Some(unsafe { cairo::ImageSurface::from_raw_full
(raw_surface).unwrap() });
+ *self.surface.borrow_mut() = Some(unsafe {
+ cairo::ImageSurface::from_raw_full
(raw_surface).unwrap()
+ });
} else {
let _: glib::Error = unsafe { from_glib_full(error) }; // FIXME: we should note that
the image couldn't be loaded
}
- },
+ }
_ => (),
}
}
- Ok (())
+ Ok(())
}
- fn draw (&self, node: &RsvgNode, draw_ctx: *const RsvgDrawingCtx, dominate: i32) {
+ fn draw(&self, node: &RsvgNode, draw_ctx: *const RsvgDrawingCtx, dominate: i32) {
if let Some(ref surface) = *self.surface.borrow() {
let x = self.x.get().normalize(draw_ctx);
let y = self.y.get().normalize(draw_ctx);
@@ -98,14 +107,19 @@ impl NodeTrait for NodeImage {
let aspect = self.aspect.get();
if !drawing_ctx::state_is_overflow(state) {
- if let Align::Aligned {fit: FitMode::Slice, ..} = aspect.align {
+ if let Align::Aligned { fit: FitMode::Slice,
+ .. } = aspect.align
+ {
drawing_ctx::add_clipping_rect(draw_ctx, x, y, w, h);
}
}
- let (x, y, w, h) = aspect.compute (f64::from(surface.get_width()),
- f64::from(surface.get_height()),
- x, y, w, h);
+ let (x, y, w, h) = aspect.compute(f64::from(surface.get_width()),
+ f64::from(surface.get_height()),
+ x,
+ y,
+ w,
+ h);
drawing_ctx::render_surface(draw_ctx, surface, x, y, w, h);
@@ -113,14 +127,14 @@ impl NodeTrait for NodeImage {
}
}
- fn get_c_impl (&self) -> *const RsvgCNodeImpl {
- unreachable! ();
+ fn get_c_impl(&self) -> *const RsvgCNodeImpl {
+ unreachable!();
}
}
#[no_mangle]
-pub extern fn rsvg_node_image_new (_: *const libc::c_char, raw_parent: *const RsvgNode) -> *const RsvgNode {
- boxed_node_new (NodeType::Image,
- raw_parent,
- Box::new (NodeImage::new ()))
+pub extern "C" fn rsvg_node_image_new(_: *const libc::c_char,
+ raw_parent: *const RsvgNode)
+ -> *const RsvgNode {
+ boxed_node_new(NodeType::Image, raw_parent, Box::new(NodeImage::new()))
}
diff --git a/rsvg_internals/src/length.rs b/rsvg_internals/src/length.rs
index c22f76f2..d64c55e6 100644
--- a/rsvg_internals/src/length.rs
+++ b/rsvg_internals/src/length.rs
@@ -1,6 +1,6 @@
use cssparser::{Parser, ParserInput, Token};
-use glib_sys;
use glib::translate::*;
+use glib_sys;
use libc;
use regex::Regex;
@@ -10,9 +10,9 @@ use std::ptr;
use drawing_ctx;
use drawing_ctx::RsvgDrawingCtx;
+use error::*;
use parsers::Parse;
use parsers::ParseError;
-use error::*;
use util::utf8_cstr;
/* Keep this in sync with ../../rsvg-private.h:LengthUnit */
@@ -25,7 +25,7 @@ pub enum LengthUnit {
FontEx,
Inch,
RelativeLarger,
- RelativeSmaller
+ RelativeSmaller,
}
/* Keep this in sync with ../../rsvg-private.h:LengthDir */
@@ -34,7 +34,7 @@ pub enum LengthUnit {
pub enum LengthDir {
Horizontal,
Vertical,
- Both
+ Both,
}
/* This is *not* an opaque struct; it is actually visible to the C code. It is so
@@ -47,76 +47,91 @@ pub enum LengthDir {
pub struct RsvgLength {
pub length: f64,
pub unit: LengthUnit,
- dir: LengthDir
+ dir: LengthDir,
}
impl Default for RsvgLength {
- fn default () -> RsvgLength {
- RsvgLength {
- length: 0.0,
- unit: LengthUnit::Default,
- dir: LengthDir::Both
- }
+ fn default() -> RsvgLength {
+ RsvgLength { length: 0.0,
+ unit: LengthUnit::Default,
+ dir: LengthDir::Both, }
}
}
const POINTS_PER_INCH: f64 = 72.0;
-const CM_PER_INCH: f64 = 2.54;
-const MM_PER_INCH: f64 = 25.4;
-const PICA_PER_INCH: f64 = 6.0;
+const CM_PER_INCH: f64 = 2.54;
+const MM_PER_INCH: f64 = 25.4;
+const PICA_PER_INCH: f64 = 6.0;
-fn compute_named_size (name: &str) -> f64 {
+fn compute_named_size(name: &str) -> f64 {
let power: f64;
match name {
- "xx-small" => { power = -3.0; },
- "x-small" => { power = -2.0; },
- "small" => { power = -1.0; },
- "medium" => { power = 0.0; },
- "large" => { power = 1.0; },
- "x-large" => { power = 2.0; },
- "xx-large" => { power = 3.0; },
- _ => { unreachable! (); }
+ "xx-small" => {
+ power = -3.0;
+ }
+ "x-small" => {
+ power = -2.0;
+ }
+ "small" => {
+ power = -1.0;
+ }
+ "medium" => {
+ power = 0.0;
+ }
+ "large" => {
+ power = 1.0;
+ }
+ "x-large" => {
+ power = 2.0;
+ }
+ "xx-large" => {
+ power = 3.0;
+ }
+ _ => {
+ unreachable!();
+ }
}
- 12.0 * 1.2f64.powf (power) / POINTS_PER_INCH
+ 12.0 * 1.2f64.powf(power) / POINTS_PER_INCH
}
#[no_mangle]
-pub extern fn rsvg_length_parse (string: *const libc::c_char, dir: LengthDir) -> RsvgLength {
+pub extern "C" fn rsvg_length_parse(string: *const libc::c_char, dir: LengthDir) -> RsvgLength {
let my_string = unsafe { utf8_cstr(string) };
// FIXME: this ignores errors; propagate them upstream
- RsvgLength::parse (my_string, dir).unwrap_or_else(|_| {RsvgLength::default ()})
+ RsvgLength::parse(my_string, dir).unwrap_or_else(|_| RsvgLength::default())
}
/* https://www.w3.org/TR/SVG/types.html#DataTypeLength
- * https://www.w3.org/TR/2008/REC-CSS2-20080411/syndata.html#length-units
- *
- * Lengths have units. When they need to be need resolved to
- * units in the user's coordinate system, some unit types
- * need to know if they are horizontal/vertical/both. For example,
- * a some_object.width="50%" is 50% with respect to the current
- * viewport's width. In this case, the @dir argument is used
- * inside RsvgLength::normalize(), when it needs to know to what the
- * length refers.
- */
-
-fn make_err () -> AttributeError {
- AttributeError::Parse (ParseError::new ("expected length: number(\"em\" | \"ex\" | \"px\" | \"in\" |
\"cm\" | \"mm\" | \"pt\" | \"pc\" | \"%\")?"))
+ * https://www.w3.org/TR/2008/REC-CSS2-20080411/syndata.html#length-units */
+//
+// Lengths have units. When they need to be need resolved to
+// units in the user's coordinate system, some unit types
+// need to know if they are horizontal/vertical/both. For example,
+// a some_object.width="50%" is 50% with respect to the current
+// viewport's width. In this case, the @dir argument is used
+// inside RsvgLength::normalize(), when it needs to know to what the
+// length refers.
+//
+
+fn make_err() -> AttributeError {
+ AttributeError::Parse(ParseError::new("expected length: number(\"em\" | \"ex\" | \"px\" | \
+ \"in\" | \"cm\" | \"mm\" | \"pt\" | \"pc\" | \"%\")?"))
}
impl Parse for RsvgLength {
type Data = LengthDir;
type Err = AttributeError;
- fn parse (string: &str, dir: LengthDir) -> Result <RsvgLength, AttributeError> {
- let mut input = ParserInput::new (string);
- let mut parser = Parser::new (&mut input);
+ fn parse(string: &str, dir: LengthDir) -> Result<RsvgLength, AttributeError> {
+ let mut input = ParserInput::new(string);
+ let mut parser = Parser::new(&mut input);
let length = RsvgLength::from_cssparser(&mut parser, dir)?;
- parser.expect_exhausted ().map_err (|_| make_err ())?;
+ parser.expect_exhausted().map_err(|_| make_err())?;
Ok(length)
}
@@ -124,175 +139,191 @@ impl Parse for RsvgLength {
impl RsvgLength {
pub fn new(l: f64, unit: LengthUnit, dir: LengthDir) -> RsvgLength {
- RsvgLength {
- length: l,
- unit: unit,
- dir: dir
- }
+ RsvgLength { length: l,
+ unit,
+ dir, }
}
- pub fn check_nonnegative (self) -> Result <RsvgLength, AttributeError> {
+ pub fn check_nonnegative(self) -> Result<RsvgLength, AttributeError> {
if self.length >= 0.0 {
- Ok (self)
+ Ok(self)
} else {
- Err (AttributeError::Value ("value must be non-negative".to_string ()))
+ Err(AttributeError::Value("value must be non-negative".to_string()))
}
}
- pub fn normalize (&self, draw_ctx: *const RsvgDrawingCtx) -> f64 {
+ pub fn normalize(&self, draw_ctx: *const RsvgDrawingCtx) -> f64 {
match self.unit {
- LengthUnit::Default => {
- self.length
- },
+ LengthUnit::Default => self.length,
LengthUnit::Percent => {
- let (width, height) = drawing_ctx::get_view_box_size (draw_ctx);
+ let (width, height) = drawing_ctx::get_view_box_size(draw_ctx);
match self.dir {
- LengthDir::Horizontal => { self.length * width },
- LengthDir::Vertical => { self.length * height },
- LengthDir::Both => { self.length * viewport_percentage (width, height) }
+ LengthDir::Horizontal => self.length * width,
+ LengthDir::Vertical => self.length * height,
+ LengthDir::Both => self.length * viewport_percentage(width, height),
}
- },
+ }
- LengthUnit::FontEm => {
- self.length * drawing_ctx::get_normalized_font_size (draw_ctx)
- },
+ LengthUnit::FontEm => self.length * drawing_ctx::get_normalized_font_size(draw_ctx),
LengthUnit::FontEx => {
- self.length * drawing_ctx::get_normalized_font_size (draw_ctx) / 2.0
- },
+ self.length * drawing_ctx::get_normalized_font_size(draw_ctx) / 2.0
+ }
LengthUnit::Inch => {
- let (dpi_x, dpi_y) = drawing_ctx::get_dpi (draw_ctx);
+ let (dpi_x, dpi_y) = drawing_ctx::get_dpi(draw_ctx);
match self.dir {
- LengthDir::Horizontal => { self.length * dpi_x },
- LengthDir::Vertical => { self.length * dpi_y },
- LengthDir::Both => { self.length * viewport_percentage (dpi_x, dpi_y) }
+ LengthDir::Horizontal => self.length * dpi_x,
+ LengthDir::Vertical => self.length * dpi_y,
+ LengthDir::Both => self.length * viewport_percentage(dpi_x, dpi_y),
}
- },
+ }
- LengthUnit::RelativeLarger |
- LengthUnit::RelativeSmaller => {
- drawing_ctx::get_normalized_font_size (draw_ctx)
- },
+ LengthUnit::RelativeLarger | LengthUnit::RelativeSmaller => {
+ drawing_ctx::get_normalized_font_size(draw_ctx)
+ }
}
}
- pub fn hand_normalize (&self,
- pixels_per_inch: f64,
- width_or_height: f64,
- font_size: f64) -> f64 {
+ pub fn hand_normalize(&self,
+ pixels_per_inch: f64,
+ width_or_height: f64,
+ font_size: f64)
+ -> f64 {
match self.unit {
- LengthUnit::Default => { self.length },
+ LengthUnit::Default => self.length,
- LengthUnit::Percent => { self.length * width_or_height },
+ LengthUnit::Percent => self.length * width_or_height,
- LengthUnit::FontEm => { self.length * font_size },
+ LengthUnit::FontEm => self.length * font_size,
- LengthUnit::FontEx => { self.length * font_size / 2.0 },
+ LengthUnit::FontEx => self.length * font_size / 2.0,
- LengthUnit::Inch => { self.length * pixels_per_inch },
+ LengthUnit::Inch => self.length * pixels_per_inch,
- _ => { 0.0 }
+ _ => 0.0,
}
}
- fn from_cssparser(parser: &mut Parser, dir: LengthDir) -> Result <RsvgLength, AttributeError> {
-
+ fn from_cssparser(parser: &mut Parser, dir: LengthDir) -> Result<RsvgLength, AttributeError> {
let length = {
let token = parser.next ()
.map_err (|_| AttributeError::Parse (ParseError::new ("expected number and optional symbol,
or number and percentage")))?;
match *token {
- Token::Number { value, .. } => RsvgLength { length: f64::from(value),
- unit: LengthUnit::Default,
- dir: dir },
+ Token::Number { value, .. } => {
+ RsvgLength { length: f64::from(value),
+ unit: LengthUnit::Default,
+ dir, }
+ }
- Token::Percentage { unit_value, .. } => RsvgLength { length: f64::from(unit_value),
- unit: LengthUnit::Percent,
- dir: dir },
+ Token::Percentage { unit_value, .. } => {
+ RsvgLength { length: f64::from(unit_value),
+ unit: LengthUnit::Percent,
+ dir, }
+ }
Token::Dimension { value, ref unit, .. } => {
let value = f64::from(value);
- match unit.as_ref () {
- "em" => RsvgLength { length: value,
- unit: LengthUnit::FontEm,
- dir: dir },
-
- "ex" => RsvgLength { length: value,
- unit: LengthUnit::FontEx,
- dir: dir },
-
- "pt" => RsvgLength { length: value / POINTS_PER_INCH,
- unit: LengthUnit::Inch,
- dir: dir },
-
- "in" => RsvgLength { length: value,
- unit: LengthUnit::Inch,
- dir: dir },
-
- "cm" => RsvgLength { length: value / CM_PER_INCH,
- unit: LengthUnit::Inch,
- dir: dir },
-
- "mm" => RsvgLength { length: value / MM_PER_INCH,
- unit: LengthUnit::Inch,
- dir: dir },
-
- "pc" => RsvgLength { length: value / PICA_PER_INCH,
- unit: LengthUnit::Inch,
- dir: dir },
-
- "px" => RsvgLength { length: value,
- unit: LengthUnit::Default,
- dir: dir },
-
- _ => return Err (make_err ())
+ match unit.as_ref() {
+ "em" => {
+ RsvgLength { length: value,
+ unit: LengthUnit::FontEm,
+ dir, }
+ }
+
+ "ex" => {
+ RsvgLength { length: value,
+ unit: LengthUnit::FontEx,
+ dir, }
+ }
+
+ "pt" => {
+ RsvgLength { length: value / POINTS_PER_INCH,
+ unit: LengthUnit::Inch,
+ dir, }
+ }
+
+ "in" => {
+ RsvgLength { length: value,
+ unit: LengthUnit::Inch,
+ dir, }
+ }
+
+ "cm" => {
+ RsvgLength { length: value / CM_PER_INCH,
+ unit: LengthUnit::Inch,
+ dir, }
+ }
+
+ "mm" => {
+ RsvgLength { length: value / MM_PER_INCH,
+ unit: LengthUnit::Inch,
+ dir, }
+ }
+
+ "pc" => {
+ RsvgLength { length: value / PICA_PER_INCH,
+ unit: LengthUnit::Inch,
+ dir, }
+ }
+
+ "px" => {
+ RsvgLength { length: value,
+ unit: LengthUnit::Default,
+ dir, }
+ }
+
+ _ => return Err(make_err()),
}
- },
+ }
// FIXME: why are the following in Length? They should be in FontSize
- Token::Ident (ref cow) => match cow.as_ref () {
- "larger" => RsvgLength { length: 0.0,
- unit: LengthUnit::RelativeLarger,
- dir: dir },
-
- "smaller" => RsvgLength { length: 0.0,
- unit: LengthUnit::RelativeSmaller,
- dir: dir },
-
- "xx-small" |
- "x-small" |
- "small" |
- "medium" |
- "large" |
- "x-large" |
- "xx-large" => RsvgLength { length: compute_named_size (cow),
- unit: LengthUnit::Inch,
- dir: dir },
-
- _ => return Err (make_err ())
- },
-
- _ => return Err (make_err ())
+ Token::Ident(ref cow) => {
+ match cow.as_ref() {
+ "larger" => {
+ RsvgLength { length: 0.0,
+ unit: LengthUnit::RelativeLarger,
+ dir, }
+ }
+
+ "smaller" => {
+ RsvgLength { length: 0.0,
+ unit: LengthUnit::RelativeSmaller,
+ dir, }
+ }
+
+ "xx-small" | "x-small" | "small" | "medium" | "large" | "x-large"
+ | "xx-large" => {
+ RsvgLength { length: compute_named_size(cow),
+ unit: LengthUnit::Inch,
+ dir, }
+ }
+
+ _ => return Err(make_err()),
+ }
+ }
+
+ _ => return Err(make_err()),
}
};
- Ok (length)
+ Ok(length)
}
}
-fn viewport_percentage (x: f64, y: f64) -> f64 {
- /* https://www.w3.org/TR/SVG/coords.html#Units
- *
- * "For any other length value expressed as a percentage of the viewport, the
- * percentage is calculated as the specified percentage of
- * sqrt((actual-width)**2 + (actual-height)**2))/sqrt(2)."
- */
- (x * x + y * y).sqrt () / SQRT_2
+fn viewport_percentage(x: f64, y: f64) -> f64 {
+ /* https://www.w3.org/TR/SVG/coords.html#Units */
+ //
+ // "For any other length value expressed as a percentage of the viewport, the
+ // percentage is calculated as the specified percentage of
+ // sqrt((actual-width)**2 + (actual-height)**2))/sqrt(2)."
+ //
+ (x * x + y * y).sqrt() / SQRT_2
}
// Keep in sync with rsvg-styles.h:RsvgStrokeDasharrayKind
@@ -301,7 +332,7 @@ pub enum RsvgStrokeDasharrayKind {
None,
Inherit,
Dashes,
- Error
+ Error,
}
// Keep in sync with rsvg-styles.h:RsvgStrokeDasharray
@@ -309,7 +340,7 @@ pub enum RsvgStrokeDasharrayKind {
pub struct RsvgStrokeDasharray {
pub kind: RsvgStrokeDasharrayKind,
pub num_dashes: usize,
- pub dashes: *mut RsvgLength
+ pub dashes: *mut RsvgLength,
}
#[derive(Debug, PartialEq)]
@@ -367,53 +398,56 @@ fn parse_dash_array(s: &str) -> Result<Vec<RsvgLength>, AttributeError> {
}
#[no_mangle]
-pub extern fn rsvg_length_normalize (raw_length: *const RsvgLength, draw_ctx: *const RsvgDrawingCtx) -> f64 {
- assert! (!raw_length.is_null ());
+pub extern "C" fn rsvg_length_normalize(raw_length: *const RsvgLength,
+ draw_ctx: *const RsvgDrawingCtx)
+ -> f64 {
+ assert!(!raw_length.is_null());
let length: &RsvgLength = unsafe { &*raw_length };
- length.normalize (draw_ctx)
+ length.normalize(draw_ctx)
}
#[no_mangle]
-pub extern fn rsvg_length_hand_normalize (raw_length: *const RsvgLength,
- pixels_per_inch: f64,
- width_or_height: f64,
- font_size: f64) -> f64 {
- assert! (!raw_length.is_null ());
+pub extern "C" fn rsvg_length_hand_normalize(raw_length: *const RsvgLength,
+ pixels_per_inch: f64,
+ width_or_height: f64,
+ font_size: f64)
+ -> f64 {
+ assert!(!raw_length.is_null());
let length: &RsvgLength = unsafe { &*raw_length };
- length.hand_normalize (pixels_per_inch, width_or_height, font_size)
+ length.hand_normalize(pixels_per_inch, width_or_height, font_size)
}
#[no_mangle]
-pub extern fn rsvg_parse_stroke_dasharray(string: *const libc::c_char) -> RsvgStrokeDasharray {
- let my_string = unsafe { &String::from_glib_none (string) };
+pub extern "C" fn rsvg_parse_stroke_dasharray(string: *const libc::c_char) -> RsvgStrokeDasharray {
+ let my_string = unsafe { &String::from_glib_none(string) };
match parse_stroke_dash_array(my_string) {
- Ok(StrokeDasharray::None) => RsvgStrokeDasharray {
- kind: RsvgStrokeDasharrayKind::None,
- num_dashes: 0,
- dashes: ptr::null_mut()
- },
-
- Ok(StrokeDasharray::Inherit) => RsvgStrokeDasharray {
- kind: RsvgStrokeDasharrayKind::Inherit,
- num_dashes: 0,
- dashes: ptr::null_mut()
- },
-
- Ok(StrokeDasharray::Dasharray(ref v)) => RsvgStrokeDasharray {
- kind: RsvgStrokeDasharrayKind::Dashes,
- num_dashes: v.len(),
- dashes: to_c_array(v)
- },
-
- Err(_) => RsvgStrokeDasharray {
- kind: RsvgStrokeDasharrayKind::Error,
- num_dashes: 0,
- dashes: ptr::null_mut()
+ Ok(StrokeDasharray::None) => {
+ RsvgStrokeDasharray { kind: RsvgStrokeDasharrayKind::None,
+ num_dashes: 0,
+ dashes: ptr::null_mut(), }
+ }
+
+ Ok(StrokeDasharray::Inherit) => {
+ RsvgStrokeDasharray { kind: RsvgStrokeDasharrayKind::Inherit,
+ num_dashes: 0,
+ dashes: ptr::null_mut(), }
+ }
+
+ Ok(StrokeDasharray::Dasharray(ref v)) => {
+ RsvgStrokeDasharray { kind: RsvgStrokeDasharrayKind::Dashes,
+ num_dashes: v.len(),
+ dashes: to_c_array(v), }
+ }
+
+ Err(_) => {
+ RsvgStrokeDasharray { kind: RsvgStrokeDasharrayKind::Error,
+ num_dashes: 0,
+ dashes: ptr::null_mut(), }
}
}
}
@@ -431,71 +465,79 @@ mod tests {
use super::*;
#[test]
- fn parses_default () {
- assert_eq! (RsvgLength::parse ("42", LengthDir::Horizontal),
- Ok (RsvgLength::new(42.0, LengthUnit::Default, LengthDir::Horizontal)));
-
- assert_eq! (RsvgLength::parse ("-42px", LengthDir::Horizontal),
- Ok (RsvgLength::new(-42.0, LengthUnit::Default, LengthDir::Horizontal)));
+ fn parses_default() {
+ assert_eq!(RsvgLength::parse("42", LengthDir::Horizontal),
+ Ok(RsvgLength::new(42.0,
+ LengthUnit::Default,
+ LengthDir::Horizontal)));
+
+ assert_eq!(RsvgLength::parse("-42px", LengthDir::Horizontal),
+ Ok(RsvgLength::new(-42.0,
+ LengthUnit::Default,
+ LengthDir::Horizontal)));
}
#[test]
- fn parses_percent () {
- assert_eq! (RsvgLength::parse ("50.0%", LengthDir::Horizontal),
- Ok (RsvgLength::new(0.5, LengthUnit::Percent, LengthDir::Horizontal)));
+ fn parses_percent() {
+ assert_eq!(RsvgLength::parse("50.0%", LengthDir::Horizontal),
+ Ok(RsvgLength::new(0.5,
+ LengthUnit::Percent,
+ LengthDir::Horizontal)));
}
#[test]
- fn parses_font_em () {
- assert_eq! (RsvgLength::parse ("22.5em", LengthDir::Vertical),
- Ok (RsvgLength::new(22.5, LengthUnit::FontEm, LengthDir::Vertical)));
+ fn parses_font_em() {
+ assert_eq!(RsvgLength::parse("22.5em", LengthDir::Vertical),
+ Ok(RsvgLength::new(22.5,
+ LengthUnit::FontEm,
+ LengthDir::Vertical)));
}
#[test]
- fn parses_font_ex () {
- assert_eq! (RsvgLength::parse ("22.5ex", LengthDir::Vertical),
- Ok (RsvgLength::new(22.5, LengthUnit::FontEx, LengthDir::Vertical)));
+ fn parses_font_ex() {
+ assert_eq!(RsvgLength::parse("22.5ex", LengthDir::Vertical),
+ Ok(RsvgLength::new(22.5,
+ LengthUnit::FontEx,
+ LengthDir::Vertical)));
}
#[test]
- fn parses_physical_units () {
- assert_eq! (RsvgLength::parse ("72pt", LengthDir::Both),
- Ok (RsvgLength::new(1.0, LengthUnit::Inch, LengthDir::Both)));
+ fn parses_physical_units() {
+ assert_eq!(RsvgLength::parse("72pt", LengthDir::Both),
+ Ok(RsvgLength::new(1.0, LengthUnit::Inch, LengthDir::Both)));
- assert_eq! (RsvgLength::parse ("-22.5in", LengthDir::Both),
- Ok (RsvgLength::new(-22.5, LengthUnit::Inch, LengthDir::Both)));
+ assert_eq!(RsvgLength::parse("-22.5in", LengthDir::Both),
+ Ok(RsvgLength::new(-22.5, LengthUnit::Inch, LengthDir::Both)));
- assert_eq! (RsvgLength::parse ("-254cm", LengthDir::Both),
- Ok (RsvgLength::new(-100.0, LengthUnit::Inch, LengthDir::Both)));
+ assert_eq!(RsvgLength::parse("-254cm", LengthDir::Both),
+ Ok(RsvgLength::new(-100.0, LengthUnit::Inch, LengthDir::Both)));
- assert_eq! (RsvgLength::parse ("254mm", LengthDir::Both),
- Ok (RsvgLength::new(10.0, LengthUnit::Inch, LengthDir::Both)));
+ assert_eq!(RsvgLength::parse("254mm", LengthDir::Both),
+ Ok(RsvgLength::new(10.0, LengthUnit::Inch, LengthDir::Both)));
- assert_eq! (RsvgLength::parse ("60pc", LengthDir::Both),
- Ok (RsvgLength::new(10.0, LengthUnit::Inch, LengthDir::Both)));
+ assert_eq!(RsvgLength::parse("60pc", LengthDir::Both),
+ Ok(RsvgLength::new(10.0, LengthUnit::Inch, LengthDir::Both)));
}
#[test]
- fn parses_relative_larger () {
- assert_eq! (RsvgLength::parse ("larger", LengthDir::Vertical),
- Ok (RsvgLength::new(0.0, LengthUnit::RelativeLarger, LengthDir::Vertical)));
+ fn parses_relative_larger() {
+ assert_eq!(RsvgLength::parse("larger", LengthDir::Vertical),
+ Ok(RsvgLength::new(0.0,
+ LengthUnit::RelativeLarger,
+ LengthDir::Vertical)));
}
#[test]
- fn parses_relative_smaller () {
- assert_eq! (RsvgLength::parse ("smaller", LengthDir::Vertical),
- Ok (RsvgLength::new(0.0, LengthUnit::RelativeSmaller, LengthDir::Vertical)));
+ fn parses_relative_smaller() {
+ assert_eq!(RsvgLength::parse("smaller", LengthDir::Vertical),
+ Ok(RsvgLength::new(0.0,
+ LengthUnit::RelativeSmaller,
+ LengthDir::Vertical)));
}
#[test]
- fn parses_named_sizes () {
- let names = vec![ "xx-small",
- "x-small",
- "small",
- "medium",
- "large",
- "x-large",
- "xx-large" ];
+ fn parses_named_sizes() {
+ let names = vec!["xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large"];
let mut previous_value: Option<f64> = None;
@@ -503,48 +545,51 @@ mod tests {
// enforce a particular sequence.
for name in names {
- let length = RsvgLength::parse (name, LengthDir::Both).unwrap ();
+ let length = RsvgLength::parse(name, LengthDir::Both).unwrap();
- assert_eq! (length.unit, LengthUnit::Inch);
- assert_eq! (length.dir, LengthDir::Both);
+ assert_eq!(length.unit, LengthUnit::Inch);
+ assert_eq!(length.dir, LengthDir::Both);
- if let Some (v) = previous_value {
- assert! (length.length > v);
+ if let Some(v) = previous_value {
+ assert!(length.length > v);
} else {
- previous_value = Some (length.length);
+ previous_value = Some(length.length);
}
-
}
}
#[test]
- fn empty_length_yields_error () {
- assert! (is_parse_error (&RsvgLength::parse ("", LengthDir::Both)));
+ fn empty_length_yields_error() {
+ assert!(is_parse_error(&RsvgLength::parse("", LengthDir::Both)));
}
#[test]
- fn invalid_unit_yields_error () {
- assert! (is_parse_error (&RsvgLength::parse ("8furlong", LengthDir::Both)));
+ fn invalid_unit_yields_error() {
+ assert!(is_parse_error(&RsvgLength::parse("8furlong", LengthDir::Both)));
}
#[test]
- fn invalid_font_size_yields_error () {
+ fn invalid_font_size_yields_error() {
// FIXME: this is intended to test the (absence of) the "larger" et al values.
// Since they really be in FontSize, not RsvgLength, we should remember
// to move this test to that type later.
- assert! (is_parse_error (&RsvgLength::parse ("furlong", LengthDir::Both)));
+ assert!(is_parse_error(&RsvgLength::parse("furlong", LengthDir::Both)));
}
#[test]
- fn check_nonnegative_works () {
- assert! (RsvgLength::parse ("0", LengthDir::Both).and_then (|l| l.check_nonnegative ()).is_ok ());
- assert! (RsvgLength::parse ("-10", LengthDir::Both).and_then (|l| l.check_nonnegative ()).is_err ());
+ fn check_nonnegative_works() {
+ assert!(RsvgLength::parse("0", LengthDir::Both).and_then(|l| l.check_nonnegative())
+ .is_ok());
+ assert!(RsvgLength::parse("-10", LengthDir::Both).and_then(|l| l.check_nonnegative())
+ .is_err());
}
#[test]
fn parses_stroke_dasharray() {
- assert_eq!(parse_stroke_dash_array("none").unwrap(), StrokeDasharray::None);
- assert_eq!(parse_stroke_dash_array("inherit").unwrap(), StrokeDasharray::Inherit);
+ assert_eq!(parse_stroke_dash_array("none").unwrap(),
+ StrokeDasharray::None);
+ assert_eq!(parse_stroke_dash_array("inherit").unwrap(),
+ StrokeDasharray::Inherit);
assert_eq!(parse_stroke_dash_array("10, 5").unwrap(),
StrokeDasharray::Dasharray(parse_dash_array("10, 5").unwrap()));
assert!(parse_stroke_dash_array("").is_err());
@@ -553,34 +598,24 @@ mod tests {
#[test]
fn parses_dash_array() {
// helper to cut down boilderplate
- let length_parse = |s| { RsvgLength::parse(s, LengthDir::Both).unwrap() };
+ let length_parse = |s| RsvgLength::parse(s, LengthDir::Both).unwrap();
- let expected = vec![
- length_parse("1"),
- length_parse("2in"),
- length_parse("3"),
- length_parse("4%")
- ];
+ let expected = vec![length_parse("1"),
+ length_parse("2in"),
+ length_parse("3"),
+ length_parse("4%")];
let sample_1 = vec![length_parse("10"), length_parse("6")];
- let sample_2 = vec![
- length_parse("5"),
- length_parse("5"),
- length_parse("20"),
- ];
-
- let sample_3 = vec![
- length_parse("10px"),
- length_parse("20px"),
- length_parse("20px"),
- ];
-
- let sample_4 = vec![
- length_parse("25"),
- length_parse("5"),
- length_parse("5"),
- length_parse("5"),
- ];
+ let sample_2 = vec![length_parse("5"), length_parse("5"), length_parse("20")];
+
+ let sample_3 = vec![length_parse("10px"),
+ length_parse("20px"),
+ length_parse("20px")];
+
+ let sample_4 = vec![length_parse("25"),
+ length_parse("5"),
+ length_parse("5"),
+ length_parse("5")];
let sample_5 = vec![length_parse("3.1415926"), length_parse("8")];
let sample_6 = vec![length_parse("5"), length_parse("3.14")];
@@ -596,8 +631,10 @@ mod tests {
assert_eq!(parse_dash_array("2").unwrap(), sample_7);
// Empty dash_array
- assert_eq!(parse_dash_array(""), Err(AttributeError::Parse(ParseError::new("empty string"))));
- assert_eq!(parse_dash_array("\t \n "), Err(AttributeError::Parse(ParseError::new("empty
string"))));
+ assert_eq!(parse_dash_array(""),
+ Err(AttributeError::Parse(ParseError::new("empty string"))));
+ assert_eq!(parse_dash_array("\t \n "),
+ Err(AttributeError::Parse(ParseError::new("empty string"))));
assert!(parse_dash_array(",,,").is_err());
assert!(parse_dash_array("10, \t, 20 \n").is_err());
// No trailling commas allowed, parse error
diff --git a/rsvg_internals/src/lib.rs b/rsvg_internals/src/lib.rs
index aedebebf..78c6345a 100644
--- a/rsvg_internals/src/lib.rs
+++ b/rsvg_internals/src/lib.rs
@@ -7,8 +7,8 @@ extern crate cairo_sys;
extern crate cssparser;
extern crate glib;
extern crate glib_sys;
-extern crate libc;
extern crate itertools;
+extern crate libc;
extern crate pango;
extern crate pango_sys;
extern crate regex;
@@ -19,169 +19,70 @@ extern crate lazy_static;
#[macro_use]
extern crate downcast_rs;
-pub use attributes::{
- rsvg_attribute_from_name,
-};
-
-pub use bbox::{
- RsvgBbox,
- rsvg_bbox_init,
- rsvg_bbox_insert,
- rsvg_bbox_clip
-};
-
-pub use chars::{
- rsvg_node_chars_new,
- rsvg_node_chars_append,
- rsvg_node_chars_get_string,
-};
-
-pub use clip_path::{
- rsvg_node_clip_path_new,
- rsvg_node_clip_path_get_units
-};
-
-pub use cnode::{
- rsvg_rust_cnode_new,
- rsvg_rust_cnode_get_impl
-};
-
-pub use color::{
- AllowCurrentColor,
- AllowInherit,
- ColorKind,
- ColorSpec,
- rsvg_css_parse_color
-};
-
-pub use gradient::{
- rsvg_node_linear_gradient_new,
- rsvg_node_radial_gradient_new,
-};
-
-pub use length::{
- LengthUnit,
- LengthDir,
- RsvgLength,
- rsvg_length_parse,
- rsvg_length_normalize,
- rsvg_length_hand_normalize,
- rsvg_parse_stroke_dasharray
-};
-
-pub use image::{
- rsvg_node_image_new,
-};
-
-pub use link::{
- rsvg_node_link_new,
-};
-
-pub use marker::{
- rsvg_node_marker_new,
-};
-
-pub use mask::{
- rsvg_node_mask_new,
- rsvg_node_mask_get_x,
- rsvg_node_mask_get_y,
- rsvg_node_mask_get_width,
- rsvg_node_mask_get_height,
- rsvg_node_mask_get_units,
- rsvg_node_mask_get_content_units,
-};
-
-pub use node::{
- rsvg_node_get_type,
- rsvg_node_get_parent,
- rsvg_node_ref,
- rsvg_node_unref,
- rsvg_node_is_same,
- rsvg_node_get_state,
- rsvg_node_add_child,
- rsvg_node_set_atts,
- rsvg_node_draw,
- rsvg_node_set_attribute_parse_error,
- rsvg_node_foreach_child,
- rsvg_node_draw_children,
-};
-
-pub use opacity::{
- OpacityKind,
- OpacitySpec,
- rsvg_css_parse_opacity
-};
-
-pub use paint_server::{
- rsvg_paint_server_parse,
- rsvg_paint_server_ref,
- rsvg_paint_server_unref,
- _set_source_rsvg_paint_server
-};
-
-pub use parsers::{
- rsvg_css_parse_number_list,
- rsvg_css_parse_number_optional_number
-};
-
-pub use path_builder::{
- rsvg_path_builder_add_to_cairo_context
-};
-
-pub use pattern::{
- rsvg_node_pattern_new,
-};
-
-pub use property_bag::{
- rsvg_property_bag_free,
- rsvg_property_bag_iter_begin,
- rsvg_property_bag_iter_end,
- rsvg_property_bag_iter_next,
- rsvg_property_bag_new,
-};
-
-pub use shapes::{
- rsvg_node_circle_new,
- rsvg_node_ellipse_new,
- rsvg_node_line_new,
- rsvg_node_path_new,
- rsvg_node_polygon_new,
- rsvg_node_polyline_new,
- rsvg_node_rect_new,
-};
-
-pub use space::{
- rsvg_xml_space_normalize,
-};
-
-pub use stop::{
- rsvg_node_stop_new
-};
-
-pub use structure::{
- rsvg_node_group_new,
- rsvg_node_defs_new,
- rsvg_node_switch_new,
- rsvg_node_symbol_new,
- rsvg_node_svg_new,
- rsvg_node_svg_get_size,
- rsvg_node_svg_get_view_box,
- rsvg_node_svg_apply_atts,
- rsvg_node_use_new,
-};
-
-pub use text::{
- rsvg_text_create_layout,
-};
-
-pub use transform::{
- rsvg_parse_transform,
-};
-
-pub use viewbox::{
- RsvgViewBox
-};
+pub use attributes::rsvg_attribute_from_name;
+
+pub use bbox::{rsvg_bbox_clip, rsvg_bbox_init, rsvg_bbox_insert, RsvgBbox};
+
+pub use chars::{rsvg_node_chars_append, rsvg_node_chars_get_string, rsvg_node_chars_new};
+
+pub use clip_path::{rsvg_node_clip_path_get_units, rsvg_node_clip_path_new};
+
+pub use cnode::{rsvg_rust_cnode_get_impl, rsvg_rust_cnode_new};
+
+pub use color::{rsvg_css_parse_color, AllowCurrentColor, AllowInherit, ColorKind, ColorSpec};
+
+pub use gradient::{rsvg_node_linear_gradient_new, rsvg_node_radial_gradient_new};
+
+pub use length::{rsvg_length_hand_normalize, rsvg_length_normalize, rsvg_length_parse,
+ rsvg_parse_stroke_dasharray, LengthDir, LengthUnit, RsvgLength};
+
+pub use image::rsvg_node_image_new;
+
+pub use link::rsvg_node_link_new;
+
+pub use marker::rsvg_node_marker_new;
+
+pub use mask::{rsvg_node_mask_get_content_units, rsvg_node_mask_get_height,
+ rsvg_node_mask_get_units, rsvg_node_mask_get_width, rsvg_node_mask_get_x,
+ rsvg_node_mask_get_y, rsvg_node_mask_new};
+
+pub use node::{rsvg_node_add_child, rsvg_node_draw, rsvg_node_draw_children,
+ rsvg_node_foreach_child, rsvg_node_get_parent, rsvg_node_get_state,
+ rsvg_node_get_type, rsvg_node_is_same, rsvg_node_ref,
+ rsvg_node_set_attribute_parse_error, rsvg_node_set_atts, rsvg_node_unref};
+
+pub use opacity::{rsvg_css_parse_opacity, OpacityKind, OpacitySpec};
+
+pub use paint_server::{_set_source_rsvg_paint_server, rsvg_paint_server_parse,
+ rsvg_paint_server_ref, rsvg_paint_server_unref};
+
+pub use parsers::{rsvg_css_parse_number_list, rsvg_css_parse_number_optional_number};
+
+pub use path_builder::rsvg_path_builder_add_to_cairo_context;
+
+pub use pattern::rsvg_node_pattern_new;
+
+pub use property_bag::{rsvg_property_bag_free, rsvg_property_bag_iter_begin,
+ rsvg_property_bag_iter_end, rsvg_property_bag_iter_next,
+ rsvg_property_bag_new};
+
+pub use shapes::{rsvg_node_circle_new, rsvg_node_ellipse_new, rsvg_node_line_new,
+ rsvg_node_path_new, rsvg_node_polygon_new, rsvg_node_polyline_new,
+ rsvg_node_rect_new};
+
+pub use space::rsvg_xml_space_normalize;
+
+pub use stop::rsvg_node_stop_new;
+
+pub use structure::{rsvg_node_defs_new, rsvg_node_group_new, rsvg_node_svg_apply_atts,
+ rsvg_node_svg_get_size, rsvg_node_svg_get_view_box, rsvg_node_svg_new,
+ rsvg_node_switch_new, rsvg_node_symbol_new, rsvg_node_use_new};
+
+pub use text::rsvg_text_create_layout;
+
+pub use transform::rsvg_parse_transform;
+pub use viewbox::RsvgViewBox;
#[macro_use]
mod coord_units;
@@ -189,6 +90,7 @@ mod coord_units;
mod aspect_ratio;
mod attributes;
mod bbox;
+#[cfg_attr(rustfmt, rustfmt_skip)]
mod chars;
mod clip_path;
mod cnode;
diff --git a/rsvg_internals/src/link.rs b/rsvg_internals/src/link.rs
index cfcb546c..c15f5d81 100644
--- a/rsvg_internals/src/link.rs
+++ b/rsvg_internals/src/link.rs
@@ -3,9 +3,9 @@ use cairo_sys;
use glib::translate::*;
use libc;
+use regex::{Captures, Regex};
use std::borrow::Cow;
use std::cell::RefCell;
-use regex::{Regex, Captures};
use attributes::Attribute;
use drawing_ctx::{self, RsvgDrawingCtx};
@@ -19,7 +19,7 @@ struct NodeLink {
impl NodeLink {
fn new() -> NodeLink {
- NodeLink { link: RefCell::new(None) }
+ NodeLink { link: RefCell::new(None), }
}
}
@@ -44,11 +44,13 @@ impl NodeTrait for NodeLink {
let attributes = link.as_ref().map(|i| format!("uri='{}'", escape_value(i)));
- drawing_ctx::get_cairo_context(draw_ctx).with_tag(
- CAIRO_TAG_LINK,
- attributes.as_ref().map(|i| i.as_str()),
- || node.draw_children(draw_ctx, dominate),
- )
+ drawing_ctx::get_cairo_context(draw_ctx).with_tag(CAIRO_TAG_LINK,
+ attributes.as_ref()
+ .map(|i| i.as_str()),
+ || {
+ node.draw_children(draw_ctx,
+ dominate)
+ })
} else {
node.draw_children(draw_ctx, dominate)
}
@@ -65,22 +67,19 @@ fn escape_value(value: &str) -> Cow<str> {
static ref REGEX: Regex = Regex::new(r"['\\]").unwrap();
}
- REGEX.replace_all(
- value,
- |caps: &Captures| match caps.get(0).unwrap().as_str() {
+ REGEX.replace_all(value, |caps: &Captures| {
+ match caps.get(0).unwrap().as_str() {
"'" => "\\'".to_owned(),
"\\" => "\\\\".to_owned(),
_ => unreachable!(),
- },
- )
+ }
+ })
}
extern "C" {
- fn cairo_tag_begin(
- cr: *mut cairo_sys::cairo_t,
- tag_name: *const libc::c_char,
- attibutes: *const libc::c_char,
- );
+ fn cairo_tag_begin(cr: *mut cairo_sys::cairo_t,
+ tag_name: *const libc::c_char,
+ attibutes: *const libc::c_char);
fn cairo_tag_end(cr: *mut cairo_sys::cairo_t, tag_name: *const libc::c_char);
}
@@ -89,8 +88,7 @@ trait CairoTagging {
fn tag_begin(&self, tag_name: &str, attributes: Option<&str>);
fn tag_end(&self, tag_name: &str);
fn with_tag<U, T>(&self, tag_name: &str, attributes: Option<&str>, f: U) -> T
- where
- U: Fn() -> T,
+ where U: Fn() -> T
{
self.tag_begin(tag_name, attributes);
let result = f();
@@ -103,11 +101,9 @@ trait CairoTagging {
impl CairoTagging for cairo::Context {
fn tag_begin(&self, tag_name: &str, attributes: Option<&str>) {
unsafe {
- cairo_tag_begin(
- self.to_glib_none().0,
- tag_name.to_glib_none().0,
- attributes.to_glib_none().0,
- );
+ cairo_tag_begin(self.to_glib_none().0,
+ tag_name.to_glib_none().0,
+ attributes.to_glib_none().0);
}
}
@@ -118,12 +114,11 @@ impl CairoTagging for cairo::Context {
}
}
-/***** C Prototypes *****/
+/***** C Prototypes **** * * * * **/
#[no_mangle]
-pub extern "C" fn rsvg_node_link_new(
- _: *const libc::c_char,
- raw_parent: *const RsvgNode,
-) -> *const RsvgNode {
+pub extern "C" fn rsvg_node_link_new(_: *const libc::c_char,
+ raw_parent: *const RsvgNode)
+ -> *const RsvgNode {
boxed_node_new(NodeType::Link, raw_parent, Box::new(NodeLink::new()))
}
diff --git a/rsvg_internals/src/marker.rs b/rsvg_internals/src/marker.rs
index 88d3ea0a..252b75cc 100644
--- a/rsvg_internals/src/marker.rs
+++ b/rsvg_internals/src/marker.rs
@@ -13,10 +13,10 @@ use error::*;
use handle::RsvgHandle;
use length::*;
use node::*;
-use path_builder::*;
use parsers;
-use parsers::{Parse, parse};
+use parsers::{parse, Parse};
use parsers::ParseError;
+use path_builder::*;
use property_bag::PropertyBag;
use util::*;
use viewbox::*;
@@ -26,11 +26,11 @@ use viewbox::*;
#[derive(Debug, Copy, Clone, PartialEq)]
enum MarkerUnits {
UserSpaceOnUse,
- StrokeWidth
+ StrokeWidth,
}
impl Default for MarkerUnits {
- fn default () -> MarkerUnits {
+ fn default() -> MarkerUnits {
MarkerUnits::StrokeWidth
}
}
@@ -39,11 +39,14 @@ impl Parse for MarkerUnits {
type Data = ();
type Err = AttributeError;
- fn parse (s: &str, _: ()) -> Result <MarkerUnits, AttributeError> {
+ fn parse(s: &str, _: ()) -> Result<MarkerUnits, AttributeError> {
match s {
- "userSpaceOnUse" => Ok (MarkerUnits::UserSpaceOnUse),
- "strokeWidth" => Ok (MarkerUnits::StrokeWidth),
- _ => Err (AttributeError::Parse (ParseError::new ("expected \"userSpaceOnUse\" or
\"strokeWidth\"")))
+ "userSpaceOnUse" => Ok(MarkerUnits::UserSpaceOnUse),
+ "strokeWidth" => Ok(MarkerUnits::StrokeWidth),
+ _ => {
+ Err(AttributeError::Parse(ParseError::new("expected \"userSpaceOnUse\" or \
+ \"strokeWidth\"")))
+ }
}
}
}
@@ -53,12 +56,12 @@ impl Parse for MarkerUnits {
#[derive(Debug, Copy, Clone, PartialEq)]
enum MarkerOrient {
Auto,
- Degrees (f64)
+ Degrees(f64),
}
impl Default for MarkerOrient {
- fn default () -> MarkerOrient {
- MarkerOrient::Degrees (0.0)
+ fn default() -> MarkerOrient {
+ MarkerOrient::Degrees(0.0)
}
}
@@ -66,12 +69,13 @@ impl Parse for MarkerOrient {
type Data = ();
type Err = AttributeError;
- fn parse (s: &str, _: ()) -> Result <MarkerOrient, AttributeError> {
+ fn parse(s: &str, _: ()) -> Result<MarkerOrient, AttributeError> {
match s {
- "auto" => Ok (MarkerOrient::Auto),
- _ => parsers::angle_degrees (s)
- .map (MarkerOrient::Degrees)
- .map_err (AttributeError::Parse)
+ "auto" => Ok(MarkerOrient::Auto),
+ _ => {
+ parsers::angle_degrees(s).map(MarkerOrient::Degrees)
+ .map_err(AttributeError::Parse)
+ }
}
}
}
@@ -79,184 +83,189 @@ impl Parse for MarkerOrient {
// NodeMarker
struct NodeMarker {
- units: Cell<MarkerUnits>,
- ref_x: Cell<RsvgLength>,
- ref_y: Cell<RsvgLength>,
- width: Cell<RsvgLength>,
+ units: Cell<MarkerUnits>,
+ ref_x: Cell<RsvgLength>,
+ ref_y: Cell<RsvgLength>,
+ width: Cell<RsvgLength>,
height: Cell<RsvgLength>,
orient: Cell<MarkerOrient>,
aspect: Cell<AspectRatio>,
- vbox: Cell<Option<ViewBox>>
+ vbox: Cell<Option<ViewBox>>,
}
impl NodeMarker {
- fn new () -> NodeMarker {
- NodeMarker {
- units: Cell::new (MarkerUnits::default ()),
- ref_x: Cell::new (RsvgLength::default ()),
- ref_y: Cell::new (RsvgLength::default ()),
- width: Cell::new (NodeMarker::get_default_size (LengthDir::Horizontal)),
- height: Cell::new (NodeMarker::get_default_size (LengthDir::Vertical)),
- orient: Cell::new (MarkerOrient::default ()),
- aspect: Cell::new (AspectRatio::default ()),
- vbox: Cell::new (None)
- }
+ fn new() -> NodeMarker {
+ NodeMarker { units: Cell::new(MarkerUnits::default()),
+ ref_x: Cell::new(RsvgLength::default()),
+ ref_y: Cell::new(RsvgLength::default()),
+ width: Cell::new(NodeMarker::get_default_size(LengthDir::Horizontal)),
+ height: Cell::new(NodeMarker::get_default_size(LengthDir::Vertical)),
+ orient: Cell::new(MarkerOrient::default()),
+ aspect: Cell::new(AspectRatio::default()),
+ vbox: Cell::new(None), }
}
- fn get_default_size (dir: LengthDir) -> RsvgLength {
+ fn get_default_size(dir: LengthDir) -> RsvgLength {
// per the spec
- RsvgLength::parse ("3", dir).unwrap()
+ RsvgLength::parse("3", dir).unwrap()
}
- fn render (&self,
- node: &RsvgNode,
- c_node: *const RsvgNode,
- draw_ctx: *const RsvgDrawingCtx,
- xpos: f64,
- ypos: f64,
- computed_angle: f64,
- line_width: f64) {
- let marker_width = self.width.get ().normalize (draw_ctx);
- let marker_height = self.height.get ().normalize (draw_ctx);
+ fn render(&self,
+ node: &RsvgNode,
+ c_node: *const RsvgNode,
+ draw_ctx: *const RsvgDrawingCtx,
+ xpos: f64,
+ ypos: f64,
+ computed_angle: f64,
+ line_width: f64) {
+ let marker_width = self.width.get().normalize(draw_ctx);
+ let marker_height = self.height.get().normalize(draw_ctx);
if double_equals(marker_width, 0.0) || double_equals(marker_height, 0.0) {
// markerWidth or markerHeight set to 0 disables rendering of the element
// https://www.w3.org/TR/SVG/painting.html#MarkerWidthAttribute
return;
}
- let mut affine = drawing_ctx::get_current_state_affine (draw_ctx);
- affine.translate (xpos, ypos);
+ let mut affine = drawing_ctx::get_current_state_affine(draw_ctx);
+ affine.translate(xpos, ypos);
- let rotation = match self.orient.get () {
- MarkerOrient::Auto => computed_angle,
- MarkerOrient::Degrees (d) => d * PI / 180.0,
+ let rotation = match self.orient.get() {
+ MarkerOrient::Auto => computed_angle,
+ MarkerOrient::Degrees(d) => d * PI / 180.0,
};
- affine.rotate (rotation);
+ affine.rotate(rotation);
- if self.units.get () == MarkerUnits::StrokeWidth {
- affine.scale (line_width, line_width);
+ if self.units.get() == MarkerUnits::StrokeWidth {
+ affine.scale(line_width, line_width);
}
- if let Some (vbox) = self.vbox.get () {
- let (_, _, w, h) = self.aspect.get ().compute (vbox.0.width, vbox.0.height,
- 0.0, 0.0,
- marker_width, marker_height);
+ if let Some(vbox) = self.vbox.get() {
+ let (_, _, w, h) = self.aspect.get().compute(vbox.0.width,
+ vbox.0.height,
+ 0.0,
+ 0.0,
+ marker_width,
+ marker_height);
- affine.scale (w / vbox.0.width, h / vbox.0.height);
+ affine.scale(w / vbox.0.width, h / vbox.0.height);
- drawing_ctx::push_view_box (draw_ctx, vbox.0.width, vbox.0.height);
- drawing_ctx::push_discrete_layer (draw_ctx);
+ drawing_ctx::push_view_box(draw_ctx, vbox.0.width, vbox.0.height);
+ drawing_ctx::push_discrete_layer(draw_ctx);
} else {
- drawing_ctx::push_view_box (draw_ctx, marker_width, marker_height);
- drawing_ctx::push_discrete_layer (draw_ctx);
+ drawing_ctx::push_view_box(draw_ctx, marker_width, marker_height);
+ drawing_ctx::push_discrete_layer(draw_ctx);
}
- affine.translate (-self.ref_x.get ().normalize (draw_ctx),
- -self.ref_y.get ().normalize (draw_ctx));
-
- drawing_ctx::state_push (draw_ctx);
+ affine.translate(-self.ref_x.get().normalize(draw_ctx),
+ -self.ref_y.get().normalize(draw_ctx));
- let state = drawing_ctx::get_current_state (draw_ctx);
- drawing_ctx::state_reinit (state);
- drawing_ctx::state_reconstruct (state, c_node);
+ drawing_ctx::state_push(draw_ctx);
- drawing_ctx::set_current_state_affine (draw_ctx, affine);
+ let state = drawing_ctx::get_current_state(draw_ctx);
+ drawing_ctx::state_reinit(state);
+ drawing_ctx::state_reconstruct(state, c_node);
+ drawing_ctx::set_current_state_affine(draw_ctx, affine);
- let state = drawing_ctx::get_current_state (draw_ctx);
+ let state = drawing_ctx::get_current_state(draw_ctx);
- if !drawing_ctx::state_is_overflow (state) {
- if let Some (vbox) = self.vbox.get () {
- drawing_ctx::add_clipping_rect (draw_ctx,
- vbox.0.x,
- vbox.0.y,
- vbox.0.width,
- vbox.0.height);
+ if !drawing_ctx::state_is_overflow(state) {
+ if let Some(vbox) = self.vbox.get() {
+ drawing_ctx::add_clipping_rect(draw_ctx,
+ vbox.0.x,
+ vbox.0.y,
+ vbox.0.width,
+ vbox.0.height);
} else {
- drawing_ctx::add_clipping_rect (draw_ctx,
- 0.0,
- 0.0,
- marker_width,
- marker_height);
+ drawing_ctx::add_clipping_rect(draw_ctx, 0.0, 0.0, marker_width, marker_height);
}
}
- node.draw_children (draw_ctx, -1); // dominate=-1 so it won't reinherit state / push a layer
+ node.draw_children(draw_ctx, -1); // dominate=-1 so it won't reinherit state / push a layer
- drawing_ctx::state_pop (draw_ctx);
- drawing_ctx::pop_discrete_layer (draw_ctx);
- drawing_ctx::pop_view_box (draw_ctx);
+ drawing_ctx::state_pop(draw_ctx);
+ drawing_ctx::pop_discrete_layer(draw_ctx);
+ drawing_ctx::pop_view_box(draw_ctx);
}
}
impl NodeTrait for NodeMarker {
- fn set_atts (&self, _: &RsvgNode, _: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
+ fn set_atts(&self, _: &RsvgNode, _: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
for (_key, attr, value) in pbag.iter() {
match attr {
- Attribute::MarkerUnits =>
- self.units.set(parse("markerUnits", value, (), None)?),
+ Attribute::MarkerUnits => self.units.set(parse("markerUnits", value, (), None)?),
- Attribute::RefX =>
- self.ref_x.set(parse("refX", value, LengthDir::Horizontal, None)?),
+ Attribute::RefX => {
+ self.ref_x.set(parse("refX", value, LengthDir::Horizontal, None)?)
+ }
- Attribute::RefY =>
- self.ref_y.set(parse("refY", value, LengthDir::Vertical, None)?),
+ Attribute::RefY => self.ref_y.set(parse("refY", value, LengthDir::Vertical, None)?),
- Attribute::MarkerWidth =>
- self.width.set(parse("markerWidth", value, LengthDir::Horizontal,
- Some(RsvgLength::check_nonnegative))?),
+ Attribute::MarkerWidth => {
+ self.width.set(parse("markerWidth",
+ value,
+ LengthDir::Horizontal,
+ Some(RsvgLength::check_nonnegative))?)
+ }
- Attribute::MarkerHeight =>
- self.height.set(parse("markerHeight", value, LengthDir::Vertical,
- Some(RsvgLength::check_nonnegative))?),
+ Attribute::MarkerHeight => {
+ self.height.set(parse("markerHeight",
+ value,
+ LengthDir::Vertical,
+ Some(RsvgLength::check_nonnegative))?)
+ }
- Attribute::Orient =>
- self.orient.set(parse("orient", value, (), None)?),
+ Attribute::Orient => self.orient.set(parse("orient", value, (), None)?),
- Attribute::PreserveAspectRatio =>
- self.aspect.set(parse("preserveAspectRatio", value, (), None)?),
+ Attribute::PreserveAspectRatio => {
+ self.aspect.set(parse("preserveAspectRatio", value, (), None)?)
+ }
- Attribute::ViewBox =>
- self.vbox.set(Some(parse("viewBox", value, (), None)?)),
+ Attribute::ViewBox => self.vbox.set(Some(parse("viewBox", value, (), None)?)),
_ => (),
}
}
- Ok (())
+ Ok(())
}
- fn draw (&self, _: &RsvgNode, _: *const RsvgDrawingCtx, _: i32) {
+ fn draw(&self, _: &RsvgNode, _: *const RsvgDrawingCtx, _: i32) {
// nothing; markers are drawn by their referencing shapes
}
- fn get_c_impl (&self) -> *const RsvgCNodeImpl {
- unreachable! ();
+ fn get_c_impl(&self) -> *const RsvgCNodeImpl {
+ unreachable!();
}
}
#[no_mangle]
-pub extern fn rsvg_node_marker_new (_: *const libc::c_char, raw_parent: *const RsvgNode) -> *const RsvgNode {
- boxed_node_new (NodeType::Marker,
- raw_parent,
- Box::new (NodeMarker::new ()))
+pub extern "C" fn rsvg_node_marker_new(_: *const libc::c_char,
+ raw_parent: *const RsvgNode)
+ -> *const RsvgNode {
+ boxed_node_new(NodeType::Marker, raw_parent, Box::new(NodeMarker::new()))
}
// Machinery to figure out marker orientations
#[derive(Debug, PartialEq)]
pub enum Segment {
- Degenerate { // A single lone point
+ Degenerate {
+ // A single lone point
x: f64,
- y: f64
+ y: f64,
},
LineOrCurve {
- x1: f64, y1: f64,
- x2: f64, y2: f64,
- x3: f64, y3: f64,
- x4: f64, y4: f64
+ x1: f64,
+ y1: f64,
+ x2: f64,
+ y2: f64,
+ x3: f64,
+ y3: f64,
+ x4: f64,
+ y4: f64,
},
}
@@ -264,48 +273,47 @@ enum SegmentState {
Initial,
NewSubpath,
InSubpath,
- ClosedSubpath
+ ClosedSubpath,
}
-/* This converts a cairo_path_t into a list of curveto-like segments. Each segment can be:
- *
- * 1. Segment::Degenerate => the segment is actually a single point (x, y)
- *
- * 2. Segment::LineOrCurve => either a lineto or a curveto (or the effective lineto that results from a
closepath).
- * We have the following points:
- * P1 = (x1, y1)
- * P2 = (x2, y2)
- * P3 = (x3, y3)
- * P4 = (x4, y4)
- *
- * The start and end points are P1 and P4, respectively.
- * The tangent at the start point is given by the vector (P2 - P1).
- * The tangent at the end point is given by the vector (P4 - P3).
- * The tangents also work if the segment refers to a lineto (they will both just point in the same
direction).
- */
-
-fn make_degenerate (x: f64, y: f64) -> Segment {
- Segment::Degenerate { x: x, y: y }
+/* This converts a cairo_path_t into a list of curveto-like segments. Each segment can be: */
+//
+// 1. Segment::Degenerate => the segment is actually a single point (x, y)
+//
+// 2. Segment::LineOrCurve => either a lineto or a curveto (or the effective lineto that results
+// from a closepath). We have the following points:
+// P1 = (x1, y1)
+// P2 = (x2, y2)
+// P3 = (x3, y3)
+// P4 = (x4, y4)
+//
+// The start and end points are P1 and P4, respectively.
+// The tangent at the start point is given by the vector (P2 - P1).
+// The tangent at the end point is given by the vector (P4 - P3).
+// The tangents also work if the segment refers to a lineto (they will both just point in the
+// same direction).
+//
+
+fn make_degenerate(x: f64, y: f64) -> Segment {
+ Segment::Degenerate { x, y }
}
-fn make_curve (x1: f64, y1: f64,
- x2: f64, y2: f64,
- x3: f64, y3: f64,
- x4: f64, y4: f64) -> Segment {
- Segment::LineOrCurve {
- x1: x1, y1: y1,
- x2: x2, y2: y2,
- x3: x3, y3: y3,
- x4: x4, y4: y4
- }
+fn make_curve(x1: f64, y1: f64, x2: f64, y2: f64, x3: f64, y3: f64, x4: f64, y4: f64) -> Segment {
+ Segment::LineOrCurve { x1,
+ y1,
+ x2,
+ y2,
+ x3,
+ y3,
+ x4,
+ y4, }
}
-fn make_line (x1: f64, y1: f64, x2: f64, y2: f64) -> Segment {
- make_curve (x1, y1, x2, y2, x1, y1, x2, y2)
+fn make_line(x1: f64, y1: f64, x2: f64, y2: f64) -> Segment {
+ make_curve(x1, y1, x2, y2, x1, y1, x2, y2)
}
-
-pub fn path_builder_to_segments (builder: &RsvgPathBuilder) -> Vec<Segment> {
+pub fn path_builder_to_segments(builder: &RsvgPathBuilder) -> Vec<Segment> {
let mut last_x: f64;
let mut last_y: f64;
let mut cur_x: f64;
@@ -320,15 +328,15 @@ pub fn path_builder_to_segments (builder: &RsvgPathBuilder) -> Vec<Segment> {
subpath_start_x = 0.0;
subpath_start_y = 0.0;
- segments = Vec::new ();
+ segments = Vec::new();
state = SegmentState::Initial;
- for path_command in builder.get_path_commands () {
+ for path_command in builder.get_path_commands() {
last_x = cur_x;
last_y = cur_y;
match *path_command {
- PathCommand::MoveTo (x, y) => {
+ PathCommand::MoveTo(x, y) => {
cur_x = x;
cur_y = y;
@@ -336,61 +344,62 @@ pub fn path_builder_to_segments (builder: &RsvgPathBuilder) -> Vec<Segment> {
subpath_start_y = cur_y;
match state {
- SegmentState::Initial |
- SegmentState::InSubpath => {
- /* Ignore the very first moveto in a sequence (Initial state), or if we were
- * already drawing within a subpath, start a new subpath.
+ SegmentState::Initial | SegmentState::InSubpath => {
+ /* Ignore the very first moveto in a sequence (Initial state), or if we
+ * were already drawing within a subpath, start
+ * a new subpath.
*/
state = SegmentState::NewSubpath;
- },
+ }
SegmentState::NewSubpath => {
- /* We had just begun a new subpath (i.e. from a moveto) and we got another
- * moveto? Output a stray point for the previous moveto.
+ /* We had just begun a new subpath (i.e. from a moveto) and we got
+ * another moveto? Output a stray point for the
+ * previous moveto.
*/
- segments.push (make_degenerate (last_x, last_y));
+ segments.push(make_degenerate(last_x, last_y));
state = SegmentState::NewSubpath;
}
SegmentState::ClosedSubpath => {
/* Cairo outputs a moveto after every closepath, so that subsequent
- * lineto/curveto commands will start at the closed vertex.
- *
- * We don't want to actually emit a point (a degenerate segment) in that
- * artificial-moveto case.
- *
- * We'll reset to the Initial state so that a subsequent "real" moveto will
- * be handled as the beginning of a new subpath, or a degenerate point, as
- * usual.
- */
+ * lineto/curveto commands will start at the closed vertex. */
+ //
+ // We don't want to actually emit a point (a degenerate segment) in that
+ // artificial-moveto case.
+ //
+ // We'll reset to the Initial state so that a subsequent "real" moveto will
+ // be handled as the beginning of a new subpath, or a degenerate point, as
+ // usual.
+ //
state = SegmentState::Initial;
}
}
- },
+ }
- PathCommand::LineTo (x, y) => {
+ PathCommand::LineTo(x, y) => {
cur_x = x;
cur_y = y;
- segments.push (make_line (last_x, last_y, cur_x, cur_y));
+ segments.push(make_line(last_x, last_y, cur_x, cur_y));
state = SegmentState::InSubpath;
- },
+ }
- PathCommand::CurveTo ((x2, y2), (x3, y3), (x4, y4)) => {
+ PathCommand::CurveTo((x2, y2), (x3, y3), (x4, y4)) => {
cur_x = x4;
cur_y = y4;
- segments.push (make_curve (last_x, last_y, x2, y2, x3, y3, cur_x, cur_y));
+ segments.push(make_curve(last_x, last_y, x2, y2, x3, y3, cur_x, cur_y));
state = SegmentState::InSubpath;
- },
+ }
PathCommand::ClosePath => {
cur_x = subpath_start_x;
cur_y = subpath_start_y;
- segments.push (make_line (last_x, last_y, cur_x, cur_y));
+ segments.push(make_line(last_x, last_y, cur_x, cur_y));
state = SegmentState::ClosedSubpath;
}
@@ -400,129 +409,132 @@ pub fn path_builder_to_segments (builder: &RsvgPathBuilder) -> Vec<Segment> {
if let SegmentState::NewSubpath = state {
// Output a lone point if we started a subpath with a moveto
// command, but there are no subsequent commands.
- segments.push (make_degenerate (cur_x, cur_y));
+ segments.push(make_degenerate(cur_x, cur_y));
};
segments
}
-fn points_equal (x1: f64, y1: f64, x2: f64, y2: f64) -> bool {
- double_equals (x1, x2) && double_equals (y1, y2)
+fn points_equal(x1: f64, y1: f64, x2: f64, y2: f64) -> bool {
+ double_equals(x1, x2) && double_equals(y1, y2)
}
-/* If the segment has directionality, returns two vectors (v1x, v1y, v2x, v2y); otherwise, returns None. The
- * vectors are the tangents at the beginning and at the end of the segment, respectively. A segment does
not have
- * directionality if it is degenerate (i.e. a single point) or a zero-length segment, i.e. where all four
control
- * points are coincident (the first and last control points may coincide, but the others may define a loop -
thus
- * nonzero length)
+/* If the segment has directionality, returns two vectors (v1x, v1y, v2x, v2y); otherwise,
+ * returns None. The vectors are the tangents at the beginning and at the end of the segment,
+ * respectively. A segment does not have directionality if it is degenerate (i.e. a single
+ * point) or a zero-length segment, i.e. where all four control points are coincident (the first
+ * and last control points may coincide, but the others may define a loop - thus nonzero length)
*/
-fn get_segment_directionalities (segment: &Segment) -> Option <(f64, f64, f64, f64)> {
+fn get_segment_directionalities(segment: &Segment) -> Option<(f64, f64, f64, f64)> {
match *segment {
- Segment::Degenerate { .. } => { None },
-
- Segment::LineOrCurve { x1, y1, x2, y2, x3, y3, x4, y4 } => {
- let coincide_1_and_2 = points_equal (x1, y1, x2, y2);
- let coincide_1_and_3 = points_equal (x1, y1, x3, y3);
- let coincide_1_and_4 = points_equal (x1, y1, x4, y4);
- let coincide_2_and_3 = points_equal (x2, y2, x3, y3);
- let coincide_2_and_4 = points_equal (x2, y2, x4, y4);
- let coincide_3_and_4 = points_equal (x3, y3, x4, y4);
+ Segment::Degenerate { .. } => None,
+
+ Segment::LineOrCurve { x1,
+ y1,
+ x2,
+ y2,
+ x3,
+ y3,
+ x4,
+ y4, } => {
+ let coincide_1_and_2 = points_equal(x1, y1, x2, y2);
+ let coincide_1_and_3 = points_equal(x1, y1, x3, y3);
+ let coincide_1_and_4 = points_equal(x1, y1, x4, y4);
+ let coincide_2_and_3 = points_equal(x2, y2, x3, y3);
+ let coincide_2_and_4 = points_equal(x2, y2, x4, y4);
+ let coincide_3_and_4 = points_equal(x3, y3, x4, y4);
if coincide_1_and_2 && coincide_1_and_3 && coincide_1_and_4 {
-
None
-
} else if coincide_1_and_2 && coincide_1_and_3 {
-
- Some ((x4 - x1, y4 - y1, x4 - x3, y4 - y3))
-
+ Some((x4 - x1, y4 - y1, x4 - x3, y4 - y3))
} else if coincide_1_and_2 && coincide_3_and_4 {
-
- Some ((x4 - x1, y4 - y1, x4 - x1, y4 - y1))
-
+ Some((x4 - x1, y4 - y1, x4 - x1, y4 - y1))
} else if coincide_2_and_3 && coincide_2_and_4 {
-
- Some ((x2 - x1, y2 - y1, x4 - x1, y4 - y1))
-
+ Some((x2 - x1, y2 - y1, x4 - x1, y4 - y1))
} else if coincide_1_and_2 {
-
- Some ((x3 - x1, y3 - y1, x4 - x3, y4 - y3))
-
+ Some((x3 - x1, y3 - y1, x4 - x3, y4 - y3))
} else if coincide_3_and_4 {
-
- Some ((x2 - x1, y2 - y1, x4 - x2, y4 - y2))
-
+ Some((x2 - x1, y2 - y1, x4 - x2, y4 - y2))
} else {
-
- Some ((x2 - x1, y2 - y1, x4 - x3, y4 - y3))
-
+ Some((x2 - x1, y2 - y1, x4 - x3, y4 - y3))
}
}
}
}
-/* The SVG spec 1.1 says http://www.w3.org/TR/SVG/implnote.html#PathElementImplementationNotes
- *
- * Certain line-capping and line-joining situations and markers
- * require that a path segment have directionality at its start and
- * end points. Zero-length path segments have no directionality. In
- * these cases, the following algorithm is used to establish
- * directionality: to determine the directionality of the start
- * point of a zero-length path segment, go backwards in the path
- * data specification within the current subpath until you find a
- * segment which has directionality at its end point (e.g., a path
- * segment with non-zero length) and use its ending direction;
- * otherwise, temporarily consider the start point to lack
- * directionality. Similarly, to determine the directionality of the
- * end point of a zero-length path segment, go forwards in the path
- * data specification within the current subpath until you find a
- * segment which has directionality at its start point (e.g., a path
- * segment with non-zero length) and use its starting direction;
- * otherwise, temporarily consider the end point to lack
- * directionality. If the start point has directionality but the end
- * point doesn't, then the end point uses the start point's
- * directionality. If the end point has directionality but the start
- * point doesn't, then the start point uses the end point's
- * directionality. Otherwise, set the directionality for the path
- * segment's start and end points to align with the positive x-axis
- * in user space.
- */
-fn find_incoming_directionality_backwards (segments: &[Segment], start_index: usize) -> (bool, f64, f64) {
- /* "go backwards ... within the current subpath until ... segment which has directionality at its end
point" */
-
- for segment in segments[.. start_index + 1].iter ().rev () {
+/* The SVG spec 1.1 says http://www.w3.org/TR/SVG/implnote.html#PathElementImplementationNotes */
+//
+// Certain line-capping and line-joining situations and markers
+// require that a path segment have directionality at its start and
+// end points. Zero-length path segments have no directionality. In
+// these cases, the following algorithm is used to establish
+// directionality: to determine the directionality of the start
+// point of a zero-length path segment, go backwards in the path
+// data specification within the current subpath until you find a
+// segment which has directionality at its end point (e.g., a path
+// segment with non-zero length) and use its ending direction;
+// otherwise, temporarily consider the start point to lack
+// directionality. Similarly, to determine the directionality of the
+// end point of a zero-length path segment, go forwards in the path
+// data specification within the current subpath until you find a
+// segment which has directionality at its start point (e.g., a path
+// segment with non-zero length) and use its starting direction;
+// otherwise, temporarily consider the end point to lack
+// directionality. If the start point has directionality but the end
+// point doesn't, then the end point uses the start point's
+// directionality. If the end point has directionality but the start
+// point doesn't, then the start point uses the end point's
+// directionality. Otherwise, set the directionality for the path
+// segment's start and end points to align with the positive x-axis
+// in user space.
+//
+fn find_incoming_directionality_backwards(segments: &[Segment],
+ start_index: usize)
+ -> (bool, f64, f64) {
+ /* "go backwards ... within the current subpath until ... segment which has directionality
+ * at its end point" */
+
+ for segment in segments[..start_index + 1].iter().rev() {
match *segment {
Segment::Degenerate { .. } => {
return (false, 0.0, 0.0); /* reached the beginning of the subpath as we ran into a
standalone point */
- },
+ }
- Segment::LineOrCurve { .. } => {
- match get_segment_directionalities (segment) {
- Some ((_, _, v2x, v2y)) => { return (true, v2x, v2y); }
- None => { continue; }
+ Segment::LineOrCurve { .. } => match get_segment_directionalities(segment) {
+ Some((_, _, v2x, v2y)) => {
+ return (true, v2x, v2y);
}
- }
+ None => {
+ continue;
+ }
+ },
}
}
(false, 0.0, 0.0)
}
-fn find_outgoing_directionality_forwards (segments: &[Segment], start_index: usize) -> (bool, f64, f64) {
- /* "go forwards ... within the current subpath until ... segment which has directionality at its start
point" */
+fn find_outgoing_directionality_forwards(segments: &[Segment],
+ start_index: usize)
+ -> (bool, f64, f64) {
+ /* "go forwards ... within the current subpath until ... segment which has directionality at
+ * its start point" */
- for segment in &segments[start_index .. ] {
+ for segment in &segments[start_index..] {
match *segment {
Segment::Degenerate { .. } => {
- return (false, 0.0, 0.0); /* reached the end of a subpath as we ran into a standalone point
*/
- },
+ return (false, 0.0, 0.0); /* reached the end of a subpath as we ran into a standalone point
*/
+ }
- Segment::LineOrCurve { .. } => {
- match get_segment_directionalities (segment) {
- Some ((v1x, v1y, _, _)) => { return (true, v1x, v1y); }
- None => { continue; }
+ Segment::LineOrCurve { .. } => match get_segment_directionalities(segment) {
+ Some((v1x, v1y, _, _)) => {
+ return (true, v1x, v1y);
}
- }
+ None => {
+ continue;
+ }
+ },
}
}
@@ -530,7 +542,7 @@ fn find_outgoing_directionality_forwards (segments: &[Segment], start_index: usi
}
// Normalizes an angle to [0.0, 2*PI)
-fn normalize_angle (mut angle: f64) -> f64 {
+fn normalize_angle(mut angle: f64) -> f64 {
if angle < 0.0 {
while angle < 0.0 {
angle += PI * 2.0;
@@ -544,25 +556,25 @@ fn normalize_angle (mut angle: f64) -> f64 {
angle
}
-fn angle_from_vector (vx: f64, vy: f64) -> f64 {
- let angle = vy.atan2 (vx);
+fn angle_from_vector(vx: f64, vy: f64) -> f64 {
+ let angle = vy.atan2(vx);
- if angle.is_nan () {
+ if angle.is_nan() {
0.0
} else {
- normalize_angle (angle)
+ normalize_angle(angle)
}
}
-fn bisect_angles (incoming: f64, outgoing: f64) -> f64 {
+fn bisect_angles(incoming: f64, outgoing: f64) -> f64 {
let half_delta: f64;
half_delta = (outgoing - incoming) * 0.5;
- if FRAC_PI_2 < half_delta.abs () {
- normalize_angle (incoming + half_delta - PI)
+ if FRAC_PI_2 < half_delta.abs() {
+ normalize_angle(incoming + half_delta - PI)
} else {
- normalize_angle (incoming + half_delta)
+ normalize_angle(incoming + half_delta)
}
}
@@ -571,89 +583,101 @@ fn bisect_angles (incoming: f64, outgoing: f64) -> f64 {
enum MarkerType {
Start,
Middle,
- End
+ End,
}
-fn emit_marker_by_name (draw_ctx: *const RsvgDrawingCtx,
- marker_name: *const libc::c_char,
- xpos: f64,
- ypos: f64,
- computed_angle: f64,
- line_width: f64) {
- if marker_name.is_null () {
+fn emit_marker_by_name(draw_ctx: *const RsvgDrawingCtx,
+ marker_name: *const libc::c_char,
+ xpos: f64,
+ ypos: f64,
+ computed_angle: f64,
+ line_width: f64) {
+ if marker_name.is_null() {
return;
}
let name = unsafe { utf8_cstr(marker_name) };
- let c_node = drawing_ctx::acquire_node_of_type (draw_ctx, name, NodeType::Marker);
+ let c_node = drawing_ctx::acquire_node_of_type(draw_ctx, name, NodeType::Marker);
- if c_node.is_null () {
+ if c_node.is_null() {
return;
}
- let node: &RsvgNode = unsafe { & *c_node };
+ let node: &RsvgNode = unsafe { &*c_node };
- node.with_impl (|marker: &NodeMarker| marker.render (node, c_node, draw_ctx, xpos, ypos, computed_angle,
line_width));
+ node.with_impl(|marker: &NodeMarker| {
+ marker.render(node,
+ c_node,
+ draw_ctx,
+ xpos,
+ ypos,
+ computed_angle,
+ line_width)
+ });
- drawing_ctx::release_node (draw_ctx, c_node);
+ drawing_ctx::release_node(draw_ctx, c_node);
}
-fn get_marker_name_from_drawing_ctx (draw_ctx: *const RsvgDrawingCtx,
- marker_type: MarkerType) -> *const libc::c_char {
- match marker_type {
- MarkerType::Start => unsafe { rsvg_get_start_marker (draw_ctx) },
- MarkerType::Middle => unsafe { rsvg_get_middle_marker (draw_ctx) },
- MarkerType::End => unsafe { rsvg_get_end_marker (draw_ctx) }
+fn get_marker_name_from_drawing_ctx(draw_ctx: *const RsvgDrawingCtx,
+ marker_type: MarkerType)
+ -> *const libc::c_char {
+ match marker_type {
+ MarkerType::Start => unsafe { rsvg_get_start_marker(draw_ctx) },
+ MarkerType::Middle => unsafe { rsvg_get_middle_marker(draw_ctx) },
+ MarkerType::End => unsafe { rsvg_get_end_marker(draw_ctx) },
}
}
#[derive(Debug, Copy, Clone, PartialEq)]
enum MarkerEndpoint {
Start,
- End
+ End,
}
-fn emit_marker<E> (segment: &Segment,
- endpoint: MarkerEndpoint,
- marker_type: MarkerType,
- orient: f64,
- emit_fn: &mut E) where E: FnMut(MarkerType, f64, f64, f64) {
+fn emit_marker<E>(segment: &Segment,
+ endpoint: MarkerEndpoint,
+ marker_type: MarkerType,
+ orient: f64,
+ emit_fn: &mut E)
+ where E: FnMut(MarkerType, f64, f64, f64)
+{
let (x, y) = match *segment {
- Segment::Degenerate { x, y } => (x, y),
+ Segment::Degenerate { x, y } => (x, y),
- Segment::LineOrCurve { x1, y1, x4, y4, .. } => match endpoint {
- MarkerEndpoint::Start => (x1, y1),
- MarkerEndpoint::End => (x4, y4)
+ Segment::LineOrCurve { x1, y1, x4, y4, .. } => {
+ match endpoint {
+ MarkerEndpoint::Start => (x1, y1),
+ MarkerEndpoint::End => (x4, y4),
+ }
}
};
- emit_fn (marker_type, x, y, orient);
+ emit_fn(marker_type, x, y, orient);
}
extern "C" {
- fn rsvg_get_normalized_stroke_width (draw_ctx: *const RsvgDrawingCtx) -> f64;
+ fn rsvg_get_normalized_stroke_width(draw_ctx: *const RsvgDrawingCtx) -> f64;
- fn rsvg_get_start_marker (draw_ctx: *const RsvgDrawingCtx) -> *const libc::c_char;
- fn rsvg_get_middle_marker (draw_ctx: *const RsvgDrawingCtx) -> *const libc::c_char;
- fn rsvg_get_end_marker (draw_ctx: *const RsvgDrawingCtx) -> *const libc::c_char;
+ fn rsvg_get_start_marker(draw_ctx: *const RsvgDrawingCtx) -> *const libc::c_char;
+ fn rsvg_get_middle_marker(draw_ctx: *const RsvgDrawingCtx) -> *const libc::c_char;
+ fn rsvg_get_end_marker(draw_ctx: *const RsvgDrawingCtx) -> *const libc::c_char;
}
-fn drawing_ctx_has_markers (draw_ctx: *const RsvgDrawingCtx) -> bool {
- (!get_marker_name_from_drawing_ctx (draw_ctx, MarkerType::Start).is_null ()
- || !get_marker_name_from_drawing_ctx (draw_ctx, MarkerType::Middle).is_null ()
- || !get_marker_name_from_drawing_ctx (draw_ctx, MarkerType::End).is_null ())
+fn drawing_ctx_has_markers(draw_ctx: *const RsvgDrawingCtx) -> bool {
+ (!get_marker_name_from_drawing_ctx(draw_ctx, MarkerType::Start).is_null()
+ || !get_marker_name_from_drawing_ctx(draw_ctx, MarkerType::Middle).is_null()
+ || !get_marker_name_from_drawing_ctx(draw_ctx, MarkerType::End).is_null())
}
-pub fn render_markers_for_path_builder (builder: &RsvgPathBuilder,
- draw_ctx: *const RsvgDrawingCtx) {
- let linewidth: f64 = unsafe { rsvg_get_normalized_stroke_width (draw_ctx) };
+pub fn render_markers_for_path_builder(builder: &RsvgPathBuilder, draw_ctx: *const RsvgDrawingCtx) {
+ let linewidth: f64 = unsafe { rsvg_get_normalized_stroke_width(draw_ctx) };
if linewidth == 0.0 {
return;
}
- if !drawing_ctx_has_markers (draw_ctx) {
+ if !drawing_ctx_has_markers(draw_ctx) {
return;
}
@@ -668,71 +692,80 @@ pub fn render_markers_for_path_builder (builder: &RsvgPathBuilder,
});
}
-fn emit_markers_for_path_builder<E> (builder: &RsvgPathBuilder,
- emit_fn: &mut E) where E: FnMut(MarkerType, f64, f64, f64) {
+fn emit_markers_for_path_builder<E>(builder: &RsvgPathBuilder, emit_fn: &mut E)
+ where E: FnMut(MarkerType, f64, f64, f64)
+{
enum SubpathState {
NoSubpath,
- InSubpath
+ InSubpath,
};
/* Convert the path to a list of segments and bare points */
- let segments = path_builder_to_segments (builder);
+ let segments = path_builder_to_segments(builder);
let mut subpath_state = SubpathState::NoSubpath;
- for (i, segment) in segments.iter ().enumerate () {
+ for (i, segment) in segments.iter().enumerate() {
match *segment {
Segment::Degenerate { .. } => {
if let SubpathState::InSubpath = subpath_state {
- assert! (i > 0);
+ assert!(i > 0);
/* Got a lone point after a subpath; render the subpath's end marker first */
- let (_, incoming_vx, incoming_vy) = find_incoming_directionality_backwards (&segments, i
- 1);
- emit_marker (&segments[i - 1],
- MarkerEndpoint::End,
- MarkerType::End,
- angle_from_vector (incoming_vx, incoming_vy),
- emit_fn);
+ let (_, incoming_vx, incoming_vy) =
+ find_incoming_directionality_backwards(&segments, i - 1);
+ emit_marker(&segments[i - 1],
+ MarkerEndpoint::End,
+ MarkerType::End,
+ angle_from_vector(incoming_vx, incoming_vy),
+ emit_fn);
}
/* Render marker for the lone point; no directionality */
- emit_marker (segment, MarkerEndpoint::Start, MarkerType::Middle, 0.0, emit_fn);
+ emit_marker(segment,
+ MarkerEndpoint::Start,
+ MarkerType::Middle,
+ 0.0,
+ emit_fn);
subpath_state = SubpathState::NoSubpath;
- },
+ }
Segment::LineOrCurve { .. } => {
/* Not a degenerate segment */
match subpath_state {
SubpathState::NoSubpath => {
- let (_, outgoing_vx, outgoing_vy) = find_outgoing_directionality_forwards
(&segments, i);
- emit_marker (segment,
- MarkerEndpoint::Start,
- MarkerType::Start,
- angle_from_vector (outgoing_vx, outgoing_vy),
- emit_fn);
+ let (_, outgoing_vx, outgoing_vy) =
+ find_outgoing_directionality_forwards(&segments, i);
+ emit_marker(segment,
+ MarkerEndpoint::Start,
+ MarkerType::Start,
+ angle_from_vector(outgoing_vx, outgoing_vy),
+ emit_fn);
subpath_state = SubpathState::InSubpath;
- },
+ }
SubpathState::InSubpath => {
- assert! (i > 0);
+ assert!(i > 0);
- let (has_incoming, incoming_vx, incoming_vy) =
find_incoming_directionality_backwards (&segments, i - 1);
- let (has_outgoing, outgoing_vx, outgoing_vy) = find_outgoing_directionality_forwards
(&segments, i);
+ let (has_incoming, incoming_vx, incoming_vy) =
+ find_incoming_directionality_backwards(&segments, i - 1);
+ let (has_outgoing, outgoing_vx, outgoing_vy) =
+ find_outgoing_directionality_forwards(&segments, i);
let incoming: f64;
let outgoing: f64;
- incoming = angle_from_vector (incoming_vx, incoming_vy);
- outgoing = angle_from_vector (outgoing_vx, outgoing_vy);
+ incoming = angle_from_vector(incoming_vx, incoming_vy);
+ outgoing = angle_from_vector(outgoing_vx, outgoing_vy);
let angle: f64;
if has_incoming && has_outgoing {
- angle = bisect_angles (incoming, outgoing);
+ angle = bisect_angles(incoming, outgoing);
} else if has_incoming {
angle = incoming;
} else if has_outgoing {
@@ -741,7 +774,11 @@ fn emit_markers_for_path_builder<E> (builder: &RsvgPathBuilder,
angle = 0.0;
}
- emit_marker (segment, MarkerEndpoint::Start, MarkerType::Middle, angle, emit_fn);
+ emit_marker(segment,
+ MarkerEndpoint::Start,
+ MarkerType::Middle,
+ angle,
+ emit_fn);
}
}
}
@@ -752,299 +789,281 @@ fn emit_markers_for_path_builder<E> (builder: &RsvgPathBuilder,
if !segments.is_empty() {
let segment = &segments[segments.len() - 1];
- if let Segment::LineOrCurve{ .. } = *segment {
- let (_, incoming_vx, incoming_vy) = find_incoming_directionality_backwards (&segments,
segments.len () - 1);
+ if let Segment::LineOrCurve { .. } = *segment {
+ let (_, incoming_vx, incoming_vy) =
+ find_incoming_directionality_backwards(&segments, segments.len() - 1);
let angle = {
- if let PathCommand::ClosePath = builder.get_path_commands ()[segments.len()] {
- let (_, outgoing_vx, outgoing_vy) = find_outgoing_directionality_forwards (&segments, 0);
- bisect_angles (angle_from_vector (incoming_vx, incoming_vy), angle_from_vector
(outgoing_vx, outgoing_vy))
+ if let PathCommand::ClosePath = builder.get_path_commands()[segments.len()] {
+ let (_, outgoing_vx, outgoing_vy) =
+ find_outgoing_directionality_forwards(&segments, 0);
+ bisect_angles(angle_from_vector(incoming_vx, incoming_vy),
+ angle_from_vector(outgoing_vx, outgoing_vy))
} else {
- angle_from_vector (incoming_vx, incoming_vy)
+ angle_from_vector(incoming_vx, incoming_vy)
}
};
- emit_marker (segment, MarkerEndpoint::End, MarkerType::End, angle, emit_fn);
+ emit_marker(segment,
+ MarkerEndpoint::End,
+ MarkerType::End,
+ angle,
+ emit_fn);
}
}
}
-/******************** Tests ********************/
+/******************** Tests ******************* * * * * **/
#[cfg(test)]
mod parser_tests {
use super::*;
#[test]
- fn parsing_invalid_marker_units_yields_error () {
- assert! (is_parse_error (&MarkerUnits::parse ("", ()).map_err (|e| AttributeError::from (e))));
- assert! (is_parse_error (&MarkerUnits::parse ("foo", ()).map_err (|e| AttributeError::from (e))));
+ fn parsing_invalid_marker_units_yields_error() {
+ assert!(is_parse_error(&MarkerUnits::parse("", ()).map_err(|e| AttributeError::from(e))));
+ assert!(is_parse_error(&MarkerUnits::parse("foo", ()).map_err(|e| {
+ AttributeError::from(e)
+ })));
}
#[test]
- fn parses_marker_units () {
- assert_eq! (MarkerUnits::parse ("userSpaceOnUse", ()), Ok (MarkerUnits::UserSpaceOnUse));
- assert_eq! (MarkerUnits::parse ("strokeWidth", ()), Ok (MarkerUnits::StrokeWidth));
+ fn parses_marker_units() {
+ assert_eq!(MarkerUnits::parse("userSpaceOnUse", ()),
+ Ok(MarkerUnits::UserSpaceOnUse));
+ assert_eq!(MarkerUnits::parse("strokeWidth", ()),
+ Ok(MarkerUnits::StrokeWidth));
}
#[test]
- fn parsing_invalid_marker_orient_yields_error () {
- assert! (is_parse_error (&MarkerOrient::parse ("", ()).map_err (|e| AttributeError::from (e))));
- assert! (is_parse_error (&MarkerOrient::parse ("blah", ()).map_err (|e| AttributeError::from (e))));
+ fn parsing_invalid_marker_orient_yields_error() {
+ assert!(is_parse_error(&MarkerOrient::parse("", ()).map_err(|e| AttributeError::from(e))));
+ assert!(is_parse_error(&MarkerOrient::parse("blah", ()).map_err(|e| {
+ AttributeError::from(e)
+ })));
assert! (is_parse_error (&MarkerOrient::parse ("45blah", ()).map_err (|e| AttributeError::from
(e))));
}
#[test]
- fn parses_marker_orient () {
- assert_eq! (MarkerOrient::parse ("auto", ()), Ok (MarkerOrient::Auto));
-
- assert_eq! (MarkerOrient::parse ("0", ()), Ok (MarkerOrient::Degrees (0.0)));
- assert_eq! (MarkerOrient::parse ("180", ()), Ok (MarkerOrient::Degrees (180.0)));
- assert_eq! (MarkerOrient::parse ("180deg", ()), Ok (MarkerOrient::Degrees (180.0)));
- assert_eq! (MarkerOrient::parse ("-400grad", ()), Ok (MarkerOrient::Degrees (-360.0)));
- assert_eq! (MarkerOrient::parse ("1rad", ()), Ok (MarkerOrient::Degrees (180.0 / PI)));
+ fn parses_marker_orient() {
+ assert_eq!(MarkerOrient::parse("auto", ()), Ok(MarkerOrient::Auto));
+
+ assert_eq!(MarkerOrient::parse("0", ()), Ok(MarkerOrient::Degrees(0.0)));
+ assert_eq!(MarkerOrient::parse("180", ()),
+ Ok(MarkerOrient::Degrees(180.0)));
+ assert_eq!(MarkerOrient::parse("180deg", ()),
+ Ok(MarkerOrient::Degrees(180.0)));
+ assert_eq!(MarkerOrient::parse("-400grad", ()),
+ Ok(MarkerOrient::Degrees(-360.0)));
+ assert_eq!(MarkerOrient::parse("1rad", ()),
+ Ok(MarkerOrient::Degrees(180.0 / PI)));
}
}
#[cfg(test)]
mod directionality_tests {
- use std::f64::consts::*;
use super::*;
+ use std::f64::consts::*;
- fn test_bisection_angle (expected: f64,
- incoming_vx: f64,
- incoming_vy: f64,
- outgoing_vx: f64,
- outgoing_vy: f64) {
- let bisected = super::bisect_angles (super::angle_from_vector (incoming_vx, incoming_vy),
- super::angle_from_vector (outgoing_vx, outgoing_vy));
- assert! (double_equals (expected, bisected));
+ fn test_bisection_angle(expected: f64,
+ incoming_vx: f64,
+ incoming_vy: f64,
+ outgoing_vx: f64,
+ outgoing_vy: f64) {
+ let bisected = super::bisect_angles(super::angle_from_vector(incoming_vx, incoming_vy),
+ super::angle_from_vector(outgoing_vx, outgoing_vy));
+ assert!(double_equals(expected, bisected));
}
#[test]
- fn bisection_angle_is_correct_from_incoming_counterclockwise_to_outgoing () {
+ fn bisection_angle_is_correct_from_incoming_counterclockwise_to_outgoing() {
// 1st quadrant
- test_bisection_angle (FRAC_PI_4,
- 1.0, 0.0,
- 0.0, 1.0);
+ test_bisection_angle(FRAC_PI_4, 1.0, 0.0, 0.0, 1.0);
// 2nd quadrant
- test_bisection_angle (FRAC_PI_2 + FRAC_PI_4,
- 0.0, 1.0,
- -1.0, 0.0);
+ test_bisection_angle(FRAC_PI_2 + FRAC_PI_4, 0.0, 1.0, -1.0, 0.0);
// 3rd quadrant
- test_bisection_angle (PI + FRAC_PI_4,
- -1.0, 0.0,
- 0.0, -1.0);
+ test_bisection_angle(PI + FRAC_PI_4, -1.0, 0.0, 0.0, -1.0);
// 4th quadrant
- test_bisection_angle (PI + FRAC_PI_2 + FRAC_PI_4,
- 0.0, -1.0,
- 1.0, 0.0);
+ test_bisection_angle(PI + FRAC_PI_2 + FRAC_PI_4, 0.0, -1.0, 1.0, 0.0);
}
#[test]
- fn bisection_angle_is_correct_from_incoming_clockwise_to_outgoing () {
+ fn bisection_angle_is_correct_from_incoming_clockwise_to_outgoing() {
// 1st quadrant
- test_bisection_angle (FRAC_PI_4,
- 0.0, 1.0,
- 1.0, 0.0);
+ test_bisection_angle(FRAC_PI_4, 0.0, 1.0, 1.0, 0.0);
// 2nd quadrant
- test_bisection_angle (FRAC_PI_2 + FRAC_PI_4,
- -1.0, 0.0,
- 0.0, 1.0);
+ test_bisection_angle(FRAC_PI_2 + FRAC_PI_4, -1.0, 0.0, 0.0, 1.0);
// 3rd quadrant
- test_bisection_angle (PI + FRAC_PI_4,
- 0.0, -1.0,
- -1.0, 0.0);
+ test_bisection_angle(PI + FRAC_PI_4, 0.0, -1.0, -1.0, 0.0);
// 4th quadrant
- test_bisection_angle (PI + FRAC_PI_2 + FRAC_PI_4,
- 1.0, 0.0,
- 0.0, -1.0);
+ test_bisection_angle(PI + FRAC_PI_2 + FRAC_PI_4, 1.0, 0.0, 0.0, -1.0);
}
#[test]
- fn bisection_angle_is_correct_for_more_than_quarter_turn_angle () {
- test_bisection_angle (0.0,
- 0.1, -1.0,
- 0.1, 1.0);
-
- test_bisection_angle (FRAC_PI_2,
- 1.0, 0.1,
- -1.0, 0.1);
-
- test_bisection_angle (PI,
- -0.1, 1.0,
- -0.1, -1.0);
-
- test_bisection_angle (PI + FRAC_PI_2,
- -1.0, -0.1,
- 1.0, -0.1);
+ fn bisection_angle_is_correct_for_more_than_quarter_turn_angle() {
+ test_bisection_angle(0.0, 0.1, -1.0, 0.1, 1.0);
+
+ test_bisection_angle(FRAC_PI_2, 1.0, 0.1, -1.0, 0.1);
+
+ test_bisection_angle(PI, -0.1, 1.0, -0.1, -1.0);
+
+ test_bisection_angle(PI + FRAC_PI_2, -1.0, -0.1, 1.0, -0.1);
}
- fn degenerate (x: f64, y: f64) -> Segment {
- super::make_degenerate (x, y)
+ fn degenerate(x: f64, y: f64) -> Segment {
+ super::make_degenerate(x, y)
}
- fn line (x1: f64, y1: f64, x2: f64, y2: f64) -> Segment {
- super::make_line (x1, y1, x2, y2)
+ fn line(x1: f64, y1: f64, x2: f64, y2: f64) -> Segment {
+ super::make_line(x1, y1, x2, y2)
}
- fn curve (x1: f64, y1: f64, x2: f64, y2: f64, x3: f64, y3: f64, x4: f64, y4: f64) -> Segment {
- super::make_curve (x1, y1, x2, y2, x3, y3, x4, y4)
+ fn curve(x1: f64, y1: f64, x2: f64, y2: f64, x3: f64, y3: f64, x4: f64, y4: f64) -> Segment {
+ super::make_curve(x1, y1, x2, y2, x3, y3, x4, y4)
}
- fn test_path_builder_to_segments (builder: &RsvgPathBuilder, expected_segments: Vec<Segment>) {
- let segments = path_builder_to_segments (builder);
- assert_eq! (expected_segments, segments);
+ fn test_path_builder_to_segments(builder: &RsvgPathBuilder, expected_segments: Vec<Segment>) {
+ let segments = path_builder_to_segments(builder);
+ assert_eq!(expected_segments, segments);
}
/* Single open path; the easy case */
- fn setup_open_path () -> RsvgPathBuilder {
- let mut builder = RsvgPathBuilder::new ();
+ fn setup_open_path() -> RsvgPathBuilder {
+ let mut builder = RsvgPathBuilder::new();
- builder.move_to (10.0, 10.0);
- builder.line_to (20.0, 10.0);
- builder.line_to (20.0, 20.0);
+ builder.move_to(10.0, 10.0);
+ builder.line_to(20.0, 10.0);
+ builder.line_to(20.0, 20.0);
builder
}
#[test]
- fn path_to_segments_handles_open_path () {
- let expected_segments: Vec<Segment> = vec![
- line (10.0, 10.0, 20.0, 10.0),
- line (20.0, 10.0, 20.0, 20.0)
- ];
+ fn path_to_segments_handles_open_path() {
+ let expected_segments: Vec<Segment> =
+ vec![line(10.0, 10.0, 20.0, 10.0), line(20.0, 10.0, 20.0, 20.0)];
- test_path_builder_to_segments (&setup_open_path (), expected_segments);
+ test_path_builder_to_segments(&setup_open_path(), expected_segments);
}
/* Multiple open subpaths */
- fn setup_multiple_open_subpaths () -> RsvgPathBuilder {
- let mut builder = RsvgPathBuilder::new ();
+ fn setup_multiple_open_subpaths() -> RsvgPathBuilder {
+ let mut builder = RsvgPathBuilder::new();
- builder.move_to (10.0, 10.0);
- builder.line_to (20.0, 10.0);
- builder.line_to (20.0, 20.0);
+ builder.move_to(10.0, 10.0);
+ builder.line_to(20.0, 10.0);
+ builder.line_to(20.0, 20.0);
- builder.move_to (30.0, 30.0);
- builder.line_to (40.0, 30.0);
- builder.curve_to (50.0, 35.0, 60.0, 60.0, 70.0, 70.0);
- builder.line_to (80.0, 90.0);
+ builder.move_to(30.0, 30.0);
+ builder.line_to(40.0, 30.0);
+ builder.curve_to(50.0, 35.0, 60.0, 60.0, 70.0, 70.0);
+ builder.line_to(80.0, 90.0);
builder
}
#[test]
- fn path_to_segments_handles_multiple_open_subpaths () {
- let expected_segments: Vec<Segment> = vec![
- line (10.0, 10.0, 20.0, 10.0),
- line (20.0, 10.0, 20.0, 20.0),
-
- line (30.0, 30.0, 40.0, 30.0),
- curve (40.0, 30.0, 50.0, 35.0, 60.0, 60.0, 70.0, 70.0),
- line (70.0, 70.0, 80.0, 90.0)
- ];
-
- test_path_builder_to_segments (&setup_multiple_open_subpaths (), expected_segments);
+ fn path_to_segments_handles_multiple_open_subpaths() {
+ let expected_segments: Vec<Segment> =
+ vec![line(10.0, 10.0, 20.0, 10.0),
+ line(20.0, 10.0, 20.0, 20.0),
+ line(30.0, 30.0, 40.0, 30.0),
+ curve(40.0, 30.0, 50.0, 35.0, 60.0, 60.0, 70.0, 70.0),
+ line(70.0, 70.0, 80.0, 90.0)];
+
+ test_path_builder_to_segments(&setup_multiple_open_subpaths(), expected_segments);
}
/* Closed subpath; must have a line segment back to the first point */
- fn setup_closed_subpath () -> RsvgPathBuilder {
- let mut builder = RsvgPathBuilder::new ();
+ fn setup_closed_subpath() -> RsvgPathBuilder {
+ let mut builder = RsvgPathBuilder::new();
- builder.move_to (10.0, 10.0);
- builder.line_to (20.0, 10.0);
- builder.line_to (20.0, 20.0);
- builder.close_path ();
+ builder.move_to(10.0, 10.0);
+ builder.line_to(20.0, 10.0);
+ builder.line_to(20.0, 20.0);
+ builder.close_path();
builder
}
#[test]
- fn path_to_segments_handles_closed_subpath () {
- let expected_segments: Vec<Segment> = vec![
- line (10.0, 10.0, 20.0, 10.0),
- line (20.0, 10.0, 20.0, 20.0),
- line (20.0, 20.0, 10.0, 10.0)
- ];
+ fn path_to_segments_handles_closed_subpath() {
+ let expected_segments: Vec<Segment> = vec![line(10.0, 10.0, 20.0, 10.0),
+ line(20.0, 10.0, 20.0, 20.0),
+ line(20.0, 20.0, 10.0, 10.0)];
- test_path_builder_to_segments (&setup_closed_subpath (), expected_segments);
+ test_path_builder_to_segments(&setup_closed_subpath(), expected_segments);
}
/* Multiple closed subpaths; each must have a line segment back to their
* initial points, with no degenerate segments between subpaths.
*/
- fn setup_multiple_closed_subpaths () -> RsvgPathBuilder {
- let mut builder = RsvgPathBuilder::new ();
+ fn setup_multiple_closed_subpaths() -> RsvgPathBuilder {
+ let mut builder = RsvgPathBuilder::new();
- builder.move_to (10.0, 10.0);
- builder.line_to (20.0, 10.0);
- builder.line_to (20.0, 20.0);
- builder.close_path ();
+ builder.move_to(10.0, 10.0);
+ builder.line_to(20.0, 10.0);
+ builder.line_to(20.0, 20.0);
+ builder.close_path();
- builder.move_to (30.0, 30.0);
- builder.line_to (40.0, 30.0);
- builder.curve_to (50.0, 35.0, 60.0, 60.0, 70.0, 70.0);
- builder.line_to (80.0, 90.0);
- builder.close_path ();
+ builder.move_to(30.0, 30.0);
+ builder.line_to(40.0, 30.0);
+ builder.curve_to(50.0, 35.0, 60.0, 60.0, 70.0, 70.0);
+ builder.line_to(80.0, 90.0);
+ builder.close_path();
builder
}
#[test]
- fn path_to_segments_handles_multiple_closed_subpaths () {
- let expected_segments: Vec<Segment> = vec![
- line (10.0, 10.0, 20.0, 10.0),
- line (20.0, 10.0, 20.0, 20.0),
- line (20.0, 20.0, 10.0, 10.0),
-
- line (30.0, 30.0, 40.0, 30.0),
- curve (40.0, 30.0, 50.0, 35.0, 60.0, 60.0, 70.0, 70.0),
- line (70.0, 70.0, 80.0, 90.0),
- line (80.0, 90.0, 30.0, 30.0)
- ];
-
- test_path_builder_to_segments (&setup_multiple_closed_subpaths (), expected_segments);
+ fn path_to_segments_handles_multiple_closed_subpaths() {
+ let expected_segments: Vec<Segment> =
+ vec![line(10.0, 10.0, 20.0, 10.0),
+ line(20.0, 10.0, 20.0, 20.0),
+ line(20.0, 20.0, 10.0, 10.0),
+ line(30.0, 30.0, 40.0, 30.0),
+ curve(40.0, 30.0, 50.0, 35.0, 60.0, 60.0, 70.0, 70.0),
+ line(70.0, 70.0, 80.0, 90.0),
+ line(80.0, 90.0, 30.0, 30.0)];
+
+ test_path_builder_to_segments(&setup_multiple_closed_subpaths(), expected_segments);
}
- /* A lineto follows the first closed subpath, with no moveto to start the second subpath. The
- * lineto must start at the first point of the first subpath.
+ /* A lineto follows the first closed subpath, with no moveto to start the second subpath.
+ * The lineto must start at the first point of the first subpath.
*/
- fn setup_no_moveto_after_closepath () -> RsvgPathBuilder {
- let mut builder = RsvgPathBuilder::new ();
+ fn setup_no_moveto_after_closepath() -> RsvgPathBuilder {
+ let mut builder = RsvgPathBuilder::new();
- builder.move_to (10.0, 10.0);
- builder.line_to (20.0, 10.0);
- builder.line_to (20.0, 20.0);
- builder.close_path ();
+ builder.move_to(10.0, 10.0);
+ builder.line_to(20.0, 10.0);
+ builder.line_to(20.0, 20.0);
+ builder.close_path();
- builder.line_to (40.0, 30.0);
+ builder.line_to(40.0, 30.0);
builder
}
#[test]
- fn path_to_segments_handles_no_moveto_after_closepath () {
- let expected_segments: Vec<Segment> = vec![
- line (10.0, 10.0, 20.0, 10.0),
- line (20.0, 10.0, 20.0, 20.0),
- line (20.0, 20.0, 10.0, 10.0),
+ fn path_to_segments_handles_no_moveto_after_closepath() {
+ let expected_segments: Vec<Segment> = vec![line(10.0, 10.0, 20.0, 10.0),
+ line(20.0, 10.0, 20.0, 20.0),
+ line(20.0, 20.0, 10.0, 10.0),
+ line(10.0, 10.0, 40.0, 30.0)];
- line (10.0, 10.0, 40.0, 30.0)
- ];
-
- test_path_builder_to_segments (&setup_no_moveto_after_closepath (), expected_segments);
+ test_path_builder_to_segments(&setup_no_moveto_after_closepath(), expected_segments);
}
/* Sequence of moveto; should generate degenerate points.
@@ -1084,77 +1103,78 @@ mod directionality_tests {
*/
#[test]
- fn degenerate_segment_has_no_directionality () {
- assert! (super::get_segment_directionalities (°enerate (1.0, 2.0)).is_none ());
+ fn degenerate_segment_has_no_directionality() {
+ assert!(super::get_segment_directionalities(°enerate(1.0, 2.0)).is_none());
}
#[test]
- fn line_segment_has_directionality () {
- let (v1x, v1y, v2x, v2y) = super::get_segment_directionalities (&line (1.0, 2.0, 3.0, 4.0)).unwrap
();
- assert_eq! ((2.0, 2.0), (v1x, v1y));
- assert_eq! ((2.0, 2.0), (v2x, v2y));
+ fn line_segment_has_directionality() {
+ let (v1x, v1y, v2x, v2y) =
+ super::get_segment_directionalities(&line(1.0, 2.0, 3.0, 4.0)).unwrap();
+ assert_eq!((2.0, 2.0), (v1x, v1y));
+ assert_eq!((2.0, 2.0), (v2x, v2y));
}
#[test]
- fn line_segment_with_coincident_ends_has_no_directionality () {
- assert! (super::get_segment_directionalities (&line (1.0, 2.0, 1.0, 2.0)).is_none ());
+ fn line_segment_with_coincident_ends_has_no_directionality() {
+ assert!(super::get_segment_directionalities(&line(1.0, 2.0, 1.0, 2.0)).is_none());
}
#[test]
- fn curve_has_directionality () {
+ fn curve_has_directionality() {
let (v1x, v1y, v2x, v2y) =
super::get_segment_directionalities (&curve (1.0, 2.0, 3.0, 5.0, 8.0, 13.0, 20.0, 33.0)).unwrap
();
- assert_eq! ((2.0, 3.0), (v1x, v1y));
- assert_eq! ((12.0, 20.0), (v2x, v2y));
+ assert_eq!((2.0, 3.0), (v1x, v1y));
+ assert_eq!((12.0, 20.0), (v2x, v2y));
}
#[test]
- fn curves_with_loops_and_coincident_ends_have_directionality () {
+ fn curves_with_loops_and_coincident_ends_have_directionality() {
let (v1x, v1y, v2x, v2y) =
super::get_segment_directionalities (&curve (1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 1.0, 2.0)).unwrap ();
- assert_eq! ((2.0, 2.0), (v1x, v1y));
- assert_eq! ((-4.0, -4.0), (v2x, v2y));
+ assert_eq!((2.0, 2.0), (v1x, v1y));
+ assert_eq!((-4.0, -4.0), (v2x, v2y));
let (v1x, v1y, v2x, v2y) =
super::get_segment_directionalities (&curve (1.0, 2.0, 1.0, 2.0, 3.0, 4.0, 1.0, 2.0)).unwrap ();
- assert_eq! ((2.0, 2.0), (v1x, v1y));
- assert_eq! ((-2.0, -2.0), (v2x, v2y));
+ assert_eq!((2.0, 2.0), (v1x, v1y));
+ assert_eq!((-2.0, -2.0), (v2x, v2y));
let (v1x, v1y, v2x, v2y) =
super::get_segment_directionalities (&curve (1.0, 2.0, 3.0, 4.0, 1.0, 2.0, 1.0, 2.0)).unwrap ();
- assert_eq! ((2.0, 2.0), (v1x, v1y));
- assert_eq! ((-2.0, -2.0), (v2x, v2y));
+ assert_eq!((2.0, 2.0), (v1x, v1y));
+ assert_eq!((-2.0, -2.0), (v2x, v2y));
}
#[test]
- fn curve_with_coincident_control_points_has_no_directionality () {
+ fn curve_with_coincident_control_points_has_no_directionality() {
assert! (super::get_segment_directionalities (&curve (1.0, 2.0, 1.0, 2.0, 1.0, 2.0, 1.0,
2.0)).is_none ());
}
#[test]
- fn curve_with_123_coincident_has_directionality () {
+ fn curve_with_123_coincident_has_directionality() {
let (v1x, v1y, v2x, v2y) =
super::get_segment_directionalities (&curve (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, 40.0)).unwrap
();
- assert_eq! ((20.0, 40.0), (v1x, v1y));
- assert_eq! ((20.0, 40.0), (v2x, v2y));
+ assert_eq!((20.0, 40.0), (v1x, v1y));
+ assert_eq!((20.0, 40.0), (v2x, v2y));
}
#[test]
- fn curve_with_234_coincident_has_directionality () {
+ fn curve_with_234_coincident_has_directionality() {
let (v1x, v1y, v2x, v2y) =
super::get_segment_directionalities (&curve (20.0, 40.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)).unwrap
();
- assert_eq! ((-20.0, -40.0), (v1x, v1y));
- assert_eq! ((-20.0, -40.0), (v2x, v2y));
+ assert_eq!((-20.0, -40.0), (v1x, v1y));
+ assert_eq!((-20.0, -40.0), (v2x, v2y));
}
#[test]
- fn curve_with_12_34_coincident_has_directionality () {
+ fn curve_with_12_34_coincident_has_directionality() {
let (v1x, v1y, v2x, v2y) =
super::get_segment_directionalities (&curve (20.0, 40.0, 20.0, 40.0, 60.0, 70.0, 60.0,
70.0)).unwrap ();
- assert_eq! ((40.0, 30.0), (v1x, v1y));
- assert_eq! ((40.0, 30.0), (v2x, v2y));
+ assert_eq!((40.0, 30.0), (v1x, v1y));
+ assert_eq!((40.0, 30.0), (v2x, v2y));
}
}
@@ -1163,46 +1183,48 @@ mod marker_tests {
use super::*;
#[test]
- fn emits_for_open_subpath () {
- let mut builder = RsvgPathBuilder::new ();
- builder.move_to (0.0, 0.0);
- builder.line_to (1.0, 0.0);
- builder.line_to (1.0, 1.0);
- builder.line_to (0.0, 1.0);
+ fn emits_for_open_subpath() {
+ let mut builder = RsvgPathBuilder::new();
+ builder.move_to(0.0, 0.0);
+ builder.line_to(1.0, 0.0);
+ builder.line_to(1.0, 1.0);
+ builder.line_to(0.0, 1.0);
- let mut v = Vec::new ();
+ let mut v = Vec::new();
emit_markers_for_path_builder (&builder,
&mut |marker_type: MarkerType, x: f64, y: f64, computed_angle: f64| {
v.push ((marker_type, x, y, computed_angle));
});
- assert_eq! (v, vec! [(MarkerType::Start, 0.0, 0.0, 0.0),
- (MarkerType::Middle, 1.0, 0.0, angle_from_vector (1.0, 1.0)),
- (MarkerType::Middle, 1.0, 1.0, angle_from_vector (-1.0, 1.0)),
- (MarkerType::End, 0.0, 1.0, angle_from_vector (-1.0, 0.0))]);
+ assert_eq!(v,
+ vec![(MarkerType::Start, 0.0, 0.0, 0.0),
+ (MarkerType::Middle, 1.0, 0.0, angle_from_vector(1.0, 1.0)),
+ (MarkerType::Middle, 1.0, 1.0, angle_from_vector(-1.0, 1.0)),
+ (MarkerType::End, 0.0, 1.0, angle_from_vector(-1.0, 0.0))]);
}
#[test]
- fn emits_for_closed_subpath () {
- let mut builder = RsvgPathBuilder::new ();
- builder.move_to (0.0, 0.0);
- builder.line_to (1.0, 0.0);
- builder.line_to (1.0, 1.0);
- builder.line_to (0.0, 1.0);
- builder.close_path ();
+ fn emits_for_closed_subpath() {
+ let mut builder = RsvgPathBuilder::new();
+ builder.move_to(0.0, 0.0);
+ builder.line_to(1.0, 0.0);
+ builder.line_to(1.0, 1.0);
+ builder.line_to(0.0, 1.0);
+ builder.close_path();
- let mut v = Vec::new ();
+ let mut v = Vec::new();
emit_markers_for_path_builder (&builder,
&mut |marker_type: MarkerType, x: f64, y: f64, computed_angle: f64| {
v.push ((marker_type, x, y, computed_angle));
});
- assert_eq! (v, vec! [(MarkerType::Start, 0.0, 0.0, 0.0),
- (MarkerType::Middle, 1.0, 0.0, angle_from_vector (1.0, 1.0)),
- (MarkerType::Middle, 1.0, 1.0, angle_from_vector (-1.0, 1.0)),
- (MarkerType::Middle, 0.0, 1.0, angle_from_vector (-1.0, -1.0)),
- (MarkerType::End, 0.0, 0.0, angle_from_vector (1.0, -1.0))]);
+ assert_eq!(v,
+ vec![(MarkerType::Start, 0.0, 0.0, 0.0),
+ (MarkerType::Middle, 1.0, 0.0, angle_from_vector(1.0, 1.0)),
+ (MarkerType::Middle, 1.0, 1.0, angle_from_vector(-1.0, 1.0)),
+ (MarkerType::Middle, 0.0, 1.0, angle_from_vector(-1.0, -1.0)),
+ (MarkerType::End, 0.0, 0.0, angle_from_vector(1.0, -1.0))]);
}
}
diff --git a/rsvg_internals/src/mask.rs b/rsvg_internals/src/mask.rs
index 81703371..2ea96ca0 100644
--- a/rsvg_internals/src/mask.rs
+++ b/rsvg_internals/src/mask.rs
@@ -5,36 +5,34 @@ use attributes::Attribute;
use coord_units::CoordUnits;
use drawing_ctx::RsvgDrawingCtx;
use handle::RsvgHandle;
-use length::{RsvgLength, LengthDir};
-use node::{NodeResult, NodeTrait, NodeType, RsvgCNodeImpl, RsvgNode, boxed_node_new};
-use parsers::{Parse, parse};
+use length::{LengthDir, RsvgLength};
+use node::{boxed_node_new, NodeResult, NodeTrait, NodeType, RsvgCNodeImpl, RsvgNode};
+use parsers::{parse, Parse};
use property_bag::PropertyBag;
coord_units!(MaskUnits, CoordUnits::ObjectBoundingBox);
coord_units!(MaskContentUnits, CoordUnits::UserSpaceOnUse);
struct NodeMask {
- x: Cell<RsvgLength>,
- y: Cell<RsvgLength>,
- width: Cell<RsvgLength>,
+ x: Cell<RsvgLength>,
+ y: Cell<RsvgLength>,
+ width: Cell<RsvgLength>,
height: Cell<RsvgLength>,
- units: Cell<MaskUnits>,
+ units: Cell<MaskUnits>,
content_units: Cell<MaskContentUnits>,
}
impl NodeMask {
fn new() -> NodeMask {
- NodeMask {
- x: Cell::new(NodeMask::get_default_pos(LengthDir::Horizontal)),
- y: Cell::new(NodeMask::get_default_pos(LengthDir::Vertical)),
+ NodeMask { x: Cell::new(NodeMask::get_default_pos(LengthDir::Horizontal)),
+ y: Cell::new(NodeMask::get_default_pos(LengthDir::Vertical)),
- width: Cell::new(NodeMask::get_default_size(LengthDir::Horizontal)),
- height: Cell::new(NodeMask::get_default_size(LengthDir::Vertical)),
+ width: Cell::new(NodeMask::get_default_size(LengthDir::Horizontal)),
+ height: Cell::new(NodeMask::get_default_size(LengthDir::Vertical)),
- units: Cell::new(MaskUnits::default()),
- content_units: Cell::new(MaskContentUnits::default())
- }
+ units: Cell::new(MaskUnits::default()),
+ content_units: Cell::new(MaskContentUnits::default()), }
}
fn get_default_pos(dir: LengthDir) -> RsvgLength {
@@ -50,18 +48,26 @@ impl NodeTrait for NodeMask {
fn set_atts(&self, _: &RsvgNode, _: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
for (_key, attr, value) in pbag.iter() {
match attr {
- Attribute::X => self.x.set(parse("x", value, LengthDir::Horizontal, None)?),
- Attribute::Y => self.y.set(parse("y", value, LengthDir::Vertical, None)?),
- Attribute::Width => self.width.set(parse("width", value, LengthDir::Horizontal,
- Some(RsvgLength::check_nonnegative))?),
- Attribute::Height => self.height.set(parse("height", value, LengthDir::Vertical,
- Some(RsvgLength::check_nonnegative))?),
-
- Attribute::MaskUnits =>
- self.units.set(parse("maskUnits", value, (), None)?),
-
- Attribute::MaskContentUnits =>
- self.content_units.set(parse("maskContentUnits", value, (), None)?),
+ Attribute::X => self.x.set(parse("x", value, LengthDir::Horizontal, None)?),
+ Attribute::Y => self.y.set(parse("y", value, LengthDir::Vertical, None)?),
+ Attribute::Width => {
+ self.width.set(parse("width",
+ value,
+ LengthDir::Horizontal,
+ Some(RsvgLength::check_nonnegative))?)
+ }
+ Attribute::Height => {
+ self.height.set(parse("height",
+ value,
+ LengthDir::Vertical,
+ Some(RsvgLength::check_nonnegative))?)
+ }
+
+ Attribute::MaskUnits => self.units.set(parse("maskUnits", value, (), None)?),
+
+ Attribute::MaskContentUnits => {
+ self.content_units.set(parse("maskContentUnits", value, (), None)?)
+ }
_ => (),
}
@@ -80,92 +86,92 @@ impl NodeTrait for NodeMask {
}
#[no_mangle]
-pub extern fn rsvg_node_mask_new(_: *const libc::c_char, raw_parent: *const RsvgNode) -> *const RsvgNode {
- boxed_node_new(NodeType::Mask,
- raw_parent,
- Box::new(NodeMask::new()))
+pub extern "C" fn rsvg_node_mask_new(_: *const libc::c_char,
+ raw_parent: *const RsvgNode)
+ -> *const RsvgNode {
+ boxed_node_new(NodeType::Mask, raw_parent, Box::new(NodeMask::new()))
}
#[no_mangle]
-pub extern fn rsvg_node_mask_get_x(raw_node: *const RsvgNode) -> RsvgLength {
- assert! (!raw_node.is_null ());
- let node: &RsvgNode = unsafe { & *raw_node };
+pub extern "C" fn rsvg_node_mask_get_x(raw_node: *const RsvgNode) -> RsvgLength {
+ assert!(!raw_node.is_null());
+ let node: &RsvgNode = unsafe { &*raw_node };
let mut v = RsvgLength::default();
node.with_impl(|mask: &NodeMask| {
- v = mask.x.get();
- });
+ v = mask.x.get();
+ });
v
}
#[no_mangle]
-pub extern fn rsvg_node_mask_get_y(raw_node: *const RsvgNode) -> RsvgLength {
- assert! (!raw_node.is_null ());
- let node: &RsvgNode = unsafe { & *raw_node };
+pub extern "C" fn rsvg_node_mask_get_y(raw_node: *const RsvgNode) -> RsvgLength {
+ assert!(!raw_node.is_null());
+ let node: &RsvgNode = unsafe { &*raw_node };
let mut v = RsvgLength::default();
node.with_impl(|mask: &NodeMask| {
- v = mask.y.get();
- });
+ v = mask.y.get();
+ });
v
}
#[no_mangle]
-pub extern fn rsvg_node_mask_get_width(raw_node: *const RsvgNode) -> RsvgLength {
- assert! (!raw_node.is_null ());
- let node: &RsvgNode = unsafe { & *raw_node };
+pub extern "C" fn rsvg_node_mask_get_width(raw_node: *const RsvgNode) -> RsvgLength {
+ assert!(!raw_node.is_null());
+ let node: &RsvgNode = unsafe { &*raw_node };
let mut v = RsvgLength::default();
node.with_impl(|mask: &NodeMask| {
- v = mask.width.get();
- });
+ v = mask.width.get();
+ });
v
}
#[no_mangle]
-pub extern fn rsvg_node_mask_get_height(raw_node: *const RsvgNode) -> RsvgLength {
- assert! (!raw_node.is_null ());
- let node: &RsvgNode = unsafe { & *raw_node };
+pub extern "C" fn rsvg_node_mask_get_height(raw_node: *const RsvgNode) -> RsvgLength {
+ assert!(!raw_node.is_null());
+ let node: &RsvgNode = unsafe { &*raw_node };
let mut v = RsvgLength::default();
node.with_impl(|mask: &NodeMask| {
- v = mask.height.get();
- });
+ v = mask.height.get();
+ });
v
}
#[no_mangle]
-pub extern fn rsvg_node_mask_get_units(raw_node: *const RsvgNode) -> CoordUnits {
- assert! (!raw_node.is_null ());
- let node: &RsvgNode = unsafe { & *raw_node };
+pub extern "C" fn rsvg_node_mask_get_units(raw_node: *const RsvgNode) -> CoordUnits {
+ assert!(!raw_node.is_null());
+ let node: &RsvgNode = unsafe { &*raw_node };
let mut units = MaskUnits::default();
node.with_impl(|mask: &NodeMask| {
- units = mask.units.get();
- });
+ units = mask.units.get();
+ });
CoordUnits::from(units)
}
#[no_mangle]
-pub extern fn rsvg_node_mask_get_content_units(raw_node: *const RsvgNode) -> CoordUnits {
- assert! (!raw_node.is_null ());
- let node: &RsvgNode = unsafe { & *raw_node };
+pub extern "C" fn rsvg_node_mask_get_content_units(raw_node: *const RsvgNode) -> CoordUnits {
+ assert!(!raw_node.is_null());
+ let node: &RsvgNode = unsafe { &*raw_node };
let mut units = MaskContentUnits::default();
node.with_impl(|mask: &NodeMask| {
- units = mask.content_units.get();
- });
+ units = mask.content_units.get();
+ });
CoordUnits::from(units)
}
diff --git a/rsvg_internals/src/node.rs b/rsvg_internals/src/node.rs
index 16718157..397ba301 100644
--- a/rsvg_internals/src/node.rs
+++ b/rsvg_internals/src/node.rs
@@ -1,14 +1,14 @@
use downcast_rs::*;
-use glib_sys;
use glib::translate::*;
+use glib_sys;
use libc;
-use std::rc::{Rc, Weak};
use std::cell::RefCell;
use std::ptr;
+use std::rc::{Rc, Weak};
-use drawing_ctx::RsvgDrawingCtx;
use drawing_ctx;
+use drawing_ctx::RsvgDrawingCtx;
use error::*;
use handle::RsvgHandle;
use parsers::ParseError;
@@ -27,12 +27,16 @@ pub type RsvgNode = Rc<Node>;
pub enum RsvgCNodeImpl {}
pub trait NodeTrait: Downcast {
- fn set_atts (&self, node: &RsvgNode, handle: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult;
- fn draw (&self, node: &RsvgNode, draw_ctx: *const RsvgDrawingCtx, dominate: i32);
- fn get_c_impl (&self) -> *const RsvgCNodeImpl;
+ fn set_atts(&self,
+ node: &RsvgNode,
+ handle: *const RsvgHandle,
+ pbag: &PropertyBag)
+ -> NodeResult;
+ fn draw(&self, node: &RsvgNode, draw_ctx: *const RsvgDrawingCtx, dominate: i32);
+ fn get_c_impl(&self) -> *const RsvgCNodeImpl;
}
-impl_downcast! (NodeTrait);
+impl_downcast!(NodeTrait);
// After creating/parsing a Node, it will be in a success or an error state.
// We represent this with a Result, aliased as a NodeResult. There is no
@@ -58,11 +62,11 @@ pub type NodeResult = Result<(), NodeError>;
pub struct Node {
node_type: NodeType,
- parent: Option<Weak<Node>>, // optional; weak ref to parent
- children: RefCell<Vec<Rc<Node>>>, // strong references to children
- state: *mut RsvgState,
- result: RefCell <NodeResult>,
- node_impl: Box<NodeTrait>
+ parent: Option<Weak<Node>>, // optional; weak ref to parent
+ children: RefCell<Vec<Rc<Node>>>, // strong references to children
+ state: *mut RsvgState,
+ result: RefCell<NodeResult>,
+ node_impl: Box<NodeTrait>,
}
/* Keep this in sync with rsvg-private.h:RsvgNodeType */
@@ -102,7 +106,7 @@ pub enum NodeType {
Use,
/* Filter primitives */
- FilterPrimitiveFirst, /* just a marker; not a valid type */
+ FilterPrimitiveFirst, /* just a marker; not a valid type */
FilterPrimitiveBlend,
FilterPrimitiveColorMatrix,
FilterPrimitiveComponentTransfer,
@@ -120,106 +124,105 @@ pub enum NodeType {
FilterPrimitiveSpecularLighting,
FilterPrimitiveTile,
FilterPrimitiveTurbulence,
- FilterPrimitiveLast /* just a marker; not a valid type */
+ FilterPrimitiveLast, /* just a marker; not a valid type */
}
impl Node {
- pub fn new (node_type: NodeType,
- parent: Option<Weak<Node>>,
- state: *mut RsvgState,
- node_impl: Box<NodeTrait>) -> Node {
- Node {
- node_type: node_type,
- parent: parent,
- children: RefCell::new (Vec::new ()),
- state: state,
- result: RefCell::new (Ok (())),
- node_impl: node_impl
- }
+ pub fn new(node_type: NodeType,
+ parent: Option<Weak<Node>>,
+ state: *mut RsvgState,
+ node_impl: Box<NodeTrait>)
+ -> Node {
+ Node { node_type,
+ parent,
+ children: RefCell::new(Vec::new()),
+ state,
+ result: RefCell::new(Ok(())),
+ node_impl, }
}
- pub fn get_type (&self) -> NodeType {
+ pub fn get_type(&self) -> NodeType {
self.node_type
}
- pub fn get_state (&self) -> *mut RsvgState {
+ pub fn get_state(&self) -> *mut RsvgState {
self.state
}
- pub fn get_parent (&self) -> Option<Rc<Node>> {
+ pub fn get_parent(&self) -> Option<Rc<Node>> {
match self.parent {
None => None,
- Some (ref weak_node) => Some (weak_node.upgrade ().unwrap ())
+ Some(ref weak_node) => Some(weak_node.upgrade().unwrap()),
}
}
- pub fn is_ancestor (ancestor: Rc<Node>, descendant: Rc<Node>) -> bool {
- let mut desc = Some (descendant.clone ());
+ pub fn is_ancestor(ancestor: Rc<Node>, descendant: Rc<Node>) -> bool {
+ let mut desc = Some(descendant.clone());
- while let Some (ref d) = desc.clone () {
- if rc_node_ptr_eq (&ancestor, d) {
+ while let Some(ref d) = desc.clone() {
+ if rc_node_ptr_eq(&ancestor, d) {
return true;
}
- desc = d.get_parent ();
+ desc = d.get_parent();
}
false
}
- pub fn add_child (&self, child: &Rc<Node>) {
- self.children.borrow_mut ().push (child.clone ());
+ pub fn add_child(&self, child: &Rc<Node>) {
+ self.children.borrow_mut().push(child.clone());
}
- pub fn set_atts (&self, node: &RsvgNode, handle: *const RsvgHandle, pbag: &PropertyBag) {
- *self.result.borrow_mut () = self.node_impl.set_atts (node, handle, pbag);
+ pub fn set_atts(&self, node: &RsvgNode, handle: *const RsvgHandle, pbag: &PropertyBag) {
+ *self.result.borrow_mut() = self.node_impl.set_atts(node, handle, pbag);
}
- pub fn draw (&self, node: &RsvgNode, draw_ctx: *const RsvgDrawingCtx, dominate: i32) {
- if self.result.borrow ().is_ok () {
- self.node_impl.draw (node, draw_ctx, dominate);
+ pub fn draw(&self, node: &RsvgNode, draw_ctx: *const RsvgDrawingCtx, dominate: i32) {
+ if self.result.borrow().is_ok() {
+ self.node_impl.draw(node, draw_ctx, dominate);
}
}
- pub fn set_error (&self, error: NodeError) {
- *self.result.borrow_mut () = Err (error);
+ pub fn set_error(&self, error: NodeError) {
+ *self.result.borrow_mut() = Err(error);
}
- pub fn get_result (&self) -> NodeResult {
- self.result.borrow ().clone ()
+ pub fn get_result(&self) -> NodeResult {
+ self.result.borrow().clone()
}
- pub fn get_c_impl (&self) -> *const RsvgCNodeImpl {
- self.node_impl.get_c_impl ()
+ pub fn get_c_impl(&self) -> *const RsvgCNodeImpl {
+ self.node_impl.get_c_impl()
}
- pub fn with_impl<T: NodeTrait, F: FnOnce (&T)> (&self, f: F) {
- if let Some (t) = (&self.node_impl).downcast_ref::<T> () {
- f (t);
+ pub fn with_impl<T: NodeTrait, F: FnOnce(&T)>(&self, f: F) {
+ if let Some(t) = (&self.node_impl).downcast_ref::<T>() {
+ f(t);
} else {
- panic! ("could not downcast");
+ panic!("could not downcast");
}
}
- pub fn draw_children (&self, draw_ctx: *const RsvgDrawingCtx, dominate: i32) {
+ pub fn draw_children(&self, draw_ctx: *const RsvgDrawingCtx, dominate: i32) {
if dominate != -1 {
- drawing_ctx::state_reinherit_top (draw_ctx, self.state, dominate);
+ drawing_ctx::state_reinherit_top(draw_ctx, self.state, dominate);
- drawing_ctx::push_discrete_layer (draw_ctx);
+ drawing_ctx::push_discrete_layer(draw_ctx);
}
self.foreach_child(|child| {
- let boxed_child = box_node (child.clone ());
+ let boxed_child = box_node(child.clone());
- drawing_ctx::draw_node_from_stack (draw_ctx, boxed_child, 0);
+ drawing_ctx::draw_node_from_stack(draw_ctx, boxed_child, 0);
- rsvg_node_unref (boxed_child);
+ rsvg_node_unref(boxed_child);
- true
- });
+ true
+ });
if dominate != -1 {
- drawing_ctx::pop_discrete_layer (draw_ctx);
+ drawing_ctx::pop_discrete_layer(draw_ctx);
}
}
@@ -245,151 +248,154 @@ impl Node {
// states; we only create stub nodes with ptr::null() for state.
#[cfg(not(test))]
impl Drop for Node {
-
- fn drop (&mut self) {
+ fn drop(&mut self) {
extern "C" {
- fn rsvg_state_free (state: *mut RsvgState);
+ fn rsvg_state_free(state: *mut RsvgState);
+ }
+ unsafe {
+ rsvg_state_free(self.state);
}
- unsafe { rsvg_state_free (self.state); }
}
}
-pub fn node_ptr_to_weak (raw_parent: *const RsvgNode) -> Option<Weak<Node>> {
- if raw_parent.is_null () {
+pub fn node_ptr_to_weak(raw_parent: *const RsvgNode) -> Option<Weak<Node>> {
+ if raw_parent.is_null() {
None
} else {
- let p: &RsvgNode = unsafe { & *raw_parent };
- Some (Rc::downgrade (&p.clone ()))
+ let p: &RsvgNode = unsafe { &*raw_parent };
+ Some(Rc::downgrade(&p.clone()))
}
}
-pub fn boxed_node_new (node_type: NodeType,
- raw_parent: *const RsvgNode,
- node_impl: Box<NodeTrait>) -> *mut RsvgNode {
- box_node (Rc::new (Node::new (node_type,
- node_ptr_to_weak (raw_parent),
- drawing_ctx::state_new (),
- node_impl)))
+pub fn boxed_node_new(node_type: NodeType,
+ raw_parent: *const RsvgNode,
+ node_impl: Box<NodeTrait>)
+ -> *mut RsvgNode {
+ box_node(Rc::new(Node::new(node_type,
+ node_ptr_to_weak(raw_parent),
+ drawing_ctx::state_new(),
+ node_impl)))
}
#[no_mangle]
-pub extern fn rsvg_node_get_type (raw_node: *const RsvgNode) -> NodeType {
- assert! (!raw_node.is_null ());
- let node: &RsvgNode = unsafe { & *raw_node };
+pub extern "C" fn rsvg_node_get_type(raw_node: *const RsvgNode) -> NodeType {
+ assert!(!raw_node.is_null());
+ let node: &RsvgNode = unsafe { &*raw_node };
- node.get_type ()
+ node.get_type()
}
-pub fn box_node (node: RsvgNode) -> *mut RsvgNode {
- Box::into_raw (Box::new (node))
+pub fn box_node(node: RsvgNode) -> *mut RsvgNode {
+ Box::into_raw(Box::new(node))
}
#[no_mangle]
-pub extern fn rsvg_node_get_parent (raw_node: *const RsvgNode) -> *const RsvgNode {
- assert! (!raw_node.is_null ());
- let node: &RsvgNode = unsafe { & *raw_node };
+pub extern "C" fn rsvg_node_get_parent(raw_node: *const RsvgNode) -> *const RsvgNode {
+ assert!(!raw_node.is_null());
+ let node: &RsvgNode = unsafe { &*raw_node };
- match node.get_parent () {
- None => { ptr::null () }
+ match node.get_parent() {
+ None => ptr::null(),
- Some (node) => {
- box_node (node)
- }
+ Some(node) => box_node(node),
}
}
#[no_mangle]
-pub extern fn rsvg_node_ref (raw_node: *mut RsvgNode) -> *mut RsvgNode {
- assert! (!raw_node.is_null ());
- let node: &RsvgNode = unsafe { & *raw_node };
+pub extern "C" fn rsvg_node_ref(raw_node: *mut RsvgNode) -> *mut RsvgNode {
+ assert!(!raw_node.is_null());
+ let node: &RsvgNode = unsafe { &*raw_node };
- box_node (node.clone ())
+ box_node(node.clone())
}
#[no_mangle]
-pub extern fn rsvg_node_unref (raw_node: *mut RsvgNode) -> *mut RsvgNode {
- if !raw_node.is_null () {
- let _ = unsafe { Box::from_raw (raw_node) };
+pub extern "C" fn rsvg_node_unref(raw_node: *mut RsvgNode) -> *mut RsvgNode {
+ if !raw_node.is_null() {
+ let _ = unsafe { Box::from_raw(raw_node) };
}
- ptr::null_mut () // so the caller can do "node = rsvg_node_unref (node);" and lose access to the node
+ ptr::null_mut() // so the caller can do "node = rsvg_node_unref (node);" and lose access to the node
}
// See https://github.com/rust-lang/rust/issues/36497 - this is what
// added Rc::ptr_eq(), but we don't want to depend on unstable Rust
// just yet.
-fn rc_node_ptr_eq<T: ?Sized> (this: &Rc<T>, other: &Rc<T>) -> bool {
+fn rc_node_ptr_eq<T: ?Sized>(this: &Rc<T>, other: &Rc<T>) -> bool {
let this_ptr: *const T = &**this;
let other_ptr: *const T = &**other;
this_ptr == other_ptr
}
#[no_mangle]
-pub extern fn rsvg_node_is_same (raw_node1: *const RsvgNode, raw_node2: *const RsvgNode) ->
glib_sys::gboolean {
- let is_same = if raw_node1.is_null () && raw_node2.is_null () {
+pub extern "C" fn rsvg_node_is_same(raw_node1: *const RsvgNode,
+ raw_node2: *const RsvgNode)
+ -> glib_sys::gboolean {
+ let is_same = if raw_node1.is_null() && raw_node2.is_null() {
true
- } else if !raw_node1.is_null () && !raw_node2.is_null () {
- let node1: &RsvgNode = unsafe { & *raw_node1 };
- let node2: &RsvgNode = unsafe { & *raw_node2 };
+ } else if !raw_node1.is_null() && !raw_node2.is_null() {
+ let node1: &RsvgNode = unsafe { &*raw_node1 };
+ let node2: &RsvgNode = unsafe { &*raw_node2 };
- rc_node_ptr_eq (node1, node2)
+ rc_node_ptr_eq(node1, node2)
} else {
false
};
- is_same.to_glib ()
+ is_same.to_glib()
}
#[no_mangle]
-pub extern fn rsvg_node_get_state (raw_node: *const RsvgNode) -> *mut RsvgState {
- assert! (!raw_node.is_null ());
- let node: &RsvgNode = unsafe { & *raw_node };
+pub extern "C" fn rsvg_node_get_state(raw_node: *const RsvgNode) -> *mut RsvgState {
+ assert!(!raw_node.is_null());
+ let node: &RsvgNode = unsafe { &*raw_node };
- node.get_state ()
+ node.get_state()
}
#[no_mangle]
-pub extern fn rsvg_node_add_child (raw_node: *mut RsvgNode, raw_child: *const RsvgNode) {
- assert! (!raw_node.is_null ());
- assert! (!raw_child.is_null ());
+pub extern "C" fn rsvg_node_add_child(raw_node: *mut RsvgNode, raw_child: *const RsvgNode) {
+ assert!(!raw_node.is_null());
+ assert!(!raw_child.is_null());
let node: &mut RsvgNode = unsafe { &mut *raw_node };
- let child: &RsvgNode = unsafe { & *raw_child };
+ let child: &RsvgNode = unsafe { &*raw_child };
- node.add_child (child);
+ node.add_child(child);
}
#[no_mangle]
-pub extern fn rsvg_node_set_atts (raw_node: *mut RsvgNode,
- handle: *const RsvgHandle,
- pbag: *const PropertyBag) {
+pub extern "C" fn rsvg_node_set_atts(raw_node: *mut RsvgNode,
+ handle: *const RsvgHandle,
+ pbag: *const PropertyBag) {
assert!(!raw_node.is_null());
assert!(!pbag.is_null());
- let node: &RsvgNode = unsafe { & *raw_node };
+ let node: &RsvgNode = unsafe { &*raw_node };
let pbag = unsafe { &*pbag };
node.set_atts(node, handle, &pbag);
}
#[no_mangle]
-pub extern fn rsvg_node_draw (raw_node: *const RsvgNode, draw_ctx: *const RsvgDrawingCtx, dominate: i32) {
- assert! (!raw_node.is_null ());
- let node: &RsvgNode = unsafe { & *raw_node };
+pub extern "C" fn rsvg_node_draw(raw_node: *const RsvgNode,
+ draw_ctx: *const RsvgDrawingCtx,
+ dominate: i32) {
+ assert!(!raw_node.is_null());
+ let node: &RsvgNode = unsafe { &*raw_node };
- node.draw (node, draw_ctx, dominate);
+ node.draw(node, draw_ctx, dominate);
}
#[no_mangle]
-pub extern fn rsvg_node_set_attribute_parse_error (raw_node: *const RsvgNode,
- attr_name: *const libc::c_char,
- description: *const libc::c_char)
-{
- assert! (!raw_node.is_null ());
- let node: &RsvgNode = unsafe { & *raw_node };
+pub extern "C" fn rsvg_node_set_attribute_parse_error(raw_node: *const RsvgNode,
+ attr_name: *const libc::c_char,
+ description: *const libc::c_char) {
+ assert!(!raw_node.is_null());
+ let node: &RsvgNode = unsafe { &*raw_node };
- assert! (!attr_name.is_null ());
- assert! (!description.is_null ());
+ assert!(!attr_name.is_null());
+ assert!(!description.is_null());
unsafe {
node.set_error (NodeError::parse_error (&String::from_glib_none (attr_name),
@@ -397,142 +403,145 @@ pub extern fn rsvg_node_set_attribute_parse_error (raw_node: *const RsvgNode,
}
}
-type NodeForeachChild = unsafe extern "C" fn (node: *const RsvgNode, data: *const libc::c_void) ->
glib_sys::gboolean;
+type NodeForeachChild =
+ unsafe extern "C" fn(node: *const RsvgNode, data: *const libc::c_void) -> glib_sys::gboolean;
#[no_mangle]
-pub extern fn rsvg_node_foreach_child (raw_node: *const RsvgNode, func: NodeForeachChild, data: *const
libc::c_void)
-{
- assert! (!raw_node.is_null ());
- let node: &RsvgNode = unsafe { & *raw_node };
+pub extern "C" fn rsvg_node_foreach_child(raw_node: *const RsvgNode,
+ func: NodeForeachChild,
+ data: *const libc::c_void) {
+ assert!(!raw_node.is_null());
+ let node: &RsvgNode = unsafe { &*raw_node };
node.foreach_child(|child| {
- let boxed_child = box_node (child.clone ());
+ let boxed_child = box_node(child.clone());
- let next: bool = unsafe { from_glib (func (boxed_child, data)) };
+ let next: bool = unsafe { from_glib(func(boxed_child, data)) };
- rsvg_node_unref (boxed_child);
+ rsvg_node_unref(boxed_child);
- next
- });
+ next
+ });
}
#[no_mangle]
-pub extern fn rsvg_node_draw_children (raw_node: *const RsvgNode, draw_ctx: *const RsvgDrawingCtx, dominate:
i32) {
- assert! (!raw_node.is_null ());
- let node: &RsvgNode = unsafe { & *raw_node };
+pub extern "C" fn rsvg_node_draw_children(raw_node: *const RsvgNode,
+ draw_ctx: *const RsvgDrawingCtx,
+ dominate: i32) {
+ assert!(!raw_node.is_null());
+ let node: &RsvgNode = unsafe { &*raw_node };
- node.draw_children (draw_ctx, dominate);
+ node.draw_children(draw_ctx, dominate);
}
#[cfg(test)]
mod tests {
- use std::rc::Rc;
+ use super::*;
use drawing_ctx::RsvgDrawingCtx;
use handle::RsvgHandle;
- use super::*;
use std::ptr;
+ use std::rc::Rc;
struct TestNodeImpl {}
impl NodeTrait for TestNodeImpl {
- fn set_atts (&self, _: &RsvgNode, _: *const RsvgHandle, _: &PropertyBag) -> NodeResult {
- Ok (())
+ fn set_atts(&self, _: &RsvgNode, _: *const RsvgHandle, _: &PropertyBag) -> NodeResult {
+ Ok(())
}
- fn draw (&self, _: &RsvgNode, _: *const RsvgDrawingCtx, _: i32) {
- }
+ fn draw(&self, _: &RsvgNode, _: *const RsvgDrawingCtx, _: i32) {}
- fn get_c_impl (&self) -> *const RsvgCNodeImpl {
- unreachable! ();
+ fn get_c_impl(&self) -> *const RsvgCNodeImpl {
+ unreachable!();
}
}
#[test]
- fn node_refs_and_unrefs () {
- let node = Rc::new (Node::new (NodeType::Path,
- None,
- ptr::null_mut (),
- Box::new (TestNodeImpl {})));
+ fn node_refs_and_unrefs() {
+ let node = Rc::new(Node::new(NodeType::Path,
+ None,
+ ptr::null_mut(),
+ Box::new(TestNodeImpl {})));
- let ref1 = box_node (node);
+ let ref1 = box_node(node);
let new_node: &mut RsvgNode = unsafe { &mut *ref1 };
- let weak = Rc::downgrade (new_node);
+ let weak = Rc::downgrade(new_node);
- let ref2 = rsvg_node_ref (new_node);
- assert! (weak.upgrade ().is_some ());
+ let ref2 = rsvg_node_ref(new_node);
+ assert!(weak.upgrade().is_some());
- rsvg_node_unref (ref2);
- assert! (weak.upgrade ().is_some ());
+ rsvg_node_unref(ref2);
+ assert!(weak.upgrade().is_some());
- rsvg_node_unref (ref1);
- assert! (weak.upgrade ().is_none ());
+ rsvg_node_unref(ref1);
+ assert!(weak.upgrade().is_none());
}
#[test]
- fn reffed_node_is_same_as_original_node () {
- let node = Rc::new (Node::new (NodeType::Path,
- None,
- ptr::null_mut (),
- Box::new (TestNodeImpl {})));
+ fn reffed_node_is_same_as_original_node() {
+ let node = Rc::new(Node::new(NodeType::Path,
+ None,
+ ptr::null_mut(),
+ Box::new(TestNodeImpl {})));
- let ref1 = box_node (node);
+ let ref1 = box_node(node);
- let ref2 = rsvg_node_ref (ref1);
+ let ref2 = rsvg_node_ref(ref1);
- assert! (rsvg_node_is_same (ref1, ref2) == true.to_glib ());
+ assert!(rsvg_node_is_same(ref1, ref2) == true.to_glib());
- rsvg_node_unref (ref1);
- rsvg_node_unref (ref2);
+ rsvg_node_unref(ref1);
+ rsvg_node_unref(ref2);
}
#[test]
- fn different_nodes_have_different_pointers () {
- let node1 = Rc::new (Node::new (NodeType::Path,
- None,
- ptr::null_mut (),
- Box::new (TestNodeImpl {})));
+ fn different_nodes_have_different_pointers() {
+ let node1 = Rc::new(Node::new(NodeType::Path,
+ None,
+ ptr::null_mut(),
+ Box::new(TestNodeImpl {})));
- let ref1 = box_node (node1);
+ let ref1 = box_node(node1);
- let node2 = Rc::new (Node::new (NodeType::Path,
- None,
- ptr::null_mut (),
- Box::new (TestNodeImpl {})));
+ let node2 = Rc::new(Node::new(NodeType::Path,
+ None,
+ ptr::null_mut(),
+ Box::new(TestNodeImpl {})));
- let ref2 = box_node (node2);
+ let ref2 = box_node(node2);
- assert! (rsvg_node_is_same (ref1, ref2) == false.to_glib ());
+ assert!(rsvg_node_is_same(ref1, ref2) == false.to_glib());
- rsvg_node_unref (ref1);
- rsvg_node_unref (ref2);
+ rsvg_node_unref(ref1);
+ rsvg_node_unref(ref2);
}
#[test]
- fn node_is_its_own_ancestor () {
- let node = Rc::new (Node::new (NodeType::Path,
- None,
- ptr::null_mut (),
- Box::new (TestNodeImpl {})));
+ fn node_is_its_own_ancestor() {
+ let node = Rc::new(Node::new(NodeType::Path,
+ None,
+ ptr::null_mut(),
+ Box::new(TestNodeImpl {})));
- assert! (Node::is_ancestor (node.clone (), node.clone ()));
+ assert!(Node::is_ancestor(node.clone(), node.clone()));
}
#[test]
- fn node_is_ancestor_of_child () {
- let node = Rc::new (Node::new (NodeType::Path,
- None,
- ptr::null_mut (),
- Box::new (TestNodeImpl {})));
+ fn node_is_ancestor_of_child() {
+ let node = Rc::new(Node::new(NodeType::Path,
+ None,
+ ptr::null_mut(),
+ Box::new(TestNodeImpl {})));
- let child = Rc::new (Node::new (NodeType::Path,
- Some (Rc::downgrade (&node)),
- ptr::null_mut (),
- Box::new (TestNodeImpl {})));
+ let child = Rc::new(Node::new(NodeType::Path,
+ Some(Rc::downgrade(&node)),
+ ptr::null_mut(),
+ Box::new(TestNodeImpl {})));
- node.add_child (&child);
+ node.add_child(&child);
- assert! (Node::is_ancestor (node.clone (), child.clone ()));
- assert! (!Node::is_ancestor (child.clone (), node.clone ()));
+ assert!(Node::is_ancestor(node.clone(), child.clone()));
+ assert!(!Node::is_ancestor(child.clone(), node.clone()));
}
}
diff --git a/rsvg_internals/src/opacity.rs b/rsvg_internals/src/opacity.rs
index 8a6bffb2..9e1248ee 100644
--- a/rsvg_internals/src/opacity.rs
+++ b/rsvg_internals/src/opacity.rs
@@ -1,13 +1,12 @@
/// Struct to represent an inheritable opacity property
/// <https://www.w3.org/TR/SVG/masking.html#OpacityProperty>
-
use cssparser::{Parser, ParserInput, Token};
use libc;
use std::str::FromStr;
-use parsers::ParseError;
use error::*;
+use parsers::ParseError;
use util::utf8_cstr;
// Keep this in sync with rsvg-css.h:RsvgOpacityKind
@@ -16,7 +15,7 @@ use util::utf8_cstr;
pub enum OpacityKind {
Inherit,
Specified,
- ParseError
+ ParseError,
}
// Keep this in sync with rsvg-css.h:RsvgOpacitySpec
@@ -24,102 +23,101 @@ pub enum OpacityKind {
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct OpacitySpec {
kind: OpacityKind,
- opacity: u8
+ opacity: u8,
}
// This is the Rust version of the above
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Opacity {
Inherit,
- Specified (f64)
+ Specified(f64),
}
impl From<Result<Opacity, AttributeError>> for OpacitySpec {
- fn from (result: Result<Opacity, AttributeError>) -> OpacitySpec {
+ fn from(result: Result<Opacity, AttributeError>) -> OpacitySpec {
match result {
- Ok (Opacity::Inherit) =>
- OpacitySpec {
- kind: OpacityKind::Inherit,
- opacity: 0
- },
-
- Ok (Opacity::Specified (val)) =>
- OpacitySpec {
- kind: OpacityKind::Specified,
- opacity: opacity_to_u8 (val)
- },
-
- _ =>
- OpacitySpec {
- kind: OpacityKind::ParseError,
- opacity: 0
- }
+ Ok(Opacity::Inherit) => {
+ OpacitySpec { kind: OpacityKind::Inherit,
+ opacity: 0, }
+ }
+
+ Ok(Opacity::Specified(val)) => {
+ OpacitySpec { kind: OpacityKind::Specified,
+ opacity: opacity_to_u8(val), }
+ }
+
+ _ => {
+ OpacitySpec { kind: OpacityKind::ParseError,
+ opacity: 0, }
+ }
}
}
}
-pub fn opacity_to_u8 (val: f64) -> u8 {
- (val * 255.0 + 0.5).floor () as u8
+pub fn opacity_to_u8(val: f64) -> u8 {
+ (val * 255.0 + 0.5).floor() as u8
}
-fn make_err () -> AttributeError {
- AttributeError::Parse (ParseError::new ("expected 'inherit' or number"))
+fn make_err() -> AttributeError {
+ AttributeError::Parse(ParseError::new("expected 'inherit' or number"))
}
impl FromStr for Opacity {
type Err = AttributeError;
- fn from_str (s: &str) -> Result<Opacity, AttributeError> {
- let mut input = ParserInput::new (s);
- let mut parser = Parser::new (&mut input);
+ fn from_str(s: &str) -> Result<Opacity, AttributeError> {
+ let mut input = ParserInput::new(s);
+ let mut parser = Parser::new(&mut input);
let opacity = {
- let token = parser.next ()
- .map_err (|_| make_err ())?;
+ let token = parser.next().map_err(|_| make_err())?;
match *token {
- Token::Ident (ref cow) => {
- if cow.as_ref () == "inherit" {
+ Token::Ident(ref cow) => {
+ if cow.as_ref() == "inherit" {
Opacity::Inherit
} else {
- return Err (make_err ());
+ return Err(make_err());
}
- },
+ }
Token::Number { value, .. } => {
if value < 0.0 {
- Opacity::Specified (0.0)
+ Opacity::Specified(0.0)
} else if value > 1.0 {
- Opacity::Specified (1.0)
+ Opacity::Specified(1.0)
} else {
- Opacity::Specified (f64::from(value))
+ Opacity::Specified(f64::from(value))
}
- },
+ }
- _ => return Err (make_err ())
+ _ => return Err(make_err()),
}
};
- parser.expect_exhausted ().map_err (|_| make_err ())?;
+ parser.expect_exhausted().map_err(|_| make_err())?;
- Ok (opacity)
+ Ok(opacity)
}
}
impl Opacity {
- pub fn from_opacity_spec (spec: &OpacitySpec) -> Result <Opacity, AttributeError> {
+ pub fn from_opacity_spec(spec: &OpacitySpec) -> Result<Opacity, AttributeError> {
match *spec {
- OpacitySpec { kind: OpacityKind::Inherit, .. } => Ok (Opacity::Inherit),
+ OpacitySpec { kind: OpacityKind::Inherit,
+ .. } => Ok(Opacity::Inherit),
- OpacitySpec { kind: OpacityKind::Specified, opacity } => Ok (Opacity::Specified
(f64::from(opacity) / 255.0)),
+ OpacitySpec { kind: OpacityKind::Specified,
+ opacity, } => Ok(Opacity::Specified(f64::from(opacity) / 255.0)),
- OpacitySpec { kind: OpacityKind::ParseError, .. } => Err (AttributeError::Parse (ParseError::new
("parse error")))
+ OpacitySpec { kind: OpacityKind::ParseError,
+ .. } => Err(AttributeError::Parse(ParseError::new("parse error"))),
}
}
}
#[no_mangle]
-pub extern fn rsvg_css_parse_opacity (string: *const libc::c_char) -> OpacitySpec {
+pub extern "C" fn rsvg_css_parse_opacity(string: *const libc::c_char) -> OpacitySpec {
let s = unsafe { utf8_cstr(string) };
OpacitySpec::from(Opacity::from_str(s))
@@ -128,79 +126,79 @@ pub extern fn rsvg_css_parse_opacity (string: *const libc::c_char) -> OpacitySpe
#[cfg(test)]
mod tests {
use super::*;
- use std::str::FromStr;
use glib::translate::*;
+ use std::str::FromStr;
#[test]
- fn parses_inherit () {
- assert_eq! (Opacity::from_str ("inherit"), Ok (Opacity::Inherit));
+ fn parses_inherit() {
+ assert_eq!(Opacity::from_str("inherit"), Ok(Opacity::Inherit));
}
#[test]
- fn parses_number () {
- assert_eq! (Opacity::from_str ("0"), Ok (Opacity::Specified (0.0)));
- assert_eq! (Opacity::from_str ("1"), Ok (Opacity::Specified (1.0)));
- assert_eq! (Opacity::from_str ("0.5"), Ok (Opacity::Specified (0.5)));
+ fn parses_number() {
+ assert_eq!(Opacity::from_str("0"), Ok(Opacity::Specified(0.0)));
+ assert_eq!(Opacity::from_str("1"), Ok(Opacity::Specified(1.0)));
+ assert_eq!(Opacity::from_str("0.5"), Ok(Opacity::Specified(0.5)));
}
#[test]
- fn parses_out_of_range_number () {
- assert_eq! (Opacity::from_str ("-10"), Ok (Opacity::Specified (0.0)));
- assert_eq! (Opacity::from_str ("10"), Ok (Opacity::Specified (1.0)));
+ fn parses_out_of_range_number() {
+ assert_eq!(Opacity::from_str("-10"), Ok(Opacity::Specified(0.0)));
+ assert_eq!(Opacity::from_str("10"), Ok(Opacity::Specified(1.0)));
}
#[test]
- fn errors_on_invalid_input () {
- assert! (is_parse_error (&Opacity::from_str ("")));
- assert! (is_parse_error (&Opacity::from_str ("foo")));
- assert! (is_parse_error (&Opacity::from_str ("-x")));
+ fn errors_on_invalid_input() {
+ assert!(is_parse_error(&Opacity::from_str("")));
+ assert!(is_parse_error(&Opacity::from_str("foo")));
+ assert!(is_parse_error(&Opacity::from_str("-x")));
}
#[test]
- fn errors_on_extra_input () {
- assert! (is_parse_error (&Opacity::from_str ("inherit a million dollars")));
- assert! (is_parse_error (&Opacity::from_str ("0.0foo")));
+ fn errors_on_extra_input() {
+ assert!(is_parse_error(&Opacity::from_str("inherit a million dollars")));
+ assert!(is_parse_error(&Opacity::from_str("0.0foo")));
}
- fn parse (s: &str) -> OpacitySpec {
- rsvg_css_parse_opacity (s.to_glib_none ().0)
+ fn parse(s: &str) -> OpacitySpec {
+ rsvg_css_parse_opacity(s.to_glib_none().0)
}
#[test]
- fn converts_result_to_opacity_spec () {
- assert_eq! (parse ("inherit"),
- OpacitySpec { kind: OpacityKind::Inherit,
- opacity: 0 });
-
- assert_eq! (parse ("0"),
- OpacitySpec { kind: OpacityKind::Specified,
- opacity: 0 });
- assert_eq! (parse ("1"),
- OpacitySpec { kind: OpacityKind::Specified,
- opacity: 255 });
-
- assert_eq! (parse ("foo"),
- OpacitySpec { kind: OpacityKind::ParseError,
- opacity: 0 });
+ fn converts_result_to_opacity_spec() {
+ assert_eq!(parse("inherit"),
+ OpacitySpec { kind: OpacityKind::Inherit,
+ opacity: 0, });
+
+ assert_eq!(parse("0"),
+ OpacitySpec { kind: OpacityKind::Specified,
+ opacity: 0, });
+ assert_eq!(parse("1"),
+ OpacitySpec { kind: OpacityKind::Specified,
+ opacity: 255, });
+
+ assert_eq!(parse("foo"),
+ OpacitySpec { kind: OpacityKind::ParseError,
+ opacity: 0, });
}
- fn test_roundtrip (s: &str) {
- let result = Opacity::from_str (s);
- let result2 = result.clone ();
- let spec = OpacitySpec::from (result2);
+ fn test_roundtrip(s: &str) {
+ let result = Opacity::from_str(s);
+ let result2 = result.clone();
+ let spec = OpacitySpec::from(result2);
- if result.is_ok () {
- assert_eq! (Opacity::from_opacity_spec (&spec), result);
+ if result.is_ok() {
+ assert_eq!(Opacity::from_opacity_spec(&spec), result);
} else {
- assert! (Opacity::from_opacity_spec (&spec).is_err ());
+ assert!(Opacity::from_opacity_spec(&spec).is_err());
}
}
#[test]
- fn roundtrips () {
- test_roundtrip ("inherit");
- test_roundtrip ("0");
- test_roundtrip ("1.0");
- test_roundtrip ("chilaquil");
+ fn roundtrips() {
+ test_roundtrip("inherit");
+ test_roundtrip("0");
+ test_roundtrip("1.0");
+ test_roundtrip("chilaquil");
}
}
diff --git a/rsvg_internals/src/paint_server.rs b/rsvg_internals/src/paint_server.rs
index a3b654d3..07d23d7d 100644
--- a/rsvg_internals/src/paint_server.rs
+++ b/rsvg_internals/src/paint_server.rs
@@ -1,11 +1,11 @@
use cairo;
use cssparser;
-use glib_sys;
use glib::translate::*;
+use glib_sys;
use libc;
-use std::rc::Rc;
use std::ptr;
+use std::rc::Rc;
use bbox::RsvgBbox;
use color::Color;
@@ -18,25 +18,29 @@ use pattern;
use util::utf8_cstr;
#[derive(Debug, Copy, Clone, PartialEq)]
-pub struct PaintServerSpread (pub cairo::enums::Extend);
+pub struct PaintServerSpread(pub cairo::enums::Extend);
impl Parse for PaintServerSpread {
type Data = ();
type Err = AttributeError;
- fn parse (s: &str, _: ()) -> Result <PaintServerSpread, AttributeError> {
+ fn parse(s: &str, _: ()) -> Result<PaintServerSpread, AttributeError> {
match s {
- "pad" => Ok (PaintServerSpread (cairo::enums::Extend::Pad)),
- "reflect" => Ok (PaintServerSpread (cairo::enums::Extend::Reflect)),
- "repeat" => Ok (PaintServerSpread (cairo::enums::Extend::Repeat)),
- _ => Err (AttributeError::Parse (ParseError::new ("expected 'pad' | 'reflect' |
'repeat'")))
+ "pad" => Ok(PaintServerSpread(cairo::enums::Extend::Pad)),
+ "reflect" => Ok(PaintServerSpread(cairo::enums::Extend::Reflect)),
+ "repeat" => Ok(PaintServerSpread(cairo::enums::Extend::Repeat)),
+ _ => {
+ Err(AttributeError::Parse(ParseError::new("expected 'pad' | \
+ 'reflect' | \
+ 'repeat'")))
+ }
}
}
}
impl Default for PaintServerSpread {
- fn default () -> PaintServerSpread {
- PaintServerSpread (cairo::enums::Extend::Pad)
+ fn default() -> PaintServerSpread {
+ PaintServerSpread(cairo::enums::Extend::Pad)
}
}
@@ -50,14 +54,11 @@ pub enum PaintServer {
}
impl PaintServer {
- pub fn parse_input<'i, 't>(
- input: &mut cssparser::Parser<'i, 't>,
- ) -> Result<Self, AttributeError> {
+ pub fn parse_input<'i, 't>(input: &mut cssparser::Parser<'i, 't>)
+ -> Result<Self, AttributeError> {
if let Ok(url) = input.try(|i| i.expect_url()) {
- Ok(PaintServer::Iri {
- iri: String::from(url.as_ref()),
- alternate: PaintServer::parse_fallback(input),
- })
+ Ok(PaintServer::Iri { iri: String::from(url.as_ref()),
+ alternate: PaintServer::parse_fallback(input), })
} else {
PaintServer::parse_color(input).map(PaintServer::SolidColor)
}
@@ -66,25 +67,28 @@ impl PaintServer {
fn parse_color<'i, 't>(input: &mut cssparser::Parser<'i, 't>) -> Result<Color, AttributeError> {
if input.try(|i| i.expect_ident_matching("inherit")).is_ok() {
Ok(Color::Inherit)
- } else if input.try(|i| i.expect_ident_matching("currentColor")).is_ok() {
+ } else if input.try(|i| i.expect_ident_matching("currentColor"))
+ .is_ok()
+ {
Ok(Color::CurrentColor)
} else {
- input
- .try(|i| cssparser::Color::parse(i))
- .map(Color::from)
- .map_err(AttributeError::from)
+ input.try(|i| cssparser::Color::parse(i))
+ .map(Color::from)
+ .map_err(AttributeError::from)
}
}
fn parse_fallback<'i, 't>(input: &mut cssparser::Parser<'i, 't>) -> Option<Color> {
if input.try(|i| i.expect_ident_matching("none")).is_ok() {
None
- } else if input.try(|i| i.expect_ident_matching("currentColor")).is_ok() {
+ } else if input.try(|i| i.expect_ident_matching("currentColor"))
+ .is_ok()
+ {
Some(Color::CurrentColor)
} else {
- input.try(|i| cssparser::Color::parse(i)).ok().map(|i| {
- Color::from(i)
- })
+ input.try(|i| cssparser::Color::parse(i))
+ .ok()
+ .map(|i| Color::from(i))
}
}
}
@@ -99,32 +103,29 @@ impl Parse for PaintServer {
}
}
-fn _set_source_rsvg_solid_color(
- ctx: *mut drawing_ctx::RsvgDrawingCtx,
- color: &Color,
- opacity: u8,
- current_color: u32,
-) {
+fn _set_source_rsvg_solid_color(ctx: *mut drawing_ctx::RsvgDrawingCtx,
+ color: &Color,
+ opacity: u8,
+ current_color: u32) {
let rgba_color = match *color {
- Color::RGBA(rgba) => Some(rgba),
+ Color::RGBA(rgba) => Some(rgba),
Color::CurrentColor => {
if let Color::RGBA(rgba) = Color::from(current_color) {
Some(rgba)
} else {
None
}
- },
+ }
- _ => None
+ _ => None,
};
if let Some(rgba) = rgba_color {
- drawing_ctx::get_cairo_context(ctx).set_source_rgba(
- f64::from(rgba.red_f32()),
- f64::from(rgba.green_f32()),
- f64::from(rgba.blue_f32()),
- f64::from(rgba.alpha_f32()) * (f64::from(opacity) / 255.0)
- );
+ drawing_ctx::get_cairo_context(ctx).set_source_rgba(f64::from(rgba.red_f32()),
+ f64::from(rgba.green_f32()),
+ f64::from(rgba.blue_f32()),
+ f64::from(rgba.alpha_f32())
+ * (f64::from(opacity) / 255.0));
}
}
@@ -135,11 +136,9 @@ fn _set_source_rsvg_solid_color(
///
/// * `str` - The SVG paint specification string to parse.
#[no_mangle]
-pub extern "C" fn rsvg_paint_server_parse(
- inherit: *mut glib_sys::gboolean,
- str: *const libc::c_char,
-) -> *const PaintServer {
-
+pub extern "C" fn rsvg_paint_server_parse(inherit: *mut glib_sys::gboolean,
+ str: *const libc::c_char)
+ -> *const PaintServer {
if !inherit.is_null() {
unsafe {
*inherit = true.to_glib();
@@ -157,14 +156,15 @@ pub extern "C" fn rsvg_paint_server_parse(
}
}
- *color = Color::RGBA(
- cssparser::RGBA{red: 0, green: 0, blue: 0, alpha: 255}
- );
+ *color = Color::RGBA(cssparser::RGBA { red: 0,
+ green: 0,
+ blue: 0,
+ alpha: 255, });
}
}
match paint_server {
- Ok(m) => Rc::into_raw(Rc::new(m)),
+ Ok(m) => Rc::into_raw(Rc::new(m)),
Err(_) => ptr::null_mut(),
}
}
@@ -203,13 +203,12 @@ pub extern "C" fn rsvg_paint_server_unref(paint_server: *const PaintServer) {
}
#[no_mangle]
-pub extern "C" fn _set_source_rsvg_paint_server(
- c_ctx: *mut drawing_ctx::RsvgDrawingCtx,
- c_ps: *const PaintServer,
- opacity: u8,
- c_bbox: RsvgBbox,
- current_color: u32,
-) -> glib_sys::gboolean {
+pub extern "C" fn _set_source_rsvg_paint_server(c_ctx: *mut drawing_ctx::RsvgDrawingCtx,
+ c_ps: *const PaintServer,
+ opacity: u8,
+ c_bbox: RsvgBbox,
+ current_color: u32)
+ -> glib_sys::gboolean {
assert!(!c_ctx.is_null());
assert!(!c_ps.is_null());
@@ -217,41 +216,37 @@ pub extern "C" fn _set_source_rsvg_paint_server(
let mut had_paint_server = false;
match *ps {
- PaintServer::Iri {
- ref iri,
- ref alternate,
- } => {
+ PaintServer::Iri { ref iri,
+ ref alternate, } => {
let node_ptr = drawing_ctx::acquire_node(c_ctx, iri.as_str());
if !node_ptr.is_null() {
let node = unsafe { &*node_ptr };
- if node.get_type() == NodeType::LinearGradient ||
- node.get_type() == NodeType::RadialGradient
+ if node.get_type() == NodeType::LinearGradient
+ || node.get_type() == NodeType::RadialGradient
{
- had_paint_server = gradient::gradient_resolve_fallbacks_and_set_pattern(
- node,
- c_ctx,
- opacity,
- &c_bbox,
- );
+ had_paint_server =
+ gradient::gradient_resolve_fallbacks_and_set_pattern(node,
+ c_ctx,
+ opacity,
+ &c_bbox);
} else if node.get_type() == NodeType::Pattern {
- had_paint_server = pattern::pattern_resolve_fallbacks_and_set_pattern(node, c_ctx,
&c_bbox);
+ had_paint_server =
+ pattern::pattern_resolve_fallbacks_and_set_pattern(node, c_ctx, &c_bbox);
}
}
if !had_paint_server && alternate.is_some() {
- _set_source_rsvg_solid_color(
- c_ctx,
- alternate.as_ref().unwrap(),
- opacity,
- current_color,
- );
+ _set_source_rsvg_solid_color(c_ctx,
+ alternate.as_ref().unwrap(),
+ opacity,
+ current_color);
had_paint_server = true;
}
drawing_ctx::release_node(c_ctx, node_ptr);
- },
+ }
PaintServer::SolidColor(color) => {
_set_source_rsvg_solid_color(c_ctx, &color, opacity, current_color);
@@ -267,86 +262,56 @@ mod tests {
use super::*;
#[test]
- fn parses_spread_method () {
- assert_eq! (PaintServerSpread::parse ("pad", ()),
- Ok (PaintServerSpread (cairo::enums::Extend::Pad)));
+ fn parses_spread_method() {
+ assert_eq!(PaintServerSpread::parse("pad", ()),
+ Ok(PaintServerSpread(cairo::enums::Extend::Pad)));
- assert_eq! (PaintServerSpread::parse ("reflect", ()),
- Ok (PaintServerSpread (cairo::enums::Extend::Reflect)));
+ assert_eq!(PaintServerSpread::parse("reflect", ()),
+ Ok(PaintServerSpread(cairo::enums::Extend::Reflect)));
- assert_eq! (PaintServerSpread::parse ("repeat", ()),
- Ok (PaintServerSpread (cairo::enums::Extend::Repeat)));
+ assert_eq!(PaintServerSpread::parse("repeat", ()),
+ Ok(PaintServerSpread(cairo::enums::Extend::Repeat)));
- assert! (PaintServerSpread::parse ("foobar", ()).is_err ());
+ assert!(PaintServerSpread::parse("foobar", ()).is_err());
}
#[test]
fn parses_solid_color() {
- assert_eq!(
- PaintServer::parse("rgb(255, 128, 64, 0.5)", ()),
- Ok(PaintServer::SolidColor(Color::from(0x80ff8040)))
- );
-
- assert_eq!(
- PaintServer::parse("inherit", ()),
- Ok(PaintServer::SolidColor(Color::Inherit))
- );
-
- assert_eq!(
- PaintServer::parse("currentColor", ()),
- Ok(PaintServer::SolidColor(Color::CurrentColor))
- );
+ assert_eq!(PaintServer::parse("rgb(255, 128, 64, 0.5)", ()),
+ Ok(PaintServer::SolidColor(Color::from(0x80ff8040))));
+
+ assert_eq!(PaintServer::parse("inherit", ()),
+ Ok(PaintServer::SolidColor(Color::Inherit)));
+
+ assert_eq!(PaintServer::parse("currentColor", ()),
+ Ok(PaintServer::SolidColor(Color::CurrentColor)));
}
#[test]
fn parses_iri() {
- assert_eq!(
- PaintServer::parse("url(#link)", ()),
- Ok(PaintServer::Iri {
- iri: "#link".to_string(),
- alternate: None,
- })
- );
-
- assert_eq!(
- PaintServer::parse("url(#link) none", ()),
- Ok(PaintServer::Iri {
- iri: "#link".to_string(),
- alternate: None,
- })
- );
-
- assert_eq!(
- PaintServer::parse("url(#link) #ff8040", ()),
- Ok(PaintServer::Iri {
- iri: "#link".to_string(),
- alternate: Some(Color::from(0xffff8040)),
- })
- );
-
- assert_eq!(
- PaintServer::parse("url(#link) rgb(255, 128, 64, 0.5)", ()),
- Ok(PaintServer::Iri {
- iri: "#link".to_string(),
- alternate: Some(Color::from(0x80ff8040)),
- })
- );
-
- assert_eq!(
- PaintServer::parse("url(#link) currentColor", ()),
- Ok(PaintServer::Iri {
- iri: "#link".to_string(),
- alternate: Some(Color::CurrentColor),
- })
- );
-
- assert_eq!(
- PaintServer::parse("url(#link) inherit", ()),
- Ok(PaintServer::Iri {
- iri: "#link".to_string(),
- alternate: None,
- })
- );
+ assert_eq!(PaintServer::parse("url(#link)", ()),
+ Ok(PaintServer::Iri { iri: "#link".to_string(),
+ alternate: None, }));
+
+ assert_eq!(PaintServer::parse("url(#link) none", ()),
+ Ok(PaintServer::Iri { iri: "#link".to_string(),
+ alternate: None, }));
+
+ assert_eq!(PaintServer::parse("url(#link) #ff8040", ()),
+ Ok(PaintServer::Iri { iri: "#link".to_string(),
+ alternate: Some(Color::from(0xffff8040)), }));
+
+ assert_eq!(PaintServer::parse("url(#link) rgb(255, 128, 64, 0.5)", ()),
+ Ok(PaintServer::Iri { iri: "#link".to_string(),
+ alternate: Some(Color::from(0x80ff8040)), }));
+
+ assert_eq!(PaintServer::parse("url(#link) currentColor", ()),
+ Ok(PaintServer::Iri { iri: "#link".to_string(),
+ alternate: Some(Color::CurrentColor), }));
+
+ assert_eq!(PaintServer::parse("url(#link) inherit", ()),
+ Ok(PaintServer::Iri { iri: "#link".to_string(),
+ alternate: None, }));
}
#[test]
diff --git a/rsvg_internals/src/parsers.rs b/rsvg_internals/src/parsers.rs
index 36a7f991..e2bae5a4 100644
--- a/rsvg_internals/src/parsers.rs
+++ b/rsvg_internals/src/parsers.rs
@@ -1,7 +1,7 @@
-use libc;
-use cssparser::{Parser, ParserInput, Token, BasicParseError};
+use cssparser::{BasicParseError, Parser, ParserInput, Token};
use glib::translate::*;
use glib_sys;
+use libc;
use std::f64::consts::*;
use std::mem;
@@ -14,18 +14,18 @@ use util::utf8_cstr;
#[derive(Debug, Clone, PartialEq)]
pub struct ParseError {
- pub display: String
+ pub display: String,
}
impl ParseError {
- pub fn new<T: AsRef<str>> (msg: T) -> ParseError {
- ParseError { display: msg.as_ref ().to_string () }
+ pub fn new<T: AsRef<str>>(msg: T) -> ParseError {
+ ParseError { display: msg.as_ref().to_string(), }
}
}
impl<'a> From<BasicParseError<'a>> for ParseError {
- fn from (_: BasicParseError) -> ParseError {
- ParseError::new ("parse error")
+ fn from(_: BasicParseError) -> ParseError {
+ ParseError::new("parse error")
}
}
@@ -33,7 +33,7 @@ pub trait Parse: Sized {
type Data;
type Err;
- fn parse (s: &str, data: Self::Data) -> Result<Self, Self::Err>;
+ fn parse(s: &str, data: Self::Data) -> Result<Self, Self::Err>;
}
/// Parses a `value` string into a type `T` with an optional validation function.
@@ -46,17 +46,18 @@ pub trait Parse: Sized {
pub fn parse<T>(key: &str,
value: &str,
data: <T as Parse>::Data,
- validate: Option<fn(T) -> Result<T, AttributeError>>) -> Result <T, NodeError>
+ validate: Option<fn(T) -> Result<T, AttributeError>>)
+ -> Result<T, NodeError>
where T: Parse<Err = AttributeError> + Copy
{
- T::parse (value, data)
- .and_then (|v|
- if let Some(validate) = validate {
- validate(v)
- } else {
- Ok(v)
- })
- .map_err (|e| NodeError::attribute_error (key, e))
+ T::parse(value, data).and_then(|v| {
+ if let Some(validate) = validate {
+ validate(v)
+ } else {
+ Ok(v)
+ }
+ })
+ .map_err(|e| NodeError::attribute_error(key, e))
}
// angle:
@@ -66,13 +67,13 @@ pub fn parse<T>(key: &str,
//
// Returns an f64 angle in degrees
-pub fn angle_degrees (s: &str) -> Result <f64, ParseError> {
- let mut input = ParserInput::new (s);
- let mut parser = Parser::new (&mut input);
+pub fn angle_degrees(s: &str) -> Result<f64, ParseError> {
+ let mut input = ParserInput::new(s);
+ let mut parser = Parser::new(&mut input);
let angle = {
- let token = parser.next ()
- .map_err (|_| ParseError::new ("expected angle"))?;
+ let token = parser.next()
+ .map_err(|_| ParseError::new("expected angle"))?;
match *token {
Token::Number { value, .. } => f64::from(value),
@@ -80,158 +81,165 @@ pub fn angle_degrees (s: &str) -> Result <f64, ParseError> {
Token::Dimension { value, ref unit, .. } => {
let value = f64::from(value);
- match unit.as_ref () {
- "deg" => value,
+ match unit.as_ref() {
+ "deg" => value,
"grad" => value * 360.0 / 400.0,
- "rad" => value * 180.0 / PI,
- _ => return Err (ParseError::new ("expected 'deg' | 'grad' | 'rad'"))
+ "rad" => value * 180.0 / PI,
+ _ => return Err(ParseError::new("expected 'deg' | 'grad' | 'rad'")),
}
- },
+ }
- _ => return Err (ParseError::new ("expected angle"))
+ _ => return Err(ParseError::new("expected angle")),
}
};
- parser.expect_exhausted ().map_err (|_| ParseError::new ("expected angle"))?;
+ parser.expect_exhausted()
+ .map_err(|_| ParseError::new("expected angle"))?;
- Ok (angle)
+ Ok(angle)
}
-pub fn optional_comma (parser: &mut Parser) {
- let _ = parser.try (|p| p.expect_comma ());
+pub fn optional_comma(parser: &mut Parser) {
+ let _ = parser.try(|p| p.expect_comma());
}
-
// number-optional-number
//
// https://www.w3.org/TR/SVG/types.html#DataTypeNumberOptionalNumber
-pub fn number_optional_number (s: &str) -> Result <(f64, f64), ParseError> {
- let mut input = ParserInput::new (s);
- let mut parser = Parser::new (&mut input);
+pub fn number_optional_number(s: &str) -> Result<(f64, f64), ParseError> {
+ let mut input = ParserInput::new(s);
+ let mut parser = Parser::new(&mut input);
- let x = f64::from(parser.expect_number ()?);
+ let x = f64::from(parser.expect_number()?);
- if !parser.is_exhausted () {
- let state = parser.state ();
+ if !parser.is_exhausted() {
+ let state = parser.state();
- match *parser.next ()? {
- Token::Comma => {},
- _ => parser.reset (&state)
+ match *parser.next()? {
+ Token::Comma => {}
+ _ => parser.reset(&state),
};
- let y = f64::from(parser.expect_number ()?);
+ let y = f64::from(parser.expect_number()?);
- parser.expect_exhausted ()?;
+ parser.expect_exhausted()?;
- Ok ((x, y))
+ Ok((x, y))
} else {
- Ok ((x, x))
+ Ok((x, x))
}
}
#[no_mangle]
-pub extern fn rsvg_css_parse_number_optional_number (s: *const libc::c_char,
- out_x: *mut f64,
- out_y: *mut f64) -> glib_sys::gboolean {
- assert! (!s.is_null ());
- assert! (!out_x.is_null ());
- assert! (!out_y.is_null ());
+pub extern "C" fn rsvg_css_parse_number_optional_number(s: *const libc::c_char,
+ out_x: *mut f64,
+ out_y: *mut f64)
+ -> glib_sys::gboolean {
+ assert!(!s.is_null());
+ assert!(!out_x.is_null());
+ assert!(!out_y.is_null());
let string = unsafe { utf8_cstr(s) };
- match number_optional_number (string) {
- Ok ((x, y)) => {
+ match number_optional_number(string) {
+ Ok((x, y)) => {
unsafe {
*out_x = x;
*out_y = y;
}
true
- },
+ }
- Err (_) => {
+ Err(_) => {
unsafe {
*out_x = 0.0;
*out_y = 0.0;
}
false
}
- }.to_glib ()
+ }.to_glib()
}
-
// Parse a list-of-points as for polyline and polygon elements
// https://www.w3.org/TR/SVG/shapes.html#PointsBNF
-pub fn list_of_points (string: &str) -> Result <Vec<(f64, f64)>, ParseError> {
- let mut input = ParserInput::new (string);
- let mut parser = Parser::new (&mut input);
+pub fn list_of_points(string: &str) -> Result<Vec<(f64, f64)>, ParseError> {
+ let mut input = ParserInput::new(string);
+ let mut parser = Parser::new(&mut input);
- let mut v = Vec::new ();
+ let mut v = Vec::new();
loop {
- let x = f64::from(parser.expect_number ()?);
+ let x = f64::from(parser.expect_number()?);
- optional_comma (&mut parser);
+ optional_comma(&mut parser);
- let y = f64::from(parser.expect_number ()?);
+ let y = f64::from(parser.expect_number()?);
- v.push ((x, y));
+ v.push((x, y));
- if parser.is_exhausted () {
+ if parser.is_exhausted() {
break;
}
- match parser.next_including_whitespace () {
- Ok (&Token::WhiteSpace(_)) => (),
- _ => optional_comma (&mut parser)
+ match parser.next_including_whitespace() {
+ Ok(&Token::WhiteSpace(_)) => (),
+ _ => optional_comma(&mut parser),
}
}
- Ok (v)
+ Ok(v)
}
// Lists of number values
pub enum ListLength {
- Exact (usize),
- Maximum (usize)
+ Exact(usize),
+ Maximum(usize),
}
#[derive(Debug, PartialEq)]
pub enum NumberListError {
IncorrectNumberOfElements,
- Parse (ParseError)
+ Parse(ParseError),
}
-pub fn number_list (s: &str, length: ListLength) -> Result <Vec<f64>, NumberListError> {
+pub fn number_list(s: &str, length: ListLength) -> Result<Vec<f64>, NumberListError> {
let n;
match length {
- ListLength::Exact (l) => { assert! (l > 0); n = l; }
- ListLength::Maximum (l) => { assert! (l > 0); n = l; }
+ ListLength::Exact(l) => {
+ assert!(l > 0);
+ n = l;
+ }
+ ListLength::Maximum(l) => {
+ assert!(l > 0);
+ n = l;
+ }
}
- let mut input = ParserInput::new (s);
- let mut parser = Parser::new (&mut input);
+ let mut input = ParserInput::new(s);
+ let mut parser = Parser::new(&mut input);
- let mut v = Vec::<f64>::with_capacity (n);
+ let mut v = Vec::<f64>::with_capacity(n);
for i in 0..n {
v.push (f64::from(parser.expect_number ().map_err (|_| NumberListError::Parse (ParseError::new
("expected number")))?));
if i != n - 1 {
- optional_comma (&mut parser);
+ optional_comma(&mut parser);
}
- if parser.is_exhausted () {
- if let ListLength::Maximum (_) = length {
+ if parser.is_exhausted() {
+ if let ListLength::Maximum(_) = length {
break;
}
}
}
- parser.expect_exhausted ().map_err (|_| NumberListError::IncorrectNumberOfElements)?;
+ parser.expect_exhausted()
+ .map_err(|_| NumberListError::IncorrectNumberOfElements)?;
Ok(v)
}
@@ -240,41 +248,41 @@ pub fn number_list (s: &str, length: ListLength) -> Result <Vec<f64>, NumberList
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum NumberListLength {
Exact,
- Maximum
+ Maximum,
}
#[no_mangle]
-pub extern fn rsvg_css_parse_number_list (in_str: *const libc::c_char,
- nlength: NumberListLength,
- size: libc::size_t,
- out_list: *mut *const libc::c_double,
- out_list_length: *mut libc::size_t) -> glib_sys::gboolean {
- assert! (!in_str.is_null ());
- assert! (!out_list.is_null ());
- assert! (!out_list_length.is_null ());
+pub extern "C" fn rsvg_css_parse_number_list(in_str: *const libc::c_char,
+ nlength: NumberListLength,
+ size: libc::size_t,
+ out_list: *mut *const libc::c_double,
+ out_list_length: *mut libc::size_t)
+ -> glib_sys::gboolean {
+ assert!(!in_str.is_null());
+ assert!(!out_list.is_null());
+ assert!(!out_list_length.is_null());
let length = match nlength {
- NumberListLength::Exact => ListLength::Exact (size),
- NumberListLength::Maximum => ListLength::Maximum (size)
+ NumberListLength::Exact => ListLength::Exact(size),
+ NumberListLength::Maximum => ListLength::Maximum(size),
};
let s = unsafe { utf8_cstr(in_str) };
- let result = number_list (&s, length);
+ let result = number_list(&s, length);
match result {
- Ok (number_list) => {
- let num_elems = number_list.len ();
+ Ok(number_list) => {
+ let num_elems = number_list.len();
let c_array = unsafe {
- glib_sys::g_malloc_n (num_elems,
- mem::size_of::<libc::c_double> ())
- as *mut libc::c_double
+ glib_sys::g_malloc_n(num_elems, mem::size_of::<libc::c_double>())
+ as *mut libc::c_double
};
- let array = unsafe { slice::from_raw_parts_mut (c_array, num_elems) };
+ let array = unsafe { slice::from_raw_parts_mut(c_array, num_elems) };
- array.copy_from_slice (&number_list);
+ array.copy_from_slice(&number_list);
unsafe {
*out_list = c_array;
@@ -282,16 +290,16 @@ pub extern fn rsvg_css_parse_number_list (in_str: *const libc::c_char,
}
true
- },
+ }
- Err (_) => {
+ Err(_) => {
unsafe {
- *out_list = ptr::null ();
+ *out_list = ptr::null();
*out_list_length = 0;
}
false
}
- }.to_glib ()
+ }.to_glib()
}
#[cfg(test)]
@@ -299,95 +307,95 @@ mod tests {
use super::*;
#[test]
- fn parses_number_optional_number () {
- assert_eq! (number_optional_number ("1, 2"), Ok ((1.0, 2.0)));
- assert_eq! (number_optional_number ("1 2"), Ok ((1.0, 2.0)));
- assert_eq! (number_optional_number ("1"), Ok ((1.0, 1.0)));
-
- assert_eq! (number_optional_number ("-1, -2"), Ok ((-1.0, -2.0)));
- assert_eq! (number_optional_number ("-1 -2"), Ok ((-1.0, -2.0)));
- assert_eq! (number_optional_number ("-1"), Ok ((-1.0, -1.0)));
+ fn parses_number_optional_number() {
+ assert_eq!(number_optional_number("1, 2"), Ok((1.0, 2.0)));
+ assert_eq!(number_optional_number("1 2"), Ok((1.0, 2.0)));
+ assert_eq!(number_optional_number("1"), Ok((1.0, 1.0)));
+
+ assert_eq!(number_optional_number("-1, -2"), Ok((-1.0, -2.0)));
+ assert_eq!(number_optional_number("-1 -2"), Ok((-1.0, -2.0)));
+ assert_eq!(number_optional_number("-1"), Ok((-1.0, -1.0)));
}
#[test]
- fn invalid_number_optional_number () {
- assert! (number_optional_number ("").is_err ());
- assert! (number_optional_number ("1x").is_err ());
- assert! (number_optional_number ("x1").is_err ());
- assert! (number_optional_number ("1 x").is_err ());
- assert! (number_optional_number ("1 , x").is_err ());
- assert! (number_optional_number ("1 , 2x").is_err ());
- assert! (number_optional_number ("1 2 x").is_err ());
+ fn invalid_number_optional_number() {
+ assert!(number_optional_number("").is_err());
+ assert!(number_optional_number("1x").is_err());
+ assert!(number_optional_number("x1").is_err());
+ assert!(number_optional_number("1 x").is_err());
+ assert!(number_optional_number("1 , x").is_err());
+ assert!(number_optional_number("1 , 2x").is_err());
+ assert!(number_optional_number("1 2 x").is_err());
}
#[test]
- fn parses_list_of_points () {
- assert_eq! (list_of_points (" 1 2 "), Ok (vec! [(1.0, 2.0)]));
- assert_eq! (list_of_points ("1 2 3 4"), Ok (vec! [(1.0, 2.0), (3.0, 4.0)]));
- assert_eq! (list_of_points ("1,2,3,4"), Ok (vec! [(1.0, 2.0), (3.0, 4.0)]));
- assert_eq! (list_of_points ("1,2 3,4"), Ok (vec! [(1.0, 2.0), (3.0, 4.0)]));
- assert_eq! (list_of_points ("1,2 -3,4"), Ok (vec! [(1.0, 2.0), (-3.0, 4.0)]));
- assert_eq! (list_of_points ("1,2,-3,4"), Ok (vec! [(1.0, 2.0), (-3.0, 4.0)]));
+ fn parses_list_of_points() {
+ assert_eq!(list_of_points(" 1 2 "), Ok(vec![(1.0, 2.0)]));
+ assert_eq!(list_of_points("1 2 3 4"), Ok(vec![(1.0, 2.0), (3.0, 4.0)]));
+ assert_eq!(list_of_points("1,2,3,4"), Ok(vec![(1.0, 2.0), (3.0, 4.0)]));
+ assert_eq!(list_of_points("1,2 3,4"), Ok(vec![(1.0, 2.0), (3.0, 4.0)]));
+ assert_eq!(list_of_points("1,2 -3,4"),
+ Ok(vec![(1.0, 2.0), (-3.0, 4.0)]));
+ assert_eq!(list_of_points("1,2,-3,4"),
+ Ok(vec![(1.0, 2.0), (-3.0, 4.0)]));
}
#[test]
- fn errors_on_invalid_list_of_points () {
- assert! (list_of_points ("-1-2-3-4").is_err ());
- assert! (list_of_points ("1 2-3,-4").is_err ());
+ fn errors_on_invalid_list_of_points() {
+ assert!(list_of_points("-1-2-3-4").is_err());
+ assert!(list_of_points("1 2-3,-4").is_err());
}
#[test]
- fn parses_angle () {
- assert_eq! (angle_degrees ("0"), Ok (0.0));
- assert_eq! (angle_degrees ("15"), Ok (15.0));
- assert_eq! (angle_degrees ("180.5deg"), Ok (180.5));
- assert_eq! (angle_degrees ("1rad"), Ok (180.0 / PI));
- assert_eq! (angle_degrees ("-400grad"), Ok (-360.0));
-
- assert! (angle_degrees ("").is_err ());
- assert! (angle_degrees ("foo").is_err ());
- assert! (angle_degrees ("300foo").is_err ());
+ fn parses_angle() {
+ assert_eq!(angle_degrees("0"), Ok(0.0));
+ assert_eq!(angle_degrees("15"), Ok(15.0));
+ assert_eq!(angle_degrees("180.5deg"), Ok(180.5));
+ assert_eq!(angle_degrees("1rad"), Ok(180.0 / PI));
+ assert_eq!(angle_degrees("-400grad"), Ok(-360.0));
+
+ assert!(angle_degrees("").is_err());
+ assert!(angle_degrees("foo").is_err());
+ assert!(angle_degrees("300foo").is_err());
}
#[test]
- fn parses_number_list () {
- assert_eq! (number_list ("5", ListLength::Exact (1)),
- Ok (vec! [5.0]));
+ fn parses_number_list() {
+ assert_eq!(number_list("5", ListLength::Exact(1)), Ok(vec![5.0]));
- assert_eq! (number_list ("1 2 3 4", ListLength::Exact (4)),
- Ok (vec! [1.0, 2.0, 3.0, 4.0]));
+ assert_eq!(number_list("1 2 3 4", ListLength::Exact(4)),
+ Ok(vec![1.0, 2.0, 3.0, 4.0]));
- assert_eq! (number_list ("5", ListLength::Maximum (1)),
- Ok (vec! [5.0]));
+ assert_eq!(number_list("5", ListLength::Maximum(1)), Ok(vec![5.0]));
- assert_eq! (number_list ("1.0, -2.5", ListLength::Maximum (2)),
- Ok (vec! [1.0, -2.5]));
+ assert_eq!(number_list("1.0, -2.5", ListLength::Maximum(2)),
+ Ok(vec![1.0, -2.5]));
- assert_eq! (number_list ("5 6", ListLength::Maximum (3)),
- Ok (vec! [5.0, 6.0]));
+ assert_eq!(number_list("5 6", ListLength::Maximum(3)),
+ Ok(vec![5.0, 6.0]));
}
#[test]
- fn errors_on_invalid_number_list () {
+ fn errors_on_invalid_number_list() {
// empty
- assert! (number_list ("", ListLength::Exact (1)).is_err ());
+ assert!(number_list("", ListLength::Exact(1)).is_err());
// garbage
- assert! (number_list ("foo", ListLength::Exact (1)).is_err ());
- assert! (number_list ("1foo", ListLength::Exact (2)).is_err ());
- assert! (number_list ("1 foo", ListLength::Exact (2)).is_err ());
- assert! (number_list ("1 foo 2", ListLength::Exact (2)).is_err ());
- assert! (number_list ("1,foo", ListLength::Exact (2)).is_err ());
+ assert!(number_list("foo", ListLength::Exact(1)).is_err());
+ assert!(number_list("1foo", ListLength::Exact(2)).is_err());
+ assert!(number_list("1 foo", ListLength::Exact(2)).is_err());
+ assert!(number_list("1 foo 2", ListLength::Exact(2)).is_err());
+ assert!(number_list("1,foo", ListLength::Exact(2)).is_err());
// too many
- assert! (number_list ("1 2", ListLength::Exact (1)).is_err ());
- assert! (number_list ("1,2,3", ListLength::Maximum (2)).is_err ());
+ assert!(number_list("1 2", ListLength::Exact(1)).is_err());
+ assert!(number_list("1,2,3", ListLength::Maximum(2)).is_err());
// extra token
- assert! (number_list ("1,", ListLength::Exact (1)).is_err ());
+ assert!(number_list("1,", ListLength::Exact(1)).is_err());
// too few
- assert! (number_list ("1", ListLength::Exact (2)).is_err ());
- assert! (number_list ("1 2", ListLength::Exact (3)).is_err ());
+ assert!(number_list("1", ListLength::Exact(2)).is_err());
+ assert!(number_list("1 2", ListLength::Exact(3)).is_err());
}
}
diff --git a/rsvg_internals/src/path_builder.rs b/rsvg_internals/src/path_builder.rs
index ff32c293..f80bdebb 100644
--- a/rsvg_internals/src/path_builder.rs
+++ b/rsvg_internals/src/path_builder.rs
@@ -1,5 +1,5 @@
-use cairo_sys;
use cairo;
+use cairo_sys;
use glib::translate::*;
use std::f64;
@@ -11,15 +11,16 @@ pub struct LargeArc(pub bool);
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Sweep {
Negative,
- Positive
+ Positive,
}
#[derive(Debug, PartialEq)]
pub enum PathCommand {
- MoveTo (f64, f64),
- LineTo (f64, f64),
- CurveTo ((f64, f64), (f64, f64), (f64, f64)), // (x2, y2), (x3, y3), (x4, y4) <- this is the destination
point
- ClosePath
+ MoveTo(f64, f64),
+ LineTo(f64, f64),
+ CurveTo((f64, f64), (f64, f64), (f64, f64)), /* (x2, y2), (x3, y3), (x4, y4) <- this is
+ * the destination point */
+ ClosePath,
}
#[repr(C)]
@@ -29,9 +30,7 @@ pub struct RsvgPathBuilder {
impl Default for RsvgPathBuilder {
fn default() -> RsvgPathBuilder {
- RsvgPathBuilder {
- path_commands: Vec::new ()
- }
+ RsvgPathBuilder { path_commands: Vec::new(), }
}
}
@@ -40,15 +39,15 @@ impl PathCommand {
match *self {
PathCommand::MoveTo(x, y) => {
cr.move_to(x, y);
- },
+ }
PathCommand::LineTo(x, y) => {
cr.line_to(x, y);
- },
+ }
PathCommand::CurveTo((x2, y2), (x3, y3), (x4, y4)) => {
cr.curve_to(x2, y2, x3, y3, x4, y4);
- },
+ }
PathCommand::ClosePath => {
cr.close_path();
@@ -58,45 +57,48 @@ impl PathCommand {
}
impl RsvgPathBuilder {
- pub fn new () -> RsvgPathBuilder {
+ pub fn new() -> RsvgPathBuilder {
RsvgPathBuilder::default()
}
- pub fn move_to (&mut self, x: f64, y: f64) {
- self.path_commands.push (PathCommand::MoveTo (x, y));
+ pub fn move_to(&mut self, x: f64, y: f64) {
+ self.path_commands.push(PathCommand::MoveTo(x, y));
}
- pub fn line_to (&mut self, x: f64, y: f64) {
- self.path_commands.push (PathCommand::LineTo (x, y));
+ pub fn line_to(&mut self, x: f64, y: f64) {
+ self.path_commands.push(PathCommand::LineTo(x, y));
}
- pub fn curve_to (&mut self, x2: f64, y2: f64, x3: f64, y3: f64, x4: f64, y4: f64) {
- self.path_commands.push (PathCommand::CurveTo ((x2, y2), (x3, y3), (x4, y4)));
+ pub fn curve_to(&mut self, x2: f64, y2: f64, x3: f64, y3: f64, x4: f64, y4: f64) {
+ self.path_commands.push(PathCommand::CurveTo((x2, y2), (x3, y3), (x4, y4)));
}
- pub fn close_path (&mut self) {
- self.path_commands.push (PathCommand::ClosePath);
+ pub fn close_path(&mut self) {
+ self.path_commands.push(PathCommand::ClosePath);
}
- pub fn get_path_commands (&self) -> &[PathCommand] {
+ pub fn get_path_commands(&self) -> &[PathCommand] {
&self.path_commands
}
- /**
- * x1/y1: starting coordinates
- * rx/ry: radiuses before rotation
- * x_axis_rotation: Rotation angle for axes, in degrees
- * large_arc: false for arc length <= 180, true for arc >= 180
- * sweep: negative or positive angle
- * x2/y2: ending coordinates
- */
- pub fn arc (&mut self,
- x1: f64, y1: f64,
- mut rx: f64, mut ry: f64,
- x_axis_rotation: f64,
- large_arc: LargeArc,
- sweep: Sweep,
- x2: f64, y2: f64) {
+ /** * * * * **/
+ // x1/y1: starting coordinates
+ // rx/ry: radiuses before rotation
+ // x_axis_rotation: Rotation angle for axes, in degrees
+ // large_arc: false for arc length <= 180, true for arc >= 180
+ // sweep: negative or positive angle
+ // x2/y2: ending coordinates
+ //
+ pub fn arc(&mut self,
+ x1: f64,
+ y1: f64,
+ mut rx: f64,
+ mut ry: f64,
+ x_axis_rotation: f64,
+ large_arc: LargeArc,
+ sweep: Sweep,
+ x2: f64,
+ y2: f64) {
/* See Appendix F.6 Elliptical arc implementation notes
http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes */
@@ -129,16 +131,16 @@ impl RsvgPathBuilder {
/* X-axis */
f = x_axis_rotation * PI / 180.0;
- sinf = f.sin ();
- cosf = f.cos ();
+ sinf = f.sin();
+ cosf = f.cos();
- rx = rx.abs ();
- ry = ry.abs ();
+ rx = rx.abs();
+ ry = ry.abs();
/* Check the radius against floading point underflow.
See http://bugs.debian.org/508443 */
if (rx < f64::EPSILON) || (ry < f64::EPSILON) {
- self.line_to (x2, y2);
+ self.line_to(x2, y2);
return;
}
@@ -150,8 +152,8 @@ impl RsvgPathBuilder {
gamma = (x1_ * x1_) / (rx * rx) + (y1_ * y1_) / (ry * ry);
if gamma > 1.0 {
- rx *= gamma.sqrt ();
- ry *= gamma.sqrt ();
+ rx *= gamma.sqrt();
+ ry *= gamma.sqrt();
}
/* Compute the center */
@@ -161,7 +163,7 @@ impl RsvgPathBuilder {
return;
}
- k1 = ((rx * rx * ry * ry) / k1 - 1.0).abs ().sqrt ();
+ k1 = ((rx * rx * ry * ry) / k1 - 1.0).abs().sqrt();
if is_positive_sweep == is_large_arc {
k1 = -k1;
}
@@ -179,28 +181,28 @@ impl RsvgPathBuilder {
k3 = (-x1_ - cx_) / rx;
k4 = (-y1_ - cy_) / ry;
- k5 = (k1 * k1 + k2 * k2).abs ().sqrt ();
+ k5 = (k1 * k1 + k2 * k2).abs().sqrt();
if k5 == 0.0 {
return;
}
k5 = k1 / k5;
- k5 = clamp (k5, -1.0, 1.0);
- theta1 = k5.acos ();
+ k5 = clamp(k5, -1.0, 1.0);
+ theta1 = k5.acos();
if k2 < 0.0 {
theta1 = -theta1;
}
/* Compute delta_theta */
- k5 = ((k1 * k1 + k2 * k2) * (k3 * k3 + k4 * k4)).abs ().sqrt ();
+ k5 = ((k1 * k1 + k2 * k2) * (k3 * k3 + k4 * k4)).abs().sqrt();
if k5 == 0.0 {
return;
}
k5 = (k1 * k3 + k2 * k4) / k5;
- k5 = clamp (k5, -1.0, 1.0);
- delta_theta = k5.acos ();
+ k5 = clamp(k5, -1.0, 1.0);
+ delta_theta = k5.acos();
if k1 * k4 - k3 * k2 < 0.0 {
delta_theta = -delta_theta;
}
@@ -213,23 +215,28 @@ impl RsvgPathBuilder {
/* Now draw the arc */
- n_segs = (delta_theta / (PI * 0.5 + 0.001)).abs ().ceil () as i32;
+ n_segs = (delta_theta / (PI * 0.5 + 0.001)).abs().ceil() as i32;
let n_segs_dbl = f64::from(n_segs);
- for i in 0 .. n_segs {
- self.arc_segment (cx, cy,
- theta1 + f64::from(i) * delta_theta / n_segs_dbl,
- theta1 + f64::from(i + 1) * delta_theta / n_segs_dbl,
- rx, ry,
- x_axis_rotation);
+ for i in 0..n_segs {
+ self.arc_segment(cx,
+ cy,
+ theta1 + f64::from(i) * delta_theta / n_segs_dbl,
+ theta1 + f64::from(i + 1) * delta_theta / n_segs_dbl,
+ rx,
+ ry,
+ x_axis_rotation);
}
}
- fn arc_segment (&mut self,
- xc: f64, yc: f64,
- th0: f64, th1: f64,
- rx: f64, ry: f64,
- x_axis_rotation: f64) {
+ fn arc_segment(&mut self,
+ xc: f64,
+ yc: f64,
+ th0: f64,
+ th1: f64,
+ rx: f64,
+ ry: f64,
+ x_axis_rotation: f64) {
let x1: f64;
let y1: f64;
let x2: f64;
@@ -243,24 +250,24 @@ impl RsvgPathBuilder {
let cosf: f64;
f = x_axis_rotation * PI / 180.0;
- sinf = f.sin ();
- cosf = f.cos ();
+ sinf = f.sin();
+ cosf = f.cos();
th_half = 0.5 * (th1 - th0);
- t = (8.0 / 3.0) * (th_half * 0.5).sin () * (th_half * 0.5).sin () / th_half.sin ();
- x1 = rx * (th0.cos () - t * th0.sin ());
- y1 = ry * (th0.sin () + t * th0.cos ());
- x3 = rx * th1.cos ();
- y3 = ry * th1.sin ();
- x2 = x3 + rx * (t * th1.sin ());
- y2 = y3 + ry * (-t * th1.cos ());
-
- self.curve_to (xc + cosf * x1 - sinf * y1,
- yc + sinf * x1 + cosf * y1,
- xc + cosf * x2 - sinf * y2,
- yc + sinf * x2 + cosf * y2,
- xc + cosf * x3 - sinf * y3,
- yc + sinf * x3 + cosf * y3);
+ t = (8.0 / 3.0) * (th_half * 0.5).sin() * (th_half * 0.5).sin() / th_half.sin();
+ x1 = rx * (th0.cos() - t * th0.sin());
+ y1 = ry * (th0.sin() + t * th0.cos());
+ x3 = rx * th1.cos();
+ y3 = ry * th1.sin();
+ x2 = x3 + rx * (t * th1.sin());
+ y2 = y3 + ry * (-t * th1.cos());
+
+ self.curve_to(xc + cosf * x1 - sinf * y1,
+ yc + sinf * x1 + cosf * y1,
+ xc + cosf * x2 - sinf * y2,
+ yc + sinf * x2 + cosf * y2,
+ xc + cosf * x3 - sinf * y3,
+ yc + sinf * x3 + cosf * y3);
}
fn to_cairo(&self, cr: &cairo::Context) {
@@ -270,7 +277,7 @@ impl RsvgPathBuilder {
}
}
-fn clamp (val: f64, low: f64, high: f64) -> f64 {
+fn clamp(val: f64, low: f64, high: f64) -> f64 {
if val < low {
low
} else if val > high {
@@ -281,10 +288,10 @@ fn clamp (val: f64, low: f64, high: f64) -> f64 {
}
#[no_mangle]
-pub extern fn rsvg_path_builder_add_to_cairo_context (raw_builder: *mut RsvgPathBuilder,
- raw_cr: *mut cairo_sys::cairo_t) {
- assert! (!raw_builder.is_null ());
- assert! (!raw_cr.is_null ());
+pub extern "C" fn rsvg_path_builder_add_to_cairo_context(raw_builder: *mut RsvgPathBuilder,
+ raw_cr: *mut cairo_sys::cairo_t) {
+ assert!(!raw_builder.is_null());
+ assert!(!raw_cr.is_null());
let builder: &mut RsvgPathBuilder = unsafe { &mut (*raw_builder) };
let cr = unsafe { cairo::Context::from_glib_none(raw_cr) };
diff --git a/rsvg_internals/src/path_parser.rs b/rsvg_internals/src/path_parser.rs
index 4abe9056..08eadc2a 100644
--- a/rsvg_internals/src/path_parser.rs
+++ b/rsvg_internals/src/path_parser.rs
@@ -1,13 +1,13 @@
+use path_builder::*;
use std::error::Error;
use std::fmt::{self, Display, Formatter};
+use std::iter::Enumerate;
use std::str;
use std::str::Chars;
-use std::iter::Enumerate;
-use path_builder::*;
struct PathParser<'b> {
chars_enumerator: Enumerate<Chars<'b>>,
- lookahead: Option<char>, /* None if we are in EOF */
+ lookahead: Option<char>, /* None if we are in EOF */
current_pos: Option<usize>, /* None if the string hasn't been scanned */
builder: &'b mut RsvgPathBuilder,
@@ -32,70 +32,69 @@ struct PathParser<'b> {
* used for closepath.
*/
subpath_start_x: f64,
- subpath_start_y: f64
+ subpath_start_y: f64,
}
/* This is a recursive descent parser for path data in SVG files,
- * as specified in https://www.w3.org/TR/SVG/paths.html#PathDataBNF
- *
- * Some peculiarities:
- *
- * - SVG allows optional commas inside coordiante pairs, and between
- * coordinate pairs. So, for example, these are equivalent:
- *
- * M 10 20 30 40
- * M 10, 20 30, 40
- * M 10, 20, 30, 40
- *
- * - Whitespace is optional. These are equivalent:
- *
- * M10,20 30,40
- * M10,20,30,40
- *
- * These are also equivalent:
- *
- * M-10,20-30-40
- * M -10 20 -30 -40
- *
- * M.1-2,3E2-4
- * M 0.1 -2 300 -4
- */
+ * as specified in https://www.w3.org/TR/SVG/paths.html#PathDataBNF */
+//
+// Some peculiarities:
+//
+// - SVG allows optional commas inside coordiante pairs, and between
+// coordinate pairs. So, for example, these are equivalent:
+//
+// M 10 20 30 40
+// M 10, 20 30, 40
+// M 10, 20, 30, 40
+//
+// - Whitespace is optional. These are equivalent:
+//
+// M10,20 30,40
+// M10,20,30,40
+//
+// These are also equivalent:
+//
+// M-10,20-30-40
+// M -10 20 -30 -40
+//
+// M.1-2,3E2-4
+// M 0.1 -2 300 -4
+//
impl<'b> PathParser<'b> {
- fn new (builder: &'b mut RsvgPathBuilder, path_str: &'b str) -> PathParser<'b> {
- PathParser {
- chars_enumerator: path_str.chars ().enumerate (),
- lookahead: None,
- current_pos: None,
+ fn new(builder: &'b mut RsvgPathBuilder, path_str: &'b str) -> PathParser<'b> {
+ PathParser { chars_enumerator: path_str.chars().enumerate(),
+ lookahead: None,
+ current_pos: None,
- builder: builder,
+ builder,
- current_x: 0.0,
- current_y: 0.0,
+ current_x: 0.0,
+ current_y: 0.0,
- cubic_reflection_x: 0.0,
- cubic_reflection_y: 0.0,
+ cubic_reflection_x: 0.0,
+ cubic_reflection_y: 0.0,
- quadratic_reflection_x: 0.0,
- quadratic_reflection_y: 0.0,
+ quadratic_reflection_x: 0.0,
+ quadratic_reflection_y: 0.0,
- subpath_start_x: 0.0,
- subpath_start_y: 0.0
- }
+ subpath_start_x: 0.0,
+ subpath_start_y: 0.0, }
}
- fn parse (&mut self) -> Result<(), ParseError> {
- self.getchar ();
+ fn parse(&mut self) -> Result<(), ParseError> {
+ self.getchar();
self.optional_whitespace()?;
self.moveto_drawto_command_groups()
}
- fn getchar (&mut self) {
- if let Some ((pos, c)) = self.chars_enumerator.next () {
+ fn getchar(&mut self) {
+ if let Some((pos, c)) = self.chars_enumerator.next() {
self.lookahead = Some(c);
self.current_pos = Some(pos);
} else {
- // We got to EOF; make current_pos point to the position after the last char in the string
+ // We got to EOF; make current_pos point to the position after the last char in the
+ // string
self.lookahead = None;
if self.current_pos.is_none() {
self.current_pos = Some(0);
@@ -106,16 +105,14 @@ impl<'b> PathParser<'b> {
}
fn error(&self, kind: ErrorKind) -> ParseError {
- ParseError {
- position: self.current_pos.unwrap(),
- kind: kind
- }
+ ParseError { position: self.current_pos.unwrap(),
+ kind, }
}
- fn match_char (&mut self, c: char) -> bool {
- if let Some (x) = self.lookahead {
+ fn match_char(&mut self, c: char) -> bool {
+ if let Some(x) = self.lookahead {
if c == x {
- self.getchar ();
+ self.getchar();
return true;
}
}
@@ -123,14 +120,14 @@ impl<'b> PathParser<'b> {
false
}
- fn whitespace (&mut self) -> Result<(), ParseError> {
- if let Some (c) = self.lookahead {
- if c.is_whitespace () {
- assert! (self.match_char (c));
+ fn whitespace(&mut self) -> Result<(), ParseError> {
+ if let Some(c) = self.lookahead {
+ if c.is_whitespace() {
+ assert!(self.match_char(c));
- while let Some (c) = self.lookahead {
- if c.is_whitespace () {
- assert! (self.match_char (c));
+ while let Some(c) = self.lookahead {
+ if c.is_whitespace() {
+ assert!(self.match_char(c));
continue;
} else {
break;
@@ -142,22 +139,22 @@ impl<'b> PathParser<'b> {
Ok(())
}
- fn optional_whitespace (&mut self) -> Result<(), ParseError> {
+ fn optional_whitespace(&mut self) -> Result<(), ParseError> {
let _ = self.whitespace();
Ok(())
}
- fn optional_comma_whitespace (&mut self) -> Result<(), ParseError> {
+ fn optional_comma_whitespace(&mut self) -> Result<(), ParseError> {
self.optional_whitespace()?;
if self.lookahead_is(',') {
- self.match_char (',');
+ self.match_char(',');
self.optional_whitespace()?;
}
Ok(())
}
- fn lookahead_is (&self, c: char) -> bool {
- if let Some (x) = self.lookahead {
+ fn lookahead_is(&self, c: char) -> bool {
+ if let Some(x) = self.lookahead {
if x == c {
return true;
}
@@ -166,9 +163,9 @@ impl<'b> PathParser<'b> {
false
}
- fn lookahead_is_digit (&self, d: &mut char) -> bool {
- if let Some (c) = self.lookahead {
- if c.is_digit (10) {
+ fn lookahead_is_digit(&self, d: &mut char) -> bool {
+ if let Some(c) = self.lookahead {
+ if c.is_digit(10) {
*d = c;
return true;
}
@@ -179,20 +176,18 @@ impl<'b> PathParser<'b> {
fn lookahead_is_start_of_number(&mut self) -> bool {
let mut c = ' ';
- self.lookahead_is_digit(&mut c) ||
- self.lookahead_is('.') ||
- self.lookahead_is('+') ||
- self.lookahead_is('-')
+ self.lookahead_is_digit(&mut c) || self.lookahead_is('.') || self.lookahead_is('+')
+ || self.lookahead_is('-')
}
- fn number (&mut self) -> Result<f64, ParseError> {
+ fn number(&mut self) -> Result<f64, ParseError> {
let mut sign: f64;
sign = 1.0;
- if self.match_char ('+') {
+ if self.match_char('+') {
sign = 1.0;
- } else if self.match_char ('-') {
+ } else if self.match_char('-') {
sign = -1.0;
}
@@ -206,36 +201,36 @@ impl<'b> PathParser<'b> {
let mut c: char = ' ';
- if self.lookahead_is_digit (&mut c) || self.lookahead_is ('.') {
+ if self.lookahead_is_digit(&mut c) || self.lookahead_is('.') {
/* Integer part */
- while self.lookahead_is_digit (&mut c) {
- value = value * 10.0 + f64::from(char_to_digit (c));
+ while self.lookahead_is_digit(&mut c) {
+ value = value * 10.0 + f64::from(char_to_digit(c));
- assert! (self.match_char (c));
+ assert!(self.match_char(c));
}
/* Fractional part */
- if self.match_char ('.') {
+ if self.match_char('.') {
let mut fraction: f64 = 1.0;
let mut c: char = ' ';
- while self.lookahead_is_digit (&mut c) {
+ while self.lookahead_is_digit(&mut c) {
fraction /= 10.0;
- value += fraction * f64::from(char_to_digit (c));
+ value += fraction * f64::from(char_to_digit(c));
- assert! (self.match_char (c));
+ assert!(self.match_char(c));
}
}
- if self.match_char ('E') || self.match_char ('e') {
+ if self.match_char('E') || self.match_char('e') {
/* exponent sign */
- if self.match_char ('+') {
+ if self.match_char('+') {
exponent_sign = 1.0;
- } else if self.match_char ('-') {
+ } else if self.match_char('-') {
exponent_sign = -1.0;
}
@@ -243,13 +238,13 @@ impl<'b> PathParser<'b> {
let mut c: char = ' ';
- if self.lookahead_is_digit (&mut c) {
+ if self.lookahead_is_digit(&mut c) {
let mut exp = 0.0;
- while self.lookahead_is_digit (&mut c) {
- exp = exp * 10.0 + f64::from(char_to_digit (c));
+ while self.lookahead_is_digit(&mut c) {
+ exp = exp * 10.0 + f64::from(char_to_digit(c));
- assert! (self.match_char (c));
+ assert!(self.match_char(c));
}
exponent = Some(exp);
@@ -261,9 +256,9 @@ impl<'b> PathParser<'b> {
}
if let Some(exp) = exponent {
- Ok (sign * value * 10.0f64.powf (exp * exponent_sign))
+ Ok(sign * value * 10.0f64.powf(exp * exponent_sign))
} else {
- Ok (sign * value)
+ Ok(sign * value)
}
} else if self.lookahead.is_some() {
Err(self.error(ErrorKind::UnexpectedToken))
@@ -272,10 +267,10 @@ impl<'b> PathParser<'b> {
}
}
- fn flag (&mut self) -> Result<bool, ParseError> {
- if self.match_char ('0') {
+ fn flag(&mut self) -> Result<bool, ParseError> {
+ if self.match_char('0') {
Ok(false)
- } else if self.match_char ('1') {
+ } else if self.match_char('1') {
Ok(true)
} else if self.lookahead.is_some() {
Err(self.error(ErrorKind::UnexpectedToken))
@@ -284,7 +279,7 @@ impl<'b> PathParser<'b> {
}
}
- fn coordinate_pair (&mut self) -> Result<(f64, f64), ParseError> {
+ fn coordinate_pair(&mut self) -> Result<(f64, f64), ParseError> {
let a = self.number()?;
self.optional_comma_whitespace()?;
let b = self.number()?;
@@ -292,7 +287,7 @@ impl<'b> PathParser<'b> {
Ok((a, b))
}
- fn set_current_point (&mut self, x: f64, y: f64) {
+ fn set_current_point(&mut self, x: f64, y: f64) {
self.current_x = x;
self.current_y = y;
@@ -303,7 +298,7 @@ impl<'b> PathParser<'b> {
self.quadratic_reflection_y = self.current_y;
}
- fn set_cubic_reflection_and_current_point (&mut self, x3: f64, y3: f64, x4: f64, y4: f64) {
+ fn set_cubic_reflection_and_current_point(&mut self, x3: f64, y3: f64, x4: f64, y4: f64) {
self.cubic_reflection_x = x3;
self.cubic_reflection_y = y3;
@@ -314,7 +309,7 @@ impl<'b> PathParser<'b> {
self.quadratic_reflection_y = self.current_y;
}
- fn set_quadratic_reflection_and_current_point (&mut self, a: f64, b: f64, c: f64, d: f64) {
+ fn set_quadratic_reflection_and_current_point(&mut self, a: f64, b: f64, c: f64, d: f64) {
self.quadratic_reflection_x = a;
self.quadratic_reflection_y = b;
@@ -325,28 +320,28 @@ impl<'b> PathParser<'b> {
self.cubic_reflection_y = self.current_y;
}
- fn emit_move_to (&mut self, x: f64, y: f64) {
- self.set_current_point (x, y);
+ fn emit_move_to(&mut self, x: f64, y: f64) {
+ self.set_current_point(x, y);
self.subpath_start_x = self.current_x;
self.subpath_start_y = self.current_y;
- self.builder.move_to (self.current_x, self.current_y);
+ self.builder.move_to(self.current_x, self.current_y);
}
- fn emit_line_to (&mut self, x: f64, y: f64) {
- self.set_current_point (x, y);
+ fn emit_line_to(&mut self, x: f64, y: f64) {
+ self.set_current_point(x, y);
- self.builder.line_to (self.current_x, self.current_y);
+ self.builder.line_to(self.current_x, self.current_y);
}
- fn emit_curve_to (&mut self, x2: f64, y2: f64, x3: f64, y3: f64, x4: f64, y4: f64) {
- self.set_cubic_reflection_and_current_point (x3, y3, x4, y4);
+ fn emit_curve_to(&mut self, x2: f64, y2: f64, x3: f64, y3: f64, x4: f64, y4: f64) {
+ self.set_cubic_reflection_and_current_point(x3, y3, x4, y4);
- self.builder.curve_to (x2, y2, x3, y3, x4, y4);
+ self.builder.curve_to(x2, y2, x3, y3, x4, y4);
}
- fn emit_quadratic_curve_to (&mut self, a: f64, b: f64, c: f64, d: f64) {
+ fn emit_quadratic_curve_to(&mut self, a: f64, b: f64, c: f64, d: f64) {
/* raise quadratic Bézier to cubic */
let x2 = (self.current_x + 2.0 * a) / 3.0;
@@ -356,32 +351,42 @@ impl<'b> PathParser<'b> {
let x3 = (x4 + 2.0 * a) / 3.0;
let y3 = (y4 + 2.0 * b) / 3.0;
- self.set_quadratic_reflection_and_current_point (a, b, c, d);
+ self.set_quadratic_reflection_and_current_point(a, b, c, d);
- self.builder.curve_to (x2, y2, x3, y3, x4, y4);
+ self.builder.curve_to(x2, y2, x3, y3, x4, y4);
}
- fn emit_arc (&mut self, rx: f64, ry: f64, x_axis_rotation: f64, large_arc: LargeArc, sweep: Sweep, x:
f64, y: f64) {
+ fn emit_arc(&mut self,
+ rx: f64,
+ ry: f64,
+ x_axis_rotation: f64,
+ large_arc: LargeArc,
+ sweep: Sweep,
+ x: f64,
+ y: f64) {
let (start_x, start_y) = (self.current_x, self.current_y);
- self.set_current_point (x, y);
+ self.set_current_point(x, y);
- self.builder.arc (start_x, start_y,
- rx, ry,
- x_axis_rotation,
- large_arc,
- sweep,
- self.current_x, self.current_y);
+ self.builder.arc(start_x,
+ start_y,
+ rx,
+ ry,
+ x_axis_rotation,
+ large_arc,
+ sweep,
+ self.current_x,
+ self.current_y);
}
- fn emit_close_path (&mut self) {
+ fn emit_close_path(&mut self) {
let (x, y) = (self.subpath_start_x, self.subpath_start_y);
- self.set_current_point (x, y);
+ self.set_current_point(x, y);
- self.builder.close_path ();
+ self.builder.close_path();
}
- fn lineto_argument_sequence (&mut self, absolute: bool) -> Result<(), ParseError> {
+ fn lineto_argument_sequence(&mut self, absolute: bool) -> Result<(), ParseError> {
loop {
let (mut x, mut y) = self.coordinate_pair()?;
@@ -390,40 +395,42 @@ impl<'b> PathParser<'b> {
y += self.current_y;
}
- self.emit_line_to (x, y);
+ self.emit_line_to(x, y);
self.whitespace()?;
- if self.lookahead_is (',') {
- assert! (self.match_char (','));
+ if self.lookahead_is(',') {
+ assert!(self.match_char(','));
self.optional_whitespace()?;
} else if !self.lookahead_is_start_of_number() {
break;
}
-
}
Ok(())
}
- fn moveto_argument_sequence (&mut self, absolute: bool, is_initial_moveto: bool) -> Result<(),
ParseError> {
- let (mut x, mut y) = self.coordinate_pair ()?;
+ fn moveto_argument_sequence(&mut self,
+ absolute: bool,
+ is_initial_moveto: bool)
+ -> Result<(), ParseError> {
+ let (mut x, mut y) = self.coordinate_pair()?;
if is_initial_moveto {
- self.emit_move_to (x, y);
+ self.emit_move_to(x, y);
} else {
if !absolute {
x += self.current_x;
y += self.current_y;
}
- self.emit_move_to (x, y);
+ self.emit_move_to(x, y);
}
self.whitespace()?;
- if self.lookahead_is (',') {
- assert! (self.match_char (','));
+ if self.lookahead_is(',') {
+ assert!(self.match_char(','));
self.optional_whitespace()?;
self.lineto_argument_sequence(absolute)
} else if self.lookahead_is_start_of_number() {
@@ -433,12 +440,12 @@ impl<'b> PathParser<'b> {
}
}
- fn moveto (&mut self, is_initial_moveto: bool) -> Result<(), ParseError> {
- if self.lookahead_is ('M') || self.lookahead_is ('m') {
- let absolute = if self.match_char ('M') {
+ fn moveto(&mut self, is_initial_moveto: bool) -> Result<(), ParseError> {
+ if self.lookahead_is('M') || self.lookahead_is('m') {
+ let absolute = if self.match_char('M') {
true
} else {
- assert! (self.match_char ('m'));
+ assert!(self.match_char('m'));
false
};
@@ -451,7 +458,7 @@ impl<'b> PathParser<'b> {
}
}
- fn moveto_drawto_command_group (&mut self, is_initial_moveto: bool) -> Result<(), ParseError> {
+ fn moveto_drawto_command_group(&mut self, is_initial_moveto: bool) -> Result<(), ParseError> {
self.moveto(is_initial_moveto)?;
self.optional_whitespace()?;
@@ -474,7 +481,7 @@ impl<'b> PathParser<'b> {
Ok(())
}
- fn optional_drawto_commands (&mut self) -> Result<bool, ParseError> {
+ fn optional_drawto_commands(&mut self) -> Result<bool, ParseError> {
while self.drawto_command()? {
self.optional_whitespace()?;
}
@@ -482,33 +489,28 @@ impl<'b> PathParser<'b> {
Ok(false)
}
- fn drawto_command (&mut self) -> Result<bool, ParseError> {
- Ok(self.close_path()? ||
- self.line_to()? ||
- self.horizontal_line_to()? ||
- self.vertical_line_to()? ||
- self.curve_to()? ||
- self.smooth_curve_to()? ||
- self.quadratic_bezier_curve_to()? ||
- self.smooth_quadratic_bezier_curve_to()? ||
- self.elliptical_arc()?)
+ fn drawto_command(&mut self) -> Result<bool, ParseError> {
+ Ok(self.close_path()? || self.line_to()? || self.horizontal_line_to()?
+ || self.vertical_line_to()? || self.curve_to()? || self.smooth_curve_to()?
+ || self.quadratic_bezier_curve_to()?
+ || self.smooth_quadratic_bezier_curve_to()? || self.elliptical_arc()?)
}
- fn close_path (&mut self) -> Result<bool, ParseError> {
- if self.match_char ('Z') || self.match_char ('z') {
- self.emit_close_path ();
+ fn close_path(&mut self) -> Result<bool, ParseError> {
+ if self.match_char('Z') || self.match_char('z') {
+ self.emit_close_path();
Ok(true)
} else {
Ok(false)
}
}
- fn line_to (&mut self) -> Result<bool, ParseError> {
- if self.lookahead_is ('L') || self.lookahead_is ('l') {
- let absolute = if self.match_char ('L') {
+ fn line_to(&mut self) -> Result<bool, ParseError> {
+ if self.lookahead_is('L') || self.lookahead_is('l') {
+ let absolute = if self.match_char('L') {
true
} else {
- assert! (self.match_char ('l'));
+ assert!(self.match_char('l'));
false
};
@@ -521,7 +523,7 @@ impl<'b> PathParser<'b> {
}
}
- fn horizontal_lineto_argument_sequence (&mut self, absolute: bool) -> Result<(), ParseError> {
+ fn horizontal_lineto_argument_sequence(&mut self, absolute: bool) -> Result<(), ParseError> {
loop {
let mut x = self.number()?;
@@ -531,12 +533,12 @@ impl<'b> PathParser<'b> {
let y = self.current_y;
- self.emit_line_to (x, y);
+ self.emit_line_to(x, y);
self.whitespace()?;
- if self.lookahead_is (',') {
- assert! (self.match_char (','));
+ if self.lookahead_is(',') {
+ assert!(self.match_char(','));
self.optional_whitespace()?;
} else if !self.lookahead_is_start_of_number() {
break;
@@ -546,12 +548,12 @@ impl<'b> PathParser<'b> {
Ok(())
}
- fn horizontal_line_to (&mut self) -> Result<bool, ParseError> {
- if self.lookahead_is ('H') || self.lookahead_is ('h') {
- let absolute = if self.match_char ('H') {
+ fn horizontal_line_to(&mut self) -> Result<bool, ParseError> {
+ if self.lookahead_is('H') || self.lookahead_is('h') {
+ let absolute = if self.match_char('H') {
true
} else {
- assert! (self.match_char ('h'));
+ assert!(self.match_char('h'));
false
};
@@ -564,7 +566,7 @@ impl<'b> PathParser<'b> {
}
}
- fn vertical_lineto_argument_sequence (&mut self, absolute: bool) -> Result<(), ParseError> {
+ fn vertical_lineto_argument_sequence(&mut self, absolute: bool) -> Result<(), ParseError> {
loop {
let mut y = self.number()?;
@@ -574,12 +576,12 @@ impl<'b> PathParser<'b> {
let x = self.current_x;
- self.emit_line_to (x, y);
+ self.emit_line_to(x, y);
self.whitespace()?;
- if self.lookahead_is (',') {
- assert! (self.match_char (','));
+ if self.lookahead_is(',') {
+ assert!(self.match_char(','));
self.optional_whitespace()?;
} else if !self.lookahead_is_start_of_number() {
break;
@@ -589,12 +591,12 @@ impl<'b> PathParser<'b> {
Ok(())
}
- fn vertical_line_to (&mut self) -> Result<bool, ParseError> {
- if self.lookahead_is ('V') || self.lookahead_is ('v') {
- let absolute = if self.match_char ('V') {
+ fn vertical_line_to(&mut self) -> Result<bool, ParseError> {
+ if self.lookahead_is('V') || self.lookahead_is('v') {
+ let absolute = if self.match_char('V') {
true
} else {
- assert! (self.match_char ('v'));
+ assert!(self.match_char('v'));
false
};
@@ -607,7 +609,7 @@ impl<'b> PathParser<'b> {
}
}
- fn curveto_argument_sequence (&mut self, absolute: bool) -> Result<(), ParseError> {
+ fn curveto_argument_sequence(&mut self, absolute: bool) -> Result<(), ParseError> {
loop {
let (mut x2, mut y2) = self.coordinate_pair()?;
@@ -628,12 +630,12 @@ impl<'b> PathParser<'b> {
y4 += self.current_y;
}
- self.emit_curve_to (x2, y2, x3, y3, x4, y4);
+ self.emit_curve_to(x2, y2, x3, y3, x4, y4);
self.whitespace()?;
- if self.lookahead_is (',') {
- assert! (self.match_char (','));
+ if self.lookahead_is(',') {
+ assert!(self.match_char(','));
self.optional_whitespace()?;
} else if !self.lookahead_is_start_of_number() {
break;
@@ -643,7 +645,7 @@ impl<'b> PathParser<'b> {
Ok(())
}
- fn smooth_curveto_argument_sequence (&mut self, absolute: bool) -> Result<(), ParseError> {
+ fn smooth_curveto_argument_sequence(&mut self, absolute: bool) -> Result<(), ParseError> {
loop {
let (mut x3, mut y3) = self.coordinate_pair()?;
@@ -659,14 +661,14 @@ impl<'b> PathParser<'b> {
}
let (x2, y2) = (self.current_x + self.current_x - self.cubic_reflection_x,
- self.current_y + self.current_y - self.cubic_reflection_y);
+ self.current_y + self.current_y - self.cubic_reflection_y);
- self.emit_curve_to (x2, y2, x3, y3, x4, y4);
+ self.emit_curve_to(x2, y2, x3, y3, x4, y4);
self.whitespace()?;
- if self.lookahead_is (',') {
- assert! (self.match_char (','));
+ if self.lookahead_is(',') {
+ assert!(self.match_char(','));
self.optional_whitespace()?;
} else if !self.lookahead_is_start_of_number() {
break;
@@ -676,12 +678,12 @@ impl<'b> PathParser<'b> {
Ok(())
}
- fn curve_to (&mut self) -> Result<bool, ParseError> {
- if self.lookahead_is ('C') || self.lookahead_is ('c') {
- let absolute = if self.match_char ('C') {
+ fn curve_to(&mut self) -> Result<bool, ParseError> {
+ if self.lookahead_is('C') || self.lookahead_is('c') {
+ let absolute = if self.match_char('C') {
true
} else {
- assert! (self.match_char ('c'));
+ assert!(self.match_char('c'));
false
};
@@ -694,12 +696,12 @@ impl<'b> PathParser<'b> {
}
}
- fn smooth_curve_to (&mut self) -> Result<bool, ParseError> {
- if self.lookahead_is ('S') || self.lookahead_is ('s') {
- let absolute = if self.match_char ('S') {
+ fn smooth_curve_to(&mut self) -> Result<bool, ParseError> {
+ if self.lookahead_is('S') || self.lookahead_is('s') {
+ let absolute = if self.match_char('S') {
true
} else {
- assert! (self.match_char ('s'));
+ assert!(self.match_char('s'));
false
};
@@ -712,7 +714,7 @@ impl<'b> PathParser<'b> {
}
}
- fn quadratic_curveto_argument_sequence (&mut self, absolute: bool) -> Result<(), ParseError> {
+ fn quadratic_curveto_argument_sequence(&mut self, absolute: bool) -> Result<(), ParseError> {
loop {
let (mut a, mut b) = self.coordinate_pair()?;
@@ -727,12 +729,12 @@ impl<'b> PathParser<'b> {
d += self.current_y;
}
- self.emit_quadratic_curve_to (a, b, c, d);
+ self.emit_quadratic_curve_to(a, b, c, d);
self.whitespace()?;
- if self.lookahead_is (',') {
- assert! (self.match_char (','));
+ if self.lookahead_is(',') {
+ assert!(self.match_char(','));
self.optional_whitespace()?;
} else if !self.lookahead_is_start_of_number() {
break;
@@ -742,25 +744,27 @@ impl<'b> PathParser<'b> {
Ok(())
}
- fn quadratic_bezier_curve_to (&mut self) -> Result<bool, ParseError> {
- if self.lookahead_is ('Q') || self.lookahead_is ('q') {
- let absolute = if self.match_char ('Q') {
+ fn quadratic_bezier_curve_to(&mut self) -> Result<bool, ParseError> {
+ if self.lookahead_is('Q') || self.lookahead_is('q') {
+ let absolute = if self.match_char('Q') {
true
} else {
- assert! (self.match_char ('q'));
+ assert!(self.match_char('q'));
false
};
self.optional_whitespace()?;
- self.quadratic_curveto_argument_sequence (absolute)?;
+ self.quadratic_curveto_argument_sequence(absolute)?;
Ok(true)
} else {
Ok(false)
}
}
- fn smooth_quadratic_curveto_argument_sequence (&mut self, absolute: bool) -> Result<(), ParseError> {
+ fn smooth_quadratic_curveto_argument_sequence(&mut self,
+ absolute: bool)
+ -> Result<(), ParseError> {
loop {
let (mut c, mut d) = self.coordinate_pair()?;
@@ -770,14 +774,14 @@ impl<'b> PathParser<'b> {
}
let (a, b) = (self.current_x + self.current_x - self.quadratic_reflection_x,
- self.current_y + self.current_y - self.quadratic_reflection_y);
+ self.current_y + self.current_y - self.quadratic_reflection_y);
- self.emit_quadratic_curve_to (a, b, c, d);
+ self.emit_quadratic_curve_to(a, b, c, d);
self.whitespace()?;
- if self.lookahead_is (',') {
- assert! (self.match_char (','));
+ if self.lookahead_is(',') {
+ assert!(self.match_char(','));
self.optional_whitespace()?;
} else if !self.lookahead_is_start_of_number() {
break;
@@ -787,12 +791,12 @@ impl<'b> PathParser<'b> {
Ok(())
}
- fn smooth_quadratic_bezier_curve_to (&mut self) -> Result<bool, ParseError> {
- if self.lookahead_is ('T') || self.lookahead_is ('t') {
- let absolute = if self.match_char ('T') {
+ fn smooth_quadratic_bezier_curve_to(&mut self) -> Result<bool, ParseError> {
+ if self.lookahead_is('T') || self.lookahead_is('t') {
+ let absolute = if self.match_char('T') {
true
} else {
- assert! (self.match_char ('t'));
+ assert!(self.match_char('t'));
false
};
@@ -805,7 +809,7 @@ impl<'b> PathParser<'b> {
}
}
- fn elliptical_arc_argument_sequence (&mut self, absolute: bool) -> Result<(), ParseError> {
+ fn elliptical_arc_argument_sequence(&mut self, absolute: bool) -> Result<(), ParseError> {
loop {
let rx = self.number()?.abs();
@@ -819,7 +823,7 @@ impl<'b> PathParser<'b> {
self.optional_comma_whitespace()?;
- let large_arc = LargeArc (self.flag()?);
+ let large_arc = LargeArc(self.flag()?);
self.optional_comma_whitespace()?;
@@ -838,12 +842,12 @@ impl<'b> PathParser<'b> {
y += self.current_y;
}
- self.emit_arc (rx, ry, x_axis_rotation, large_arc, sweep, x, y);
+ self.emit_arc(rx, ry, x_axis_rotation, large_arc, sweep, x, y);
self.whitespace()?;
- if self.lookahead_is (',') {
- assert! (self.match_char (','));
+ if self.lookahead_is(',') {
+ assert!(self.match_char(','));
self.optional_whitespace()?;
} else if !self.lookahead_is_start_of_number() {
break;
@@ -853,12 +857,12 @@ impl<'b> PathParser<'b> {
Ok(())
}
- fn elliptical_arc (&mut self) -> Result<bool, ParseError> {
- if self.lookahead_is ('A') || self.lookahead_is ('a') {
- let absolute = if self.match_char ('A') {
+ fn elliptical_arc(&mut self) -> Result<bool, ParseError> {
+ if self.lookahead_is('A') || self.lookahead_is('a') {
+ let absolute = if self.match_char('A') {
true
} else {
- assert! (self.match_char ('a'));
+ assert!(self.match_char('a'));
false
};
@@ -872,39 +876,44 @@ impl<'b> PathParser<'b> {
}
}
-fn char_to_digit (c: char) -> i32 {
+fn char_to_digit(c: char) -> i32 {
c as i32 - '0' as i32
}
#[derive(Debug, PartialEq)]
pub enum ErrorKind {
UnexpectedToken,
- UnexpectedEof
+ UnexpectedEof,
}
#[derive(Debug, PartialEq)]
pub struct ParseError {
pub position: usize,
- pub kind: ErrorKind
+ pub kind: ErrorKind,
}
impl Error for ParseError {
fn description(&self) -> &str {
match self.kind {
ErrorKind::UnexpectedToken => "unexpected token",
- ErrorKind::UnexpectedEof => "unexpected end of data"
+ ErrorKind::UnexpectedEof => "unexpected end of data",
}
}
}
impl Display for ParseError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
- write!(f, "error at position {}: {}", self.position, self.description())
+ write!(f,
+ "error at position {}: {}",
+ self.position,
+ self.description())
}
}
-pub fn parse_path_into_builder (path_str: &str, builder: &mut RsvgPathBuilder) -> Result <(), ParseError> {
- let mut parser = PathParser::new (builder, path_str);
+pub fn parse_path_into_builder(path_str: &str,
+ builder: &mut RsvgPathBuilder)
+ -> Result<(), ParseError> {
+ let mut parser = PathParser::new(builder, path_str);
parser.parse()
}
@@ -917,648 +926,446 @@ mod tests {
s.find('^')
}
- fn make_parse_result(error_pos_str: &str, error_kind: Option<ErrorKind>) -> Result<(), ParseError> {
+ fn make_parse_result(error_pos_str: &str,
+ error_kind: Option<ErrorKind>)
+ -> Result<(), ParseError> {
if let Some(pos) = find_error_pos(error_pos_str) {
- Err(ParseError {
- position: pos,
- kind: error_kind.unwrap()
- })
+ Err(ParseError { position: pos,
+ kind: error_kind.unwrap(), })
} else {
assert!(error_kind.is_none());
Ok(())
}
}
- fn test_parser (path_str: &str,
- error_pos_str: &str,
- expected_commands: &[PathCommand],
- expected_error_kind: Option<ErrorKind>) {
+ fn test_parser(path_str: &str,
+ error_pos_str: &str,
+ expected_commands: &[PathCommand],
+ expected_error_kind: Option<ErrorKind>) {
let expected_result = make_parse_result(error_pos_str, expected_error_kind);
let mut builder = RsvgPathBuilder::new();
- let result = parse_path_into_builder (path_str, &mut builder);
+ let result = parse_path_into_builder(path_str, &mut builder);
- let commands = builder.get_path_commands ();
+ let commands = builder.get_path_commands();
assert_eq!(expected_commands, commands);
assert_eq!(expected_result, result);
}
- fn moveto (x: f64, y: f64) -> PathCommand {
- PathCommand::MoveTo (x, y)
+ fn moveto(x: f64, y: f64) -> PathCommand {
+ PathCommand::MoveTo(x, y)
}
- fn lineto (x: f64, y: f64) -> PathCommand {
- PathCommand::LineTo (x, y)
+ fn lineto(x: f64, y: f64) -> PathCommand {
+ PathCommand::LineTo(x, y)
}
- fn curveto (x2: f64, y2: f64, x3: f64, y3: f64, x4: f64, y4: f64) -> PathCommand {
- PathCommand::CurveTo ((x2, y2), (x3, y3), (x4, y4))
+ fn curveto(x2: f64, y2: f64, x3: f64, y3: f64, x4: f64, y4: f64) -> PathCommand {
+ PathCommand::CurveTo((x2, y2), (x3, y3), (x4, y4))
}
- fn closepath () -> PathCommand {
+ fn closepath() -> PathCommand {
PathCommand::ClosePath
}
#[test]
- fn handles_empty_data () {
- test_parser ("",
- "^",
- &Vec::<PathCommand>::new (),
- Some(ErrorKind::UnexpectedEof));
+ fn handles_empty_data() {
+ test_parser("",
+ "^",
+ &Vec::<PathCommand>::new(),
+ Some(ErrorKind::UnexpectedEof));
}
#[test]
- fn handles_numbers () {
- test_parser ("M 10 20",
- "",
- &vec![
- moveto (10.0, 20.0)
- ],
- None);
-
- test_parser ("M -10 -20",
- "",
- &vec![
- moveto (-10.0, -20.0)
- ],
- None);
-
- test_parser ("M .10 0.20",
- "",
- &vec![
- moveto (0.10, 0.20)
- ],
- None);
-
- test_parser ("M -.10 -0.20",
- "",
- &vec![
- moveto (-0.10, -0.20)
- ],
- None);
-
- test_parser ("M-.10-0.20",
- "",
- &vec![
- moveto (-0.10, -0.20)
- ],
- None);
-
- test_parser ("M10.5.50",
- "",
- &vec![
- moveto (10.5, 0.50)
- ],
- None);
-
- test_parser ("M.10.20",
- "",
- &vec![
- moveto (0.10, 0.20)
- ],
- None);
-
- test_parser ("M .10E1 .20e-4",
- "",
- &vec![
- moveto (1.0, 0.000020)
- ],
- None);
-
- test_parser ("M-.10E1-.20",
- "",
- &vec![
- moveto (-1.0, -0.20)
- ],
- None);
-
- test_parser ("M10.10E2 -0.20e3",
- "",
- &vec![
- moveto (1010.0, -200.0)
- ],
- None);
-
- test_parser ("M-10.10E2-0.20e-3",
- "",
- &vec![
- moveto (-1010.0, -0.00020)
- ],
- None);
+ fn handles_numbers() {
+ test_parser("M 10 20", "", &vec![moveto(10.0, 20.0)], None);
+
+ test_parser("M -10 -20", "", &vec![moveto(-10.0, -20.0)], None);
+
+ test_parser("M .10 0.20", "", &vec![moveto(0.10, 0.20)], None);
+
+ test_parser("M -.10 -0.20", "", &vec![moveto(-0.10, -0.20)], None);
+
+ test_parser("M-.10-0.20", "", &vec![moveto(-0.10, -0.20)], None);
+
+ test_parser("M10.5.50", "", &vec![moveto(10.5, 0.50)], None);
+
+ test_parser("M.10.20", "", &vec![moveto(0.10, 0.20)], None);
+
+ test_parser("M .10E1 .20e-4", "", &vec![moveto(1.0, 0.000020)], None);
+
+ test_parser("M-.10E1-.20", "", &vec![moveto(-1.0, -0.20)], None);
+
+ test_parser("M10.10E2 -0.20e3", "", &vec![moveto(1010.0, -200.0)], None);
+
+ test_parser("M-10.10E2-0.20e-3",
+ "",
+ &vec![moveto(-1010.0, -0.00020)],
+ None);
}
#[test]
fn detects_bogus_numbers() {
- test_parser("M+",
- " ^",
- &vec![],
- Some(ErrorKind::UnexpectedEof));
+ test_parser("M+", " ^", &vec![], Some(ErrorKind::UnexpectedEof));
- test_parser("M-",
- " ^",
- &vec![],
- Some(ErrorKind::UnexpectedEof));
+ test_parser("M-", " ^", &vec![], Some(ErrorKind::UnexpectedEof));
- test_parser("M+x",
- " ^",
- &vec![],
- Some(ErrorKind::UnexpectedToken));
+ test_parser("M+x", " ^", &vec![], Some(ErrorKind::UnexpectedToken));
- test_parser("M10e",
- " ^",
- &vec![],
- Some(ErrorKind::UnexpectedEof));
+ test_parser("M10e", " ^", &vec![], Some(ErrorKind::UnexpectedEof));
- test_parser("M10ex",
- " ^",
- &vec![],
- Some(ErrorKind::UnexpectedToken));
+ test_parser("M10ex", " ^", &vec![], Some(ErrorKind::UnexpectedToken));
- test_parser("M10e-",
- " ^",
- &vec![],
- Some(ErrorKind::UnexpectedEof));
+ test_parser("M10e-", " ^", &vec![], Some(ErrorKind::UnexpectedEof));
test_parser("M10e+x",
" ^",
&vec![],
Some(ErrorKind::UnexpectedToken));
-
}
#[test]
- fn handles_numbers_with_comma () {
- test_parser ("M 10, 20",
- "",
- &vec![
- moveto (10.0, 20.0)
- ],
- None);
-
- test_parser ("M -10,-20",
- "",
- &vec![
- moveto (-10.0, -20.0)
- ],
- None);
-
- test_parser ("M.10 , 0.20",
- "",
- &vec![
- moveto (0.10, 0.20)
- ],
- None);
-
- test_parser ("M -.10, -0.20 ",
- "",
- &vec![
- moveto (-0.10, -0.20)
- ],
- None);
-
- test_parser ("M-.10-0.20",
- "",
- &vec![
- moveto (-0.10, -0.20)
- ],
- None);
-
- test_parser ("M.10.20",
- "",
- &vec![
- moveto (0.10, 0.20)
- ],
- None);
-
- test_parser ("M .10E1,.20e-4",
- "",
- &vec![
- moveto (1.0, 0.000020)
- ],
- None);
-
- test_parser ("M-.10E-2,-.20",
- "",
- &vec![
- moveto (-0.0010, -0.20)
- ],
- None);
-
- test_parser ("M10.10E2,-0.20e3",
- "",
- &vec![
- moveto (1010.0, -200.0)
- ],
- None);
-
- test_parser ("M-10.10E2,-0.20e-3",
- "",
- &vec![
- moveto (-1010.0, -0.00020)
- ],
- None);
+ fn handles_numbers_with_comma() {
+ test_parser("M 10, 20", "", &vec![moveto(10.0, 20.0)], None);
+
+ test_parser("M -10,-20", "", &vec![moveto(-10.0, -20.0)], None);
+
+ test_parser("M.10 , 0.20", "", &vec![moveto(0.10, 0.20)], None);
+
+ test_parser("M -.10, -0.20 ", "", &vec![moveto(-0.10, -0.20)], None);
+
+ test_parser("M-.10-0.20", "", &vec![moveto(-0.10, -0.20)], None);
+
+ test_parser("M.10.20", "", &vec![moveto(0.10, 0.20)], None);
+
+ test_parser("M .10E1,.20e-4", "", &vec![moveto(1.0, 0.000020)], None);
+
+ test_parser("M-.10E-2,-.20", "", &vec![moveto(-0.0010, -0.20)], None);
+
+ test_parser("M10.10E2,-0.20e3", "", &vec![moveto(1010.0, -200.0)], None);
+
+ test_parser("M-10.10E2,-0.20e-3",
+ "",
+ &vec![moveto(-1010.0, -0.00020)],
+ None);
}
#[test]
- fn handles_single_moveto () {
- test_parser ("M 10 20 ",
- "",
- &vec![
- moveto (10.0, 20.0)
- ],
- None);
-
- test_parser ("M10,20 ",
- "",
- &vec![
- moveto (10.0, 20.0)
- ],
- None);
-
- test_parser ("M10 20 ",
- "",
- &vec![
- moveto (10.0, 20.0)
- ],
- None);
-
- test_parser (" M10,20 ",
- "",
- &vec![
- moveto (10.0, 20.0)
- ],
- None);
+ fn handles_single_moveto() {
+ test_parser("M 10 20 ", "", &vec![moveto(10.0, 20.0)], None);
+
+ test_parser("M10,20 ", "", &vec![moveto(10.0, 20.0)], None);
+
+ test_parser("M10 20 ", "", &vec![moveto(10.0, 20.0)], None);
+
+ test_parser(" M10,20 ", "", &vec![moveto(10.0, 20.0)], None);
}
#[test]
- fn handles_relative_moveto () {
- test_parser ("m10 20",
- "",
- &vec![
- moveto (10.0, 20.0)
- ],
- None);
+ fn handles_relative_moveto() {
+ test_parser("m10 20", "", &vec![moveto(10.0, 20.0)], None);
}
#[test]
- fn handles_absolute_moveto_with_implicit_lineto () {
- test_parser ("M10 20 30 40",
- "",
- &vec![
- moveto (10.0, 20.0),
- lineto (30.0, 40.0)
- ],
- None);
-
- test_parser ("M10,20,30,40",
- "",
- &vec![
- moveto (10.0, 20.0),
- lineto (30.0, 40.0)
- ],
- None);
-
- test_parser ("M.1-2,3E2-4",
- "",
- &vec![
- moveto (0.1, -2.0),
- lineto (300.0, -4.0)
- ],
- None);
+ fn handles_absolute_moveto_with_implicit_lineto() {
+ test_parser("M10 20 30 40",
+ "",
+ &vec![moveto(10.0, 20.0), lineto(30.0, 40.0)],
+ None);
+
+ test_parser("M10,20,30,40",
+ "",
+ &vec![moveto(10.0, 20.0), lineto(30.0, 40.0)],
+ None);
+
+ test_parser("M.1-2,3E2-4",
+ "",
+ &vec![moveto(0.1, -2.0), lineto(300.0, -4.0)],
+ None);
}
#[test]
- fn handles_relative_moveto_with_implicit_lineto () {
- test_parser ("m10 20 30 40",
- "",
- &vec![
- moveto (10.0, 20.0),
- lineto (40.0, 60.0)
- ],
- None);
+ fn handles_relative_moveto_with_implicit_lineto() {
+ test_parser("m10 20 30 40",
+ "",
+ &vec![moveto(10.0, 20.0), lineto(40.0, 60.0)],
+ None);
}
#[test]
- fn handles_absolute_moveto_with_implicit_linetos () {
- test_parser ("M10,20 30,40,50 60",
- "",
- &vec![
- moveto (10.0, 20.0),
- lineto (30.0, 40.0),
- lineto (50.0, 60.0)
- ],
- None);
+ fn handles_absolute_moveto_with_implicit_linetos() {
+ test_parser("M10,20 30,40,50 60",
+ "",
+ &vec![moveto(10.0, 20.0), lineto(30.0, 40.0), lineto(50.0, 60.0)],
+ None);
}
#[test]
- fn handles_relative_moveto_with_implicit_linetos () {
- test_parser ("m10 20 30 40 50 60",
- "",
- &vec![
- moveto (10.0, 20.0),
- lineto (40.0, 60.0),
- lineto (90.0, 120.0)
- ],
- None);
+ fn handles_relative_moveto_with_implicit_linetos() {
+ test_parser("m10 20 30 40 50 60",
+ "",
+ &vec![moveto(10.0, 20.0), lineto(40.0, 60.0), lineto(90.0, 120.0)],
+ None);
}
#[test]
- fn handles_absolute_moveto_moveto () {
- test_parser ("M10 20 M 30 40",
- "",
- &vec![
- moveto (10.0, 20.0),
- moveto (30.0, 40.0)
- ],
- None);
+ fn handles_absolute_moveto_moveto() {
+ test_parser("M10 20 M 30 40",
+ "",
+ &vec![moveto(10.0, 20.0), moveto(30.0, 40.0)],
+ None);
}
#[test]
- fn handles_relative_moveto_moveto () {
- test_parser ("m10 20 m 30 40",
- "",
- &vec![
- moveto (10.0, 20.0),
- moveto (40.0, 60.0)
- ],
- None);
+ fn handles_relative_moveto_moveto() {
+ test_parser("m10 20 m 30 40",
+ "",
+ &vec![moveto(10.0, 20.0), moveto(40.0, 60.0)],
+ None);
}
#[test]
- fn handles_relative_moveto_lineto_moveto () {
- test_parser ("m10 20 30 40 m 50 60",
- "",
- &vec![
- moveto (10.0, 20.0),
- lineto (40.0, 60.0),
- moveto (90.0, 120.0)
- ],
- None);
+ fn handles_relative_moveto_lineto_moveto() {
+ test_parser("m10 20 30 40 m 50 60",
+ "",
+ &vec![moveto(10.0, 20.0), lineto(40.0, 60.0), moveto(90.0, 120.0)],
+ None);
}
#[test]
- fn handles_absolute_moveto_lineto () {
- test_parser ("M10 20 L30,40",
- "",
- &vec![
- moveto (10.0, 20.0),
- lineto (30.0, 40.0)
- ],
- None);
+ fn handles_absolute_moveto_lineto() {
+ test_parser("M10 20 L30,40",
+ "",
+ &vec![moveto(10.0, 20.0), lineto(30.0, 40.0)],
+ None);
}
#[test]
- fn handles_relative_moveto_lineto () {
- test_parser ("m10 20 l30,40",
- "",
- &vec![
- moveto (10.0, 20.0),
- lineto (40.0, 60.0)
- ],
- None);
+ fn handles_relative_moveto_lineto() {
+ test_parser("m10 20 l30,40",
+ "",
+ &vec![moveto(10.0, 20.0), lineto(40.0, 60.0)],
+ None);
}
#[test]
- fn handles_relative_moveto_lineto_lineto_abs_lineto () {
- test_parser ("m10 20 30 40l30,40,50 60L200,300",
- "",
- &vec![
- moveto (10.0, 20.0),
- lineto (40.0, 60.0),
- lineto (70.0, 100.0),
- lineto (120.0, 160.0),
- lineto (200.0, 300.0)
- ],
- None);
+ fn handles_relative_moveto_lineto_lineto_abs_lineto() {
+ test_parser("m10 20 30 40l30,40,50 60L200,300",
+ "",
+ &vec![moveto(10.0, 20.0),
+ lineto(40.0, 60.0),
+ lineto(70.0, 100.0),
+ lineto(120.0, 160.0),
+ lineto(200.0, 300.0)],
+ None);
}
#[test]
- fn handles_horizontal_lineto () {
- test_parser ("M10 20 H30",
- "",
- &vec![
- moveto (10.0, 20.0),
- lineto (30.0, 20.0)
- ],
- None);
-
- test_parser ("M10 20 H30 40",
- "",
- &vec![
- moveto (10.0, 20.0),
- lineto (30.0, 20.0),
- lineto (40.0, 20.0)
- ],
- None);
-
- test_parser ("M10 20 H30,40-50",
- "",
- &vec![
- moveto (10.0, 20.0),
- lineto (30.0, 20.0),
- lineto (40.0, 20.0),
- lineto (-50.0, 20.0),
- ],
- None);
-
- test_parser ("m10 20 h30,40-50",
- "",
- &vec![
- moveto (10.0, 20.0),
- lineto (40.0, 20.0),
- lineto (80.0, 20.0),
- lineto (30.0, 20.0)
- ],
- None);
+ fn handles_horizontal_lineto() {
+ test_parser("M10 20 H30",
+ "",
+ &vec![moveto(10.0, 20.0), lineto(30.0, 20.0)],
+ None);
+
+ test_parser("M10 20 H30 40",
+ "",
+ &vec![moveto(10.0, 20.0), lineto(30.0, 20.0), lineto(40.0, 20.0)],
+ None);
+
+ test_parser("M10 20 H30,40-50",
+ "",
+ &vec![moveto(10.0, 20.0),
+ lineto(30.0, 20.0),
+ lineto(40.0, 20.0),
+ lineto(-50.0, 20.0)],
+ None);
+
+ test_parser("m10 20 h30,40-50",
+ "",
+ &vec![moveto(10.0, 20.0),
+ lineto(40.0, 20.0),
+ lineto(80.0, 20.0),
+ lineto(30.0, 20.0)],
+ None);
}
#[test]
- fn handles_vertical_lineto () {
- test_parser ("M10 20 V30",
- "",
- &vec![
- moveto (10.0, 20.0),
- lineto (10.0, 30.0)
- ],
- None);
-
- test_parser ("M10 20 V30 40",
- "",
- &vec![
- moveto (10.0, 20.0),
- lineto (10.0, 30.0),
- lineto (10.0, 40.0)
- ],
- None);
-
- test_parser ("M10 20 V30,40-50",
- "",
- &vec![
- moveto (10.0, 20.0),
- lineto (10.0, 30.0),
- lineto (10.0, 40.0),
- lineto (10.0, -50.0),
- ],
- None);
-
- test_parser ("m10 20 v30,40-50",
- "",
- &vec![
- moveto (10.0, 20.0),
- lineto (10.0, 50.0),
- lineto (10.0, 90.0),
- lineto (10.0, 40.0)
- ],
- None);
+ fn handles_vertical_lineto() {
+ test_parser("M10 20 V30",
+ "",
+ &vec![moveto(10.0, 20.0), lineto(10.0, 30.0)],
+ None);
+
+ test_parser("M10 20 V30 40",
+ "",
+ &vec![moveto(10.0, 20.0), lineto(10.0, 30.0), lineto(10.0, 40.0)],
+ None);
+
+ test_parser("M10 20 V30,40-50",
+ "",
+ &vec![moveto(10.0, 20.0),
+ lineto(10.0, 30.0),
+ lineto(10.0, 40.0),
+ lineto(10.0, -50.0)],
+ None);
+
+ test_parser("m10 20 v30,40-50",
+ "",
+ &vec![moveto(10.0, 20.0),
+ lineto(10.0, 50.0),
+ lineto(10.0, 90.0),
+ lineto(10.0, 40.0)],
+ None);
}
#[test]
- fn handles_curveto () {
- test_parser ("M10 20 C 30,40 50 60-70,80",
- "",
- &vec![
- moveto (10.0, 20.0),
- curveto (30.0, 40.0, 50.0, 60.0, -70.0, 80.0)
- ],
- None);
-
- test_parser ("M10 20 C 30,40 50 60-70,80,90 100,110 120,130,140",
- "",
- &vec![
- moveto (10.0, 20.0),
- curveto (30.0, 40.0, 50.0, 60.0, -70.0, 80.0),
- curveto (90.0, 100.0, 110.0, 120.0, 130.0, 140.0)
- ],
- None);
-
- test_parser ("m10 20 c 30,40 50 60-70,80,90 100,110 120,130,140",
- "",
- &vec![
- moveto (10.0, 20.0),
- curveto (40.0, 60.0, 60.0, 80.0, -60.0, 100.0),
- curveto (30.0, 200.0, 50.0, 220.0, 70.0, 240.0)
- ],
- None);
-
- test_parser ("m10 20 c 30,40 50 60-70,80,90 100,110 120,130,140",
- "",
- &vec![
- moveto (10.0, 20.0),
- curveto (40.0, 60.0, 60.0, 80.0, -60.0, 100.0),
- curveto (30.0, 200.0, 50.0, 220.0, 70.0, 240.0)
- ],
- None);
+ fn handles_curveto() {
+ test_parser("M10 20 C 30,40 50 60-70,80",
+ "",
+ &vec![moveto(10.0, 20.0),
+ curveto(30.0, 40.0, 50.0, 60.0, -70.0, 80.0)],
+ None);
+
+ test_parser("M10 20 C 30,40 50 60-70,80,90 100,110 120,130,140",
+ "",
+ &vec![moveto(10.0, 20.0),
+ curveto(30.0, 40.0, 50.0, 60.0, -70.0, 80.0),
+ curveto(90.0, 100.0, 110.0, 120.0, 130.0, 140.0)],
+ None);
+
+ test_parser("m10 20 c 30,40 50 60-70,80,90 100,110 120,130,140",
+ "",
+ &vec![moveto(10.0, 20.0),
+ curveto(40.0, 60.0, 60.0, 80.0, -60.0, 100.0),
+ curveto(30.0, 200.0, 50.0, 220.0, 70.0, 240.0)],
+ None);
+
+ test_parser("m10 20 c 30,40 50 60-70,80,90 100,110 120,130,140",
+ "",
+ &vec![moveto(10.0, 20.0),
+ curveto(40.0, 60.0, 60.0, 80.0, -60.0, 100.0),
+ curveto(30.0, 200.0, 50.0, 220.0, 70.0, 240.0)],
+ None);
}
#[test]
- fn handles_smooth_curveto () {
- test_parser ("M10 20 S 30,40-50,60",
- "",
- &vec![
- moveto (10.0, 20.0),
- curveto (10.0, 20.0, 30.0, 40.0, -50.0, 60.0)
- ],
- None);
-
- test_parser ("M10 20 S 30,40 50 60-70,80,90 100",
- "",
- &vec![
- moveto (10.0, 20.0),
- curveto (10.0, 20.0, 30.0, 40.0, 50.0, 60.0),
- curveto (70.0, 80.0, -70.0, 80.0, 90.0, 100.0)
- ],
- None);
-
- test_parser ("m10 20 s 30,40 50 60-70,80,90 100",
- "",
- &vec![
- moveto (10.0, 20.0),
- curveto (10.0, 20.0, 40.0, 60.0, 60.0, 80.0),
- curveto (80.0, 100.0, -10.0, 160.0, 150.0, 180.0)
- ],
- None);
+ fn handles_smooth_curveto() {
+ test_parser("M10 20 S 30,40-50,60",
+ "",
+ &vec![moveto(10.0, 20.0),
+ curveto(10.0, 20.0, 30.0, 40.0, -50.0, 60.0)],
+ None);
+
+ test_parser("M10 20 S 30,40 50 60-70,80,90 100",
+ "",
+ &vec![moveto(10.0, 20.0),
+ curveto(10.0, 20.0, 30.0, 40.0, 50.0, 60.0),
+ curveto(70.0, 80.0, -70.0, 80.0, 90.0, 100.0)],
+ None);
+
+ test_parser("m10 20 s 30,40 50 60-70,80,90 100",
+ "",
+ &vec![moveto(10.0, 20.0),
+ curveto(10.0, 20.0, 40.0, 60.0, 60.0, 80.0),
+ curveto(80.0, 100.0, -10.0, 160.0, 150.0, 180.0)],
+ None);
}
#[test]
- fn handles_quadratic_curveto () {
- test_parser ("M10 20 Q30 40 50 60",
- "",
- &vec![
- moveto (10.0, 20.0),
- curveto (70.0 / 3.0, 100.0 / 3.0, 110.0 / 3.0, 140.0 / 3.0, 50.0, 60.0)
- ],
- None);
-
- test_parser ("M10 20 Q30 40 50 60,70,80-90 100",
- "",
- &vec![
- moveto (10.0, 20.0),
- curveto (70.0 / 3.0, 100.0 / 3.0, 110.0 / 3.0, 140.0 / 3.0, 50.0, 60.0),
- curveto (190.0 / 3.0, 220.0 / 3.0, 50.0 / 3.0, 260.0 / 3.0, -90.0, 100.0)
- ],
- None);
-
- test_parser ("m10 20 q 30,40 50 60-70,80 90 100",
- "",
- &vec![
- moveto (10.0, 20.0),
- curveto (90.0 / 3.0, 140.0 / 3.0, 140.0 / 3.0, 200.0 / 3.0, 60.0, 80.0),
- curveto (40.0 / 3.0, 400.0 / 3.0, 130.0 / 3.0, 500.0 / 3.0, 150.0, 180.0)
- ],
- None);
+ fn handles_quadratic_curveto() {
+ test_parser("M10 20 Q30 40 50 60",
+ "",
+ &vec![moveto(10.0, 20.0),
+ curveto(70.0 / 3.0,
+ 100.0 / 3.0,
+ 110.0 / 3.0,
+ 140.0 / 3.0,
+ 50.0,
+ 60.0)],
+ None);
+
+ test_parser("M10 20 Q30 40 50 60,70,80-90 100",
+ "",
+ &vec![moveto(10.0, 20.0),
+ curveto(70.0 / 3.0,
+ 100.0 / 3.0,
+ 110.0 / 3.0,
+ 140.0 / 3.0,
+ 50.0,
+ 60.0),
+ curveto(190.0 / 3.0,
+ 220.0 / 3.0,
+ 50.0 / 3.0,
+ 260.0 / 3.0,
+ -90.0,
+ 100.0)],
+ None);
+
+ test_parser("m10 20 q 30,40 50 60-70,80 90 100",
+ "",
+ &vec![moveto(10.0, 20.0),
+ curveto(90.0 / 3.0,
+ 140.0 / 3.0,
+ 140.0 / 3.0,
+ 200.0 / 3.0,
+ 60.0,
+ 80.0),
+ curveto(40.0 / 3.0,
+ 400.0 / 3.0,
+ 130.0 / 3.0,
+ 500.0 / 3.0,
+ 150.0,
+ 180.0)],
+ None);
}
#[test]
- fn handles_smooth_quadratic_curveto () {
- test_parser ("M10 20 T30 40",
- "",
- &vec! [
- moveto (10.0, 20.0),
- curveto (10.0, 20.0, 50.0 / 3.0, 80.0 / 3.0, 30.0, 40.0)
- ],
- None);
-
- test_parser ("M10 20 Q30 40 50 60 T70 80",
- "",
- &vec! [
- moveto (10.0, 20.0),
- curveto (70.0 / 3.0, 100.0 / 3.0, 110.0 / 3.0, 140.0 / 3.0, 50.0, 60.0),
- curveto (190.0 / 3.0, 220.0 / 3.0, 70.0, 80.0, 70.0, 80.0)
- ],
- None);
-
- test_parser ("m10 20 q 30,40 50 60t-70,80",
- "",
- &vec! [
- moveto (10.0, 20.0),
- curveto (90.0 / 3.0, 140.0 / 3.0, 140.0 / 3.0, 200.0 / 3.0, 60.0, 80.0),
- curveto (220.0 / 3.0, 280.0 / 3.0, 50.0, 120.0, -10.0, 160.0)
- ],
- None);
+ fn handles_smooth_quadratic_curveto() {
+ test_parser("M10 20 T30 40",
+ "",
+ &vec![moveto(10.0, 20.0),
+ curveto(10.0, 20.0, 50.0 / 3.0, 80.0 / 3.0, 30.0, 40.0)],
+ None);
+
+ test_parser("M10 20 Q30 40 50 60 T70 80",
+ "",
+ &vec![moveto(10.0, 20.0),
+ curveto(70.0 / 3.0,
+ 100.0 / 3.0,
+ 110.0 / 3.0,
+ 140.0 / 3.0,
+ 50.0,
+ 60.0),
+ curveto(190.0 / 3.0, 220.0 / 3.0, 70.0, 80.0, 70.0, 80.0)],
+ None);
+
+ test_parser("m10 20 q 30,40 50 60t-70,80",
+ "",
+ &vec![moveto(10.0, 20.0),
+ curveto(90.0 / 3.0,
+ 140.0 / 3.0,
+ 140.0 / 3.0,
+ 200.0 / 3.0,
+ 60.0,
+ 80.0),
+ curveto(220.0 / 3.0, 280.0 / 3.0, 50.0, 120.0, -10.0, 160.0)],
+ None);
}
#[test]
- fn handles_close_path () {
- test_parser ("M10 20 Z",
- "",
- &vec! [
- moveto (10.0, 20.0),
- closepath ()
- ],
- None);
-
- test_parser ("m10 20 30 40 m 50 60 70 80 90 100z",
- "",
- &vec![
- moveto (10.0, 20.0),
- lineto (40.0, 60.0),
- moveto (90.0, 120.0),
- lineto (160.0, 200.0),
- lineto (250.0, 300.0),
- closepath ()
- ],
- None);
+ fn handles_close_path() {
+ test_parser("M10 20 Z", "", &vec![moveto(10.0, 20.0), closepath()], None);
+
+ test_parser("m10 20 30 40 m 50 60 70 80 90 100z",
+ "",
+ &vec![moveto(10.0, 20.0),
+ lineto(40.0, 60.0),
+ moveto(90.0, 120.0),
+ lineto(160.0, 200.0),
+ lineto(250.0, 300.0),
+ closepath()],
+ None);
}
/* FIXME: we don't have a handles_arc() because
@@ -1569,43 +1376,22 @@ mod tests {
#[test]
fn first_command_must_be_moveto() {
- test_parser(" L10 20",
- " ^",
- &vec![],
- Some(ErrorKind::UnexpectedToken));
+ test_parser(" L10 20", " ^", &vec![], Some(ErrorKind::UnexpectedToken));
}
#[test]
fn moveto_args() {
- test_parser("M",
- " ^",
- &vec![],
- Some(ErrorKind::UnexpectedEof));
+ test_parser("M", " ^", &vec![], Some(ErrorKind::UnexpectedEof));
- test_parser("M,",
- " ^",
- &vec![],
- Some(ErrorKind::UnexpectedToken));
+ test_parser("M,", " ^", &vec![], Some(ErrorKind::UnexpectedToken));
- test_parser("M10",
- " ^",
- &vec![],
- Some(ErrorKind::UnexpectedEof));
+ test_parser("M10", " ^", &vec![], Some(ErrorKind::UnexpectedEof));
- test_parser("M10,",
- " ^",
- &vec![],
- Some(ErrorKind::UnexpectedEof));
+ test_parser("M10,", " ^", &vec![], Some(ErrorKind::UnexpectedEof));
- test_parser("M10x",
- " ^",
- &vec![],
- Some(ErrorKind::UnexpectedToken));
+ test_parser("M10x", " ^", &vec![], Some(ErrorKind::UnexpectedToken));
- test_parser("M10,x",
- " ^",
- &vec![],
- Some(ErrorKind::UnexpectedToken));
+ test_parser("M10,x", " ^", &vec![], Some(ErrorKind::UnexpectedToken));
}
#[test]
@@ -1630,14 +1416,12 @@ mod tests {
fn closepath_no_args() {
test_parser("M10-20z10",
" ^",
- &vec![moveto(10.0, -20.0),
- closepath()],
+ &vec![moveto(10.0, -20.0), closepath()],
Some(ErrorKind::UnexpectedToken));
test_parser("M10-20z,",
" ^",
- &vec![moveto(10.0, -20.0),
- closepath()],
+ &vec![moveto(10.0, -20.0), closepath()],
Some(ErrorKind::UnexpectedToken));
}
@@ -1650,14 +1434,12 @@ mod tests {
test_parser("M 10,10 L 20,20,30",
" ^",
- &vec![moveto(10.0, 10.0),
- lineto(20.0, 20.0)],
+ &vec![moveto(10.0, 10.0), lineto(20.0, 20.0)],
Some(ErrorKind::UnexpectedEof));
test_parser("M 10,10 L 20,20,",
" ^",
- &vec![moveto(10.0, 10.0),
- lineto(20.0, 20.0)],
+ &vec![moveto(10.0, 10.0), lineto(20.0, 20.0)],
Some(ErrorKind::UnexpectedEof));
}
@@ -1675,8 +1457,7 @@ mod tests {
test_parser("M10-20H30,",
" ^",
- &vec![moveto(10.0, -20.0),
- lineto(30.0, -20.0)],
+ &vec![moveto(10.0, -20.0), lineto(30.0, -20.0)],
Some(ErrorKind::UnexpectedEof));
}
@@ -1694,8 +1475,7 @@ mod tests {
test_parser("M10-20v30,",
" ^",
- &vec![moveto(10.0, -20.0),
- lineto(10.0, 10.0)],
+ &vec![moveto(10.0, -20.0), lineto(10.0, 10.0)],
Some(ErrorKind::UnexpectedEof));
}
@@ -1760,8 +1540,7 @@ mod tests {
test_parser("M10-20C1,2,3,4,5,6,",
" ^",
- &vec![moveto(10.0, -20.0),
- curveto(1.0, 2.0, 3.0, 4.0, 5.0, 6.0)],
+ &vec![moveto(10.0, -20.0), curveto(1.0, 2.0, 3.0, 4.0, 5.0, 6.0)],
Some(ErrorKind::UnexpectedEof));
}
@@ -1838,13 +1617,16 @@ mod tests {
&vec![moveto(10.0, -20.0)],
Some(ErrorKind::UnexpectedEof));
- test_parser ("M10 20 Q30 40 50 60,",
- " ^",
- &vec![
- moveto (10.0, 20.0),
- curveto (70.0 / 3.0, 100.0 / 3.0, 110.0 / 3.0, 140.0 / 3.0, 50.0, 60.0)
- ],
- Some(ErrorKind::UnexpectedEof));
+ test_parser("M10 20 Q30 40 50 60,",
+ " ^",
+ &vec![moveto(10.0, 20.0),
+ curveto(70.0 / 3.0,
+ 100.0 / 3.0,
+ 110.0 / 3.0,
+ 140.0 / 3.0,
+ 50.0,
+ 60.0)],
+ Some(ErrorKind::UnexpectedEof));
}
#[test]
@@ -1858,13 +1640,11 @@ mod tests {
&vec![moveto(10.0, -20.0)],
Some(ErrorKind::UnexpectedEof));
- test_parser ("M10 20 T30 40,",
- " ^",
- &vec! [
- moveto (10.0, 20.0),
- curveto (10.0, 20.0, 50.0 / 3.0, 80.0 / 3.0, 30.0, 40.0)
- ],
- Some(ErrorKind::UnexpectedEof));
+ test_parser("M10 20 T30 40,",
+ " ^",
+ &vec![moveto(10.0, 20.0),
+ curveto(10.0, 20.0, 50.0 / 3.0, 80.0 / 3.0, 30.0, 40.0)],
+ Some(ErrorKind::UnexpectedEof));
}
#[test]
diff --git a/rsvg_internals/src/pattern.rs b/rsvg_internals/src/pattern.rs
index 57621010..04afc8ff 100644
--- a/rsvg_internals/src/pattern.rs
+++ b/rsvg_internals/src/pattern.rs
@@ -25,52 +25,50 @@ coord_units!(PatternUnits, CoordUnits::ObjectBoundingBox);
coord_units!(PatternContentUnits, CoordUnits::UserSpaceOnUse);
#[derive(Clone)]
- struct Pattern {
- pub units: Option<PatternUnits>,
- pub content_units: Option<PatternContentUnits>,
+struct Pattern {
+ pub units: Option<PatternUnits>,
+ pub content_units: Option<PatternContentUnits>,
// This Option<Option<ViewBox>> is a bit strange. We want a field
// with value None to mean, "this field isn't resolved yet". However,
// the vbox can very well be *not* specified in the SVG file.
// In that case, the fully resolved pattern will have a .vbox=Some(None) value.
- pub vbox: Option<Option<ViewBox>>,
+ pub vbox: Option<Option<ViewBox>>,
pub preserve_aspect_ratio: Option<AspectRatio>,
- pub affine: Option<cairo::Matrix>,
- pub fallback: Option<String>,
- pub x: Option<RsvgLength>,
- pub y: Option<RsvgLength>,
- pub width: Option<RsvgLength>,
- pub height: Option<RsvgLength>,
+ pub affine: Option<cairo::Matrix>,
+ pub fallback: Option<String>,
+ pub x: Option<RsvgLength>,
+ pub y: Option<RsvgLength>,
+ pub width: Option<RsvgLength>,
+ pub height: Option<RsvgLength>,
// Point back to our corresponding node, or to the fallback node which has children
- pub node: Option<Weak<Node>>
+ pub node: Option<Weak<Node>>,
}
impl Default for Pattern {
- fn default () -> Pattern {
+ fn default() -> Pattern {
// These are per the spec
- Pattern {
- units: Some(PatternUnits::default()),
- content_units: Some(PatternContentUnits::default()),
- vbox: Some(None),
- preserve_aspect_ratio: Some(AspectRatio::default()),
- affine: Some(cairo::Matrix::identity()),
- fallback: None,
- x: Some(RsvgLength::default()),
- y: Some(RsvgLength::default()),
- width: Some(RsvgLength::default()),
- height: Some(RsvgLength::default()),
- node: None
- }
+ Pattern { units: Some(PatternUnits::default()),
+ content_units: Some(PatternContentUnits::default()),
+ vbox: Some(None),
+ preserve_aspect_ratio: Some(AspectRatio::default()),
+ affine: Some(cairo::Matrix::identity()),
+ fallback: None,
+ x: Some(RsvgLength::default()),
+ y: Some(RsvgLength::default()),
+ width: Some(RsvgLength::default()),
+ height: Some(RsvgLength::default()),
+ node: None, }
}
}
-fn node_has_children (node: &Option<Weak<Node>>) -> bool {
+fn node_has_children(node: &Option<Weak<Node>>) -> bool {
match *node {
None => false,
- Some (ref weak) => {
- let ref strong_node = weak.clone ().upgrade ().unwrap ();
+ Some(ref weak) => {
+ let ref strong_node = weak.clone().upgrade().unwrap();
strong_node.has_children()
}
}
@@ -101,148 +99,143 @@ macro_rules! fallback_to (
impl Pattern {
fn unresolved() -> Pattern {
- Pattern {
- units: None,
- content_units: None,
- vbox: None,
- preserve_aspect_ratio: None,
- affine: None,
- fallback: None,
- x: None,
- y: None,
- width: None,
- height: None,
- node: None,
- }
+ Pattern { units: None,
+ content_units: None,
+ vbox: None,
+ preserve_aspect_ratio: None,
+ affine: None,
+ fallback: None,
+ x: None,
+ y: None,
+ width: None,
+ height: None,
+ node: None, }
}
- fn is_resolved (&self) -> bool {
- self.units.is_some () &&
- self.content_units.is_some () &&
- self.vbox.is_some () &&
- self.preserve_aspect_ratio.is_some () &&
- self.affine.is_some () &&
- self.x.is_some () &&
- self.y.is_some () &&
- self.width.is_some () &&
- self.height.is_some () &&
- node_has_children (&self.node)
+ fn is_resolved(&self) -> bool {
+ self.units.is_some() && self.content_units.is_some() && self.vbox.is_some()
+ && self.preserve_aspect_ratio.is_some() && self.affine.is_some() && self.x.is_some()
+ && self.y.is_some() && self.width.is_some() && self.height.is_some()
+ && node_has_children(&self.node)
}
- fn resolve_from_defaults (&mut self) {
+ fn resolve_from_defaults(&mut self) {
self.resolve_from_fallback(&Pattern::default());
- if !node_has_children (&self.node) {
+ if !node_has_children(&self.node) {
self.node = None;
}
}
- fn resolve_from_fallback (&mut self, fallback: &Pattern) {
- fallback_to! (self.units, fallback.units);
- fallback_to! (self.content_units, fallback.content_units);
- fallback_to! (self.vbox, fallback.vbox);
- fallback_to! (self.preserve_aspect_ratio, fallback.preserve_aspect_ratio);
- fallback_to! (self.affine, fallback.affine);
- fallback_to! (self.x, fallback.x);
- fallback_to! (self.y, fallback.y);
- fallback_to! (self.width, fallback.width);
- fallback_to! (self.height, fallback.height);
-
- self.fallback = fallback.fallback.clone ();
-
- if !node_has_children (&self.node) {
- self.node = fallback.node.clone ();
+ fn resolve_from_fallback(&mut self, fallback: &Pattern) {
+ fallback_to!(self.units, fallback.units);
+ fallback_to!(self.content_units, fallback.content_units);
+ fallback_to!(self.vbox, fallback.vbox);
+ fallback_to!(self.preserve_aspect_ratio, fallback.preserve_aspect_ratio);
+ fallback_to!(self.affine, fallback.affine);
+ fallback_to!(self.x, fallback.x);
+ fallback_to!(self.y, fallback.y);
+ fallback_to!(self.width, fallback.width);
+ fallback_to!(self.height, fallback.height);
+
+ self.fallback = fallback.fallback.clone();
+
+ if !node_has_children(&self.node) {
+ self.node = fallback.node.clone();
}
}
}
struct NodePattern {
- pattern: RefCell<Pattern>
+ pattern: RefCell<Pattern>,
}
impl NodePattern {
- fn new () -> NodePattern {
- NodePattern {
- pattern: RefCell::new (Pattern::unresolved ())
- }
+ fn new() -> NodePattern {
+ NodePattern { pattern: RefCell::new(Pattern::unresolved()), }
}
}
impl NodeTrait for NodePattern {
- fn set_atts (&self, node: &RsvgNode, _: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
- let mut p = self.pattern.borrow_mut ();
+ fn set_atts(&self, node: &RsvgNode, _: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
+ let mut p = self.pattern.borrow_mut();
- p.node = Some (Rc::downgrade (node));
+ p.node = Some(Rc::downgrade(node));
for (_key, attr, value) in pbag.iter() {
match attr {
- Attribute::PatternUnits =>
- p.units = Some(parse("patternUnits", value, (), None)?),
+ Attribute::PatternUnits => p.units = Some(parse("patternUnits", value, (), None)?),
- Attribute::PatternContentUnits =>
- p.content_units = Some(parse("patternContentUnits", value, (), None)?),
+ Attribute::PatternContentUnits => {
+ p.content_units = Some(parse("patternContentUnits", value, (), None)?)
+ }
- Attribute::ViewBox =>
- p.vbox = Some(Some(parse("viewBox", value, (), None)?)),
+ Attribute::ViewBox => p.vbox = Some(Some(parse("viewBox", value, (), None)?)),
- Attribute::PreserveAspectRatio =>
- p.preserve_aspect_ratio = Some(parse("preserveAspectRatio", value, (), None)?),
+ Attribute::PreserveAspectRatio => {
+ p.preserve_aspect_ratio = Some(parse("preserveAspectRatio", value, (), None)?)
+ }
- Attribute::PatternTransform =>
- p.affine = Some(parse("patternTransform", value, (), None)?),
+ Attribute::PatternTransform => {
+ p.affine = Some(parse("patternTransform", value, (), None)?)
+ }
- Attribute::XlinkHref =>
- p.fallback = Some(value.to_owned()),
+ Attribute::XlinkHref => p.fallback = Some(value.to_owned()),
- Attribute::X =>
- p.x = Some(parse("x", value, LengthDir::Horizontal, None)?),
+ Attribute::X => p.x = Some(parse("x", value, LengthDir::Horizontal, None)?),
- Attribute::Y =>
- p.y = Some(parse("y", value, LengthDir::Vertical, None)?),
+ Attribute::Y => p.y = Some(parse("y", value, LengthDir::Vertical, None)?),
- Attribute::Width =>
- p.width = Some(parse("width", value, LengthDir::Horizontal,
- Some(RsvgLength::check_nonnegative))?),
+ Attribute::Width => {
+ p.width = Some(parse("width",
+ value,
+ LengthDir::Horizontal,
+ Some(RsvgLength::check_nonnegative))?)
+ }
- Attribute::Height =>
- p.height = Some(parse("height", value, LengthDir::Vertical,
- Some(RsvgLength::check_nonnegative))?),
+ Attribute::Height => {
+ p.height = Some(parse("height",
+ value,
+ LengthDir::Vertical,
+ Some(RsvgLength::check_nonnegative))?)
+ }
_ => (),
}
}
- Ok (())
+ Ok(())
}
- fn draw (&self, _: &RsvgNode, _: *const RsvgDrawingCtx, _: i32) {
+ fn draw(&self, _: &RsvgNode, _: *const RsvgDrawingCtx, _: i32) {
// nothing; paint servers are handled specially
}
- fn get_c_impl (&self) -> *const RsvgCNodeImpl {
- unreachable! ();
+ fn get_c_impl(&self) -> *const RsvgCNodeImpl {
+ unreachable!();
}
}
trait FallbackSource {
- fn get_fallback (&mut self, name: &str) -> Option<RsvgNode>;
+ fn get_fallback(&mut self, name: &str) -> Option<RsvgNode>;
}
-fn resolve_pattern (pattern: &Pattern, fallback_source: &mut FallbackSource) -> Pattern {
- let mut result = pattern.clone ();
+fn resolve_pattern(pattern: &Pattern, fallback_source: &mut FallbackSource) -> Pattern {
+ let mut result = pattern.clone();
- while !result.is_resolved () {
+ while !result.is_resolved() {
let mut opt_fallback: Option<RsvgNode> = None;
- if let Some (ref fallback_name) = result.fallback {
- opt_fallback = fallback_source.get_fallback (&**fallback_name);
+ if let Some(ref fallback_name) = result.fallback {
+ opt_fallback = fallback_source.get_fallback(&**fallback_name);
}
- if let Some (fallback_node) = opt_fallback {
- fallback_node.with_impl (|i: &NodePattern|
- result.resolve_from_fallback (&*i.pattern.borrow ()));
+ if let Some(fallback_node) = opt_fallback {
+ fallback_node.with_impl(|i: &NodePattern| {
+ result.resolve_from_fallback(&*i.pattern.borrow())
+ });
} else {
- result.resolve_from_defaults ();
+ result.resolve_from_defaults();
break;
}
}
@@ -252,68 +245,68 @@ fn resolve_pattern (pattern: &Pattern, fallback_source: &mut FallbackSource) ->
struct NodeFallbackSource {
draw_ctx: *mut RsvgDrawingCtx,
- acquired_nodes: Vec<*mut RsvgNode>
+ acquired_nodes: Vec<*mut RsvgNode>,
}
impl NodeFallbackSource {
- fn new (draw_ctx: *mut RsvgDrawingCtx) -> NodeFallbackSource {
- NodeFallbackSource {
- draw_ctx: draw_ctx,
- acquired_nodes: Vec::<*mut RsvgNode>::new ()
- }
+ fn new(draw_ctx: *mut RsvgDrawingCtx) -> NodeFallbackSource {
+ NodeFallbackSource { draw_ctx,
+ acquired_nodes: Vec::<*mut RsvgNode>::new(), }
}
}
impl Drop for NodeFallbackSource {
- fn drop (&mut self) {
- while let Some (node) = self.acquired_nodes.pop () {
- drawing_ctx::release_node (self.draw_ctx, node);
+ fn drop(&mut self) {
+ while let Some(node) = self.acquired_nodes.pop() {
+ drawing_ctx::release_node(self.draw_ctx, node);
}
}
}
impl FallbackSource for NodeFallbackSource {
- fn get_fallback (&mut self, name: &str) -> Option<RsvgNode> {
- let raw_fallback_node = drawing_ctx::acquire_node_of_type (self.draw_ctx, name, NodeType::Pattern);
+ fn get_fallback(&mut self, name: &str) -> Option<RsvgNode> {
+ let raw_fallback_node =
+ drawing_ctx::acquire_node_of_type(self.draw_ctx, name, NodeType::Pattern);
- if raw_fallback_node.is_null () {
+ if raw_fallback_node.is_null() {
return None;
}
- self.acquired_nodes.push (raw_fallback_node);
+ self.acquired_nodes.push(raw_fallback_node);
- let fallback_node: &RsvgNode = unsafe { & *raw_fallback_node };
+ let fallback_node: &RsvgNode = unsafe { &*raw_fallback_node };
- Some (fallback_node.clone ())
+ Some(fallback_node.clone())
}
}
-fn set_pattern_on_draw_context (pattern: &Pattern,
- draw_ctx: *mut RsvgDrawingCtx,
- bbox: &RsvgBbox) -> bool {
- assert! (pattern.is_resolved ());
+fn set_pattern_on_draw_context(pattern: &Pattern,
+ draw_ctx: *mut RsvgDrawingCtx,
+ bbox: &RsvgBbox)
+ -> bool {
+ assert!(pattern.is_resolved());
- if !node_has_children (&pattern.node) {
+ if !node_has_children(&pattern.node) {
return false;
}
- let units = pattern.units.unwrap ();
- let content_units = pattern.content_units.unwrap ();
- let pattern_affine = pattern.affine.unwrap ();
- let vbox = pattern.vbox.unwrap ();
- let preserve_aspect_ratio = pattern.preserve_aspect_ratio.unwrap ();
+ let units = pattern.units.unwrap();
+ let content_units = pattern.content_units.unwrap();
+ let pattern_affine = pattern.affine.unwrap();
+ let vbox = pattern.vbox.unwrap();
+ let preserve_aspect_ratio = pattern.preserve_aspect_ratio.unwrap();
if units == PatternUnits(CoordUnits::ObjectBoundingBox) {
- drawing_ctx::push_view_box (draw_ctx, 1.0, 1.0);
+ drawing_ctx::push_view_box(draw_ctx, 1.0, 1.0);
}
- let pattern_x = pattern.x.unwrap ().normalize (draw_ctx);
- let pattern_y = pattern.y.unwrap ().normalize (draw_ctx);
- let pattern_width = pattern.width.unwrap ().normalize (draw_ctx);
- let pattern_height = pattern.height.unwrap ().normalize (draw_ctx);
+ let pattern_x = pattern.x.unwrap().normalize(draw_ctx);
+ let pattern_y = pattern.y.unwrap().normalize(draw_ctx);
+ let pattern_width = pattern.width.unwrap().normalize(draw_ctx);
+ let pattern_height = pattern.height.unwrap().normalize(draw_ctx);
if units == PatternUnits(CoordUnits::ObjectBoundingBox) {
- drawing_ctx::pop_view_box (draw_ctx);
+ drawing_ctx::pop_view_box(draw_ctx);
}
// Work out the size of the rectangle so it takes into account the object bounding box
@@ -325,7 +318,7 @@ fn set_pattern_on_draw_context (pattern: &Pattern,
PatternUnits(CoordUnits::ObjectBoundingBox) => {
bbwscale = bbox.rect.width;
bbhscale = bbox.rect.height;
- },
+ }
PatternUnits(CoordUnits::UserSpaceOnUse) => {
bbwscale = 1.0;
@@ -333,10 +326,11 @@ fn set_pattern_on_draw_context (pattern: &Pattern,
}
}
- let taffine = cairo::Matrix::multiply (&pattern_affine, &drawing_ctx::get_current_state_affine
(draw_ctx));
+ let taffine = cairo::Matrix::multiply(&pattern_affine,
+ &drawing_ctx::get_current_state_affine(draw_ctx));
- let mut scwscale = (taffine.xx * taffine.xx + taffine.xy * taffine.xy).sqrt ();
- let mut schscale = (taffine.yx * taffine.yx + taffine.yy * taffine.yy).sqrt ();
+ let mut scwscale = (taffine.xx * taffine.xx + taffine.xy * taffine.xy).sqrt();
+ let mut schscale = (taffine.yx * taffine.yx + taffine.yy * taffine.yy).sqrt();
let pw: i32 = (pattern_width * bbwscale * scwscale) as i32;
let ph: i32 = (pattern_height * bbhscale * schscale) as i32;
@@ -344,152 +338,149 @@ fn set_pattern_on_draw_context (pattern: &Pattern,
let scaled_width = pattern_width * bbwscale;
let scaled_height = pattern_height * bbhscale;
- if scaled_width.abs () < DBL_EPSILON || scaled_height.abs () < DBL_EPSILON
- || pw < 1 || ph < 1 {
+ if scaled_width.abs() < DBL_EPSILON || scaled_height.abs() < DBL_EPSILON || pw < 1 || ph < 1 {
return false;
}
scwscale = f64::from(pw) / scaled_width;
schscale = f64::from(ph) / scaled_height;
- let mut affine: cairo::Matrix = cairo::Matrix::identity ();
+ let mut affine: cairo::Matrix = cairo::Matrix::identity();
// Create the pattern coordinate system
match units {
PatternUnits(CoordUnits::ObjectBoundingBox) => {
- affine.translate (bbox.rect.x + pattern_x * bbox.rect.width,
- bbox.rect.y + pattern_y * bbox.rect.height);
- },
+ affine.translate(bbox.rect.x + pattern_x * bbox.rect.width,
+ bbox.rect.y + pattern_y * bbox.rect.height);
+ }
PatternUnits(CoordUnits::UserSpaceOnUse) => {
- affine.translate (pattern_x, pattern_y);
+ affine.translate(pattern_x, pattern_y);
}
}
// Apply the pattern transform
- affine = cairo::Matrix::multiply (&affine, &pattern_affine);
+ affine = cairo::Matrix::multiply(&affine, &pattern_affine);
let mut caffine: cairo::Matrix;
let pushed_view_box: bool;
// Create the pattern contents coordinate system
- if let Some (vbox) = vbox {
+ if let Some(vbox) = vbox {
// If there is a vbox, use that
- let (mut x, mut y, w, h) = preserve_aspect_ratio.compute (vbox.0.width,
- vbox.0.height,
- 0.0,
- 0.0,
- pattern_width * bbwscale,
- pattern_height * bbhscale);
+ let (mut x, mut y, w, h) = preserve_aspect_ratio.compute(vbox.0.width,
+ vbox.0.height,
+ 0.0,
+ 0.0,
+ pattern_width * bbwscale,
+ pattern_height * bbhscale);
x -= vbox.0.x * w / vbox.0.width;
y -= vbox.0.y * h / vbox.0.height;
- caffine = cairo::Matrix::new (w / vbox.0.width,
- 0.0,
- 0.0,
- h / vbox.0.height,
- x,
- y);
+ caffine = cairo::Matrix::new(w / vbox.0.width, 0.0, 0.0, h / vbox.0.height, x, y);
- drawing_ctx::push_view_box (draw_ctx, vbox.0.width, vbox.0.height);
+ drawing_ctx::push_view_box(draw_ctx, vbox.0.width, vbox.0.height);
pushed_view_box = true;
- } else if content_units == PatternContentUnits (CoordUnits::ObjectBoundingBox) {
+ } else if content_units == PatternContentUnits(CoordUnits::ObjectBoundingBox) {
// If coords are in terms of the bounding box, use them
- caffine = cairo::Matrix::identity ();
- caffine.scale (bbox.rect.width, bbox.rect.height);
+ caffine = cairo::Matrix::identity();
+ caffine.scale(bbox.rect.width, bbox.rect.height);
- drawing_ctx::push_view_box (draw_ctx, 1.0, 1.0);
+ drawing_ctx::push_view_box(draw_ctx, 1.0, 1.0);
pushed_view_box = true;
} else {
- caffine = cairo::Matrix::identity ();
+ caffine = cairo::Matrix::identity();
pushed_view_box = false;
}
if scwscale != 1.0 || schscale != 1.0 {
- let mut scalematrix = cairo::Matrix::identity ();
- scalematrix.scale (scwscale, schscale);
- caffine = cairo::Matrix::multiply (&caffine, &scalematrix);
+ let mut scalematrix = cairo::Matrix::identity();
+ scalematrix.scale(scwscale, schscale);
+ caffine = cairo::Matrix::multiply(&caffine, &scalematrix);
- scalematrix = cairo::Matrix::identity ();
- scalematrix.scale (1.0 / scwscale, 1.0 / schscale);
+ scalematrix = cairo::Matrix::identity();
+ scalematrix.scale(1.0 / scwscale, 1.0 / schscale);
- affine = cairo::Matrix::multiply (&scalematrix, &affine);
+ affine = cairo::Matrix::multiply(&scalematrix, &affine);
}
// Draw to another surface
- let cr_save = drawing_ctx::get_cairo_context (draw_ctx);
- drawing_ctx::state_push (draw_ctx);
+ let cr_save = drawing_ctx::get_cairo_context(draw_ctx);
+ drawing_ctx::state_push(draw_ctx);
- let surface = cr_save.get_target ().create_similar (cairo::Content::ColorAlpha, pw, ph);
+ let surface = cr_save.get_target()
+ .create_similar(cairo::Content::ColorAlpha, pw, ph);
- let cr_pattern = cairo::Context::new (&surface);
+ let cr_pattern = cairo::Context::new(&surface);
- drawing_ctx::set_cairo_context (draw_ctx, &cr_pattern);
+ drawing_ctx::set_cairo_context(draw_ctx, &cr_pattern);
// Set up transformations to be determined by the contents units
- drawing_ctx::set_current_state_affine (draw_ctx, caffine);
+ drawing_ctx::set_current_state_affine(draw_ctx, caffine);
// Draw everything
- let pattern_node = pattern.node.clone ().unwrap ().upgrade ().unwrap ();
- pattern_node.draw_children (draw_ctx, 2);
+ let pattern_node = pattern.node.clone().unwrap().upgrade().unwrap();
+ pattern_node.draw_children(draw_ctx, 2);
// Return to the original coordinate system and rendering context
- drawing_ctx::state_pop (draw_ctx);
- drawing_ctx::set_cairo_context (draw_ctx, &cr_save);
+ drawing_ctx::state_pop(draw_ctx);
+ drawing_ctx::set_cairo_context(draw_ctx, &cr_save);
if pushed_view_box {
- drawing_ctx::pop_view_box (draw_ctx);
+ drawing_ctx::pop_view_box(draw_ctx);
}
// Set the final surface as a Cairo pattern into the Cairo context
- let surface_pattern = cairo::SurfacePattern::create (&surface);
- surface_pattern.set_extend (cairo::Extend::Repeat);
+ let surface_pattern = cairo::SurfacePattern::create(&surface);
+ surface_pattern.set_extend(cairo::Extend::Repeat);
let mut matrix = affine;
- matrix.invert ();
+ matrix.invert();
- surface_pattern.set_matrix (matrix);
- surface_pattern.set_filter (cairo::Filter::Best);
+ surface_pattern.set_matrix(matrix);
+ surface_pattern.set_filter(cairo::Filter::Best);
- cr_save.set_source (&surface_pattern);
+ cr_save.set_source(&surface_pattern);
true
}
-fn resolve_fallbacks_and_set_pattern (pattern: &Pattern,
- draw_ctx: *mut RsvgDrawingCtx,
- bbox: &RsvgBbox) -> bool {
- let mut fallback_source = NodeFallbackSource::new (draw_ctx);
+fn resolve_fallbacks_and_set_pattern(pattern: &Pattern,
+ draw_ctx: *mut RsvgDrawingCtx,
+ bbox: &RsvgBbox)
+ -> bool {
+ let mut fallback_source = NodeFallbackSource::new(draw_ctx);
- let resolved = resolve_pattern (pattern, &mut fallback_source);
+ let resolved = resolve_pattern(pattern, &mut fallback_source);
- set_pattern_on_draw_context (&resolved, draw_ctx, bbox)
+ set_pattern_on_draw_context(&resolved, draw_ctx, bbox)
}
#[no_mangle]
-pub extern fn rsvg_node_pattern_new (_: *const libc::c_char, raw_parent: *const RsvgNode) -> *const RsvgNode
{
- boxed_node_new (NodeType::Pattern,
- raw_parent,
- Box::new (NodePattern::new ()))
+pub extern "C" fn rsvg_node_pattern_new(_: *const libc::c_char,
+ raw_parent: *const RsvgNode)
+ -> *const RsvgNode {
+ boxed_node_new(NodeType::Pattern, raw_parent, Box::new(NodePattern::new()))
}
-pub fn pattern_resolve_fallbacks_and_set_pattern (node: &RsvgNode,
- draw_ctx: *mut RsvgDrawingCtx,
- bbox: &RsvgBbox) -> bool {
- assert! (node.get_type () == NodeType::Pattern);
+pub fn pattern_resolve_fallbacks_and_set_pattern(node: &RsvgNode,
+ draw_ctx: *mut RsvgDrawingCtx,
+ bbox: &RsvgBbox)
+ -> bool {
+ assert!(node.get_type() == NodeType::Pattern);
let mut did_set_pattern = false;
- node.with_impl (|node_pattern: &NodePattern| {
- let pattern = &*node_pattern.pattern.borrow ();
- did_set_pattern = resolve_fallbacks_and_set_pattern (pattern, draw_ctx, bbox);
- });
+ node.with_impl(|node_pattern: &NodePattern| {
+ let pattern = &*node_pattern.pattern.borrow();
+ did_set_pattern = resolve_fallbacks_and_set_pattern(pattern, draw_ctx, bbox);
+ });
did_set_pattern
}
diff --git a/rsvg_internals/src/property_bag.rs b/rsvg_internals/src/property_bag.rs
index cc296226..603bb6d3 100644
--- a/rsvg_internals/src/property_bag.rs
+++ b/rsvg_internals/src/property_bag.rs
@@ -1,7 +1,7 @@
use libc;
-use glib_sys;
use glib::translate::*;
+use glib_sys;
use std::ffi::{CStr, CString};
use std::ops::Deref;
@@ -124,7 +124,8 @@ impl<'a> Iterator for PropertyBagIter<'a> {
type Item = (&'a str, Attribute, &'a str);
fn next(&mut self) -> Option<Self::Item> {
- self.0.next().map(|(k, a, v)| (k.to_str_utf8(), a, v.to_str_utf8()))
+ self.0.next()
+ .map(|(k, a, v)| (k.to_str_utf8(), a, v.to_str_utf8()))
}
}
@@ -137,20 +138,22 @@ impl<'a> Iterator for PropertyBagCStrIter<'a> {
}
#[no_mangle]
-pub extern fn rsvg_property_bag_new<'a>(atts: *const *const libc::c_char) -> *const PropertyBag<'a> {
+pub extern "C" fn rsvg_property_bag_new<'a>(atts: *const *const libc::c_char)
+ -> *const PropertyBag<'a> {
let pbag = unsafe { PropertyBag::new_from_key_value_pairs(atts) };
Box::into_raw(Box::new(pbag))
}
#[no_mangle]
-pub extern fn rsvg_property_bag_free(pbag: *mut PropertyBag) {
+pub extern "C" fn rsvg_property_bag_free(pbag: *mut PropertyBag) {
unsafe {
let _ = Box::from_raw(pbag);
}
}
#[no_mangle]
-pub extern fn rsvg_property_bag_iter_begin(pbag: *const PropertyBag) -> *mut PropertyBagCStrIter {
+pub extern "C" fn rsvg_property_bag_iter_begin(pbag: *const PropertyBag)
+ -> *mut PropertyBagCStrIter {
assert!(!pbag.is_null());
let pbag = unsafe { &*pbag };
@@ -158,12 +161,11 @@ pub extern fn rsvg_property_bag_iter_begin(pbag: *const PropertyBag) -> *mut Pro
}
#[no_mangle]
-pub extern fn rsvg_property_bag_iter_next(iter: *mut PropertyBagCStrIter,
- out_key: *mut *const libc::c_char,
- out_attr: *mut Attribute,
- out_value: *mut *const libc::c_char)
- -> glib_sys::gboolean
-{
+pub extern "C" fn rsvg_property_bag_iter_next(iter: *mut PropertyBagCStrIter,
+ out_key: *mut *const libc::c_char,
+ out_attr: *mut Attribute,
+ out_value: *mut *const libc::c_char)
+ -> glib_sys::gboolean {
assert!(!iter.is_null());
let iter = unsafe { &mut *iter };
@@ -184,7 +186,7 @@ pub extern fn rsvg_property_bag_iter_next(iter: *mut PropertyBagCStrIter,
}
#[no_mangle]
-pub extern fn rsvg_property_bag_iter_end(iter: *mut PropertyBagCStrIter) {
+pub extern "C" fn rsvg_property_bag_iter_end(iter: *mut PropertyBagCStrIter) {
assert!(!iter.is_null());
unsafe { Box::from_raw(iter) };
@@ -204,12 +206,10 @@ mod tests {
#[test]
fn property_bag_iters() {
- let pairs = [
- CString::new("rx").unwrap(),
- CString::new("1").unwrap(),
- CString::new("ry").unwrap(),
- CString::new("2").unwrap(),
- ];
+ let pairs = [CString::new("rx").unwrap(),
+ CString::new("1").unwrap(),
+ CString::new("ry").unwrap(),
+ CString::new("2").unwrap()];
let mut v = Vec::new();
@@ -244,12 +244,10 @@ mod tests {
#[test]
fn property_bag_can_iterate_from_c() {
- let pairs = [
- CString::new("rx").unwrap(),
- CString::new("1").unwrap(),
- CString::new("ry").unwrap(),
- CString::new("2").unwrap(),
- ];
+ let pairs = [CString::new("rx").unwrap(),
+ CString::new("1").unwrap(),
+ CString::new("ry").unwrap(),
+ CString::new("2").unwrap()];
let mut v = Vec::new();
@@ -273,7 +271,8 @@ mod tests {
while from_glib(rsvg_property_bag_iter_next(iter,
&mut key as *mut _,
&mut att as *mut _,
- &mut val as *mut _)) {
+ &mut val as *mut _))
+ {
let k = unsafe { CStr::from_ptr(key).to_str_utf8() };
let v = unsafe { CStr::from_ptr(val).to_str_utf8() };
diff --git a/rsvg_internals/src/shapes.rs b/rsvg_internals/src/shapes.rs
index 9358ee0b..d5f6da85 100644
--- a/rsvg_internals/src/shapes.rs
+++ b/rsvg_internals/src/shapes.rs
@@ -1,7 +1,7 @@
use libc;
-use std::cell::RefCell;
use std::cell::Cell;
+use std::cell::RefCell;
use attributes::Attribute;
use drawing_ctx;
@@ -17,26 +17,26 @@ use path_parser;
use property_bag::PropertyBag;
use state::RsvgState;
-fn render_path_builder (builder: &RsvgPathBuilder,
- draw_ctx: *const RsvgDrawingCtx,
- state: *mut RsvgState,
- dominate: i32,
- render_markers: bool) {
- drawing_ctx::state_reinherit_top (draw_ctx, state, dominate);
- drawing_ctx::render_path_builder (draw_ctx, builder);
+fn render_path_builder(builder: &RsvgPathBuilder,
+ draw_ctx: *const RsvgDrawingCtx,
+ state: *mut RsvgState,
+ dominate: i32,
+ render_markers: bool) {
+ drawing_ctx::state_reinherit_top(draw_ctx, state, dominate);
+ drawing_ctx::render_path_builder(draw_ctx, builder);
if render_markers {
- marker::render_markers_for_path_builder (builder, draw_ctx);
+ marker::render_markers_for_path_builder(builder, draw_ctx);
}
}
-fn render_ellipse (cx: f64,
- cy: f64,
- rx: f64,
- ry: f64,
- node: &RsvgNode,
- draw_ctx: *const RsvgDrawingCtx,
- dominate: i32) {
+fn render_ellipse(cx: f64,
+ cy: f64,
+ rx: f64,
+ ry: f64,
+ node: &RsvgNode,
+ draw_ctx: *const RsvgDrawingCtx,
+ dominate: i32) {
// Per the spec, rx and ry must be nonnegative
if rx <= 0.0 || ry <= 0.0 {
@@ -48,52 +48,62 @@ fn render_ellipse (cx: f64,
// approximate an ellipse using 4 Bézier curves
- let mut builder = RsvgPathBuilder::new ();
-
- builder.move_to (cx + rx, cy);
-
- builder.curve_to (cx + rx, cy - arc_magic * ry,
- cx + arc_magic * rx, cy - ry,
- cx, cy - ry);
-
- builder.curve_to (cx - arc_magic * rx, cy - ry,
- cx - rx, cy - arc_magic * ry,
- cx - rx, cy);
-
- builder.curve_to (cx - rx, cy + arc_magic * ry,
- cx - arc_magic * rx, cy + ry,
- cx, cy + ry);
-
- builder.curve_to (cx + arc_magic * rx, cy + ry,
- cx + rx, cy + arc_magic * ry,
- cx + rx, cy);
-
- builder.close_path ();
-
- render_path_builder (&builder, draw_ctx, node.get_state (), dominate, false);
+ let mut builder = RsvgPathBuilder::new();
+
+ builder.move_to(cx + rx, cy);
+
+ builder.curve_to(cx + rx,
+ cy - arc_magic * ry,
+ cx + arc_magic * rx,
+ cy - ry,
+ cx,
+ cy - ry);
+
+ builder.curve_to(cx - arc_magic * rx,
+ cy - ry,
+ cx - rx,
+ cy - arc_magic * ry,
+ cx - rx,
+ cy);
+
+ builder.curve_to(cx - rx,
+ cy + arc_magic * ry,
+ cx - arc_magic * rx,
+ cy + ry,
+ cx,
+ cy + ry);
+
+ builder.curve_to(cx + arc_magic * rx,
+ cy + ry,
+ cx + rx,
+ cy + arc_magic * ry,
+ cx + rx,
+ cy);
+
+ builder.close_path();
+
+ render_path_builder(&builder, draw_ctx, node.get_state(), dominate, false);
}
-/***** NodePath *****/
+/***** NodePath **** * * * * **/
struct NodePath {
- builder: RefCell<Option<RsvgPathBuilder>>
+ builder: RefCell<Option<RsvgPathBuilder>>,
}
impl NodePath {
- fn new () -> NodePath {
- NodePath {
- builder: RefCell::new (None)
- }
+ fn new() -> NodePath {
+ NodePath { builder: RefCell::new(None), }
}
}
impl NodeTrait for NodePath {
- fn set_atts (&self, _: &RsvgNode, _: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
+ fn set_atts(&self, _: &RsvgNode, _: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
for (_key, attr, value) in pbag.iter() {
if attr == Attribute::D {
- let mut builder = RsvgPathBuilder::new ();
+ let mut builder = RsvgPathBuilder::new();
- if path_parser::parse_path_into_builder (value, &mut builder).is_err() {
+ if path_parser::parse_path_into_builder(value, &mut builder).is_err() {
// FIXME: we don't propagate errors upstream, but creating a partial
// path is OK per the spec
}
@@ -102,144 +112,142 @@ impl NodeTrait for NodePath {
}
}
- Ok (())
+ Ok(())
}
- fn draw (&self, node: &RsvgNode, draw_ctx: *const RsvgDrawingCtx, dominate: i32) {
+ fn draw(&self, node: &RsvgNode, draw_ctx: *const RsvgDrawingCtx, dominate: i32) {
if let Some(ref builder) = *self.builder.borrow() {
- render_path_builder (builder, draw_ctx, node.get_state (), dominate, true);
+ render_path_builder(builder, draw_ctx, node.get_state(), dominate, true);
}
}
- fn get_c_impl (&self) -> *const RsvgCNodeImpl {
- unreachable! ();
+ fn get_c_impl(&self) -> *const RsvgCNodeImpl {
+ unreachable!();
}
}
-/***** NodePoly *****/
+/***** NodePoly **** * * * * **/
#[derive(Debug, PartialEq)]
enum PolyKind {
Open,
- Closed
+ Closed,
}
struct NodePoly {
- points: RefCell <Option<Vec<(f64, f64)>>>,
- kind: PolyKind
+ points: RefCell<Option<Vec<(f64, f64)>>>,
+ kind: PolyKind,
}
impl NodePoly {
- fn new (kind: PolyKind) -> NodePoly {
- NodePoly {
- points: RefCell::new (None),
- kind: kind
- }
+ fn new(kind: PolyKind) -> NodePoly {
+ NodePoly { points: RefCell::new(None),
+ kind, }
}
}
impl NodeTrait for NodePoly {
- fn set_atts (&self, _: &RsvgNode, _: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
+ fn set_atts(&self, _: &RsvgNode, _: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
for (key, attr, value) in pbag.iter() {
// support for svg < 1.0 which used verts
if attr == Attribute::Points || attr == Attribute::Verts {
- let result = parsers::list_of_points (value.trim ());
+ let result = parsers::list_of_points(value.trim());
match result {
- Ok (v) => {
- *self.points.borrow_mut () = Some (v);
+ Ok(v) => {
+ *self.points.borrow_mut() = Some(v);
break;
- },
+ }
- Err (e) => { return Err (NodeError::parse_error (key, e)); }
+ Err(e) => {
+ return Err(NodeError::parse_error(key, e));
+ }
}
}
}
- Ok (())
+ Ok(())
}
- fn draw (&self, node: &RsvgNode, draw_ctx: *const RsvgDrawingCtx, dominate: i32) {
- if let Some (ref points) = *self.points.borrow () {
- let mut builder = RsvgPathBuilder::new ();
+ fn draw(&self, node: &RsvgNode, draw_ctx: *const RsvgDrawingCtx, dominate: i32) {
+ if let Some(ref points) = *self.points.borrow() {
+ let mut builder = RsvgPathBuilder::new();
- for (i, &(x, y)) in points.iter ().enumerate () {
+ for (i, &(x, y)) in points.iter().enumerate() {
if i == 0 {
- builder.move_to (x, y);
+ builder.move_to(x, y);
} else {
- builder.line_to (x, y);
+ builder.line_to(x, y);
}
}
if self.kind == PolyKind::Closed {
- builder.close_path ();
+ builder.close_path();
}
- render_path_builder (&builder, draw_ctx, node.get_state (), dominate, true);
+ render_path_builder(&builder, draw_ctx, node.get_state(), dominate, true);
}
}
- fn get_c_impl (&self) -> *const RsvgCNodeImpl {
- unreachable! ();
+ fn get_c_impl(&self) -> *const RsvgCNodeImpl {
+ unreachable!();
}
}
-/***** NodeLine *****/
+/***** NodeLine **** * * * * **/
struct NodeLine {
x1: Cell<RsvgLength>,
y1: Cell<RsvgLength>,
x2: Cell<RsvgLength>,
- y2: Cell<RsvgLength>
+ y2: Cell<RsvgLength>,
}
impl NodeLine {
- fn new () -> NodeLine {
- NodeLine {
- x1: Cell::new (RsvgLength::default ()),
- y1: Cell::new (RsvgLength::default ()),
- x2: Cell::new (RsvgLength::default ()),
- y2: Cell::new (RsvgLength::default ())
- }
+ fn new() -> NodeLine {
+ NodeLine { x1: Cell::new(RsvgLength::default()),
+ y1: Cell::new(RsvgLength::default()),
+ x2: Cell::new(RsvgLength::default()),
+ y2: Cell::new(RsvgLength::default()), }
}
}
impl NodeTrait for NodeLine {
- fn set_atts (&self, _: &RsvgNode, _: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
+ fn set_atts(&self, _: &RsvgNode, _: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
for (_key, attr, value) in pbag.iter() {
match attr {
Attribute::X1 => self.x1.set(parse("x1", value, LengthDir::Horizontal, None)?),
Attribute::Y1 => self.y1.set(parse("y1", value, LengthDir::Vertical, None)?),
Attribute::X2 => self.x2.set(parse("x2", value, LengthDir::Horizontal, None)?),
Attribute::Y2 => self.y2.set(parse("y2", value, LengthDir::Vertical, None)?),
- _ => ()
+ _ => (),
}
}
- Ok (())
+ Ok(())
}
- fn draw (&self, node: &RsvgNode, draw_ctx: *const RsvgDrawingCtx, dominate: i32) {
- let mut builder = RsvgPathBuilder::new ();
+ fn draw(&self, node: &RsvgNode, draw_ctx: *const RsvgDrawingCtx, dominate: i32) {
+ let mut builder = RsvgPathBuilder::new();
- let x1 = self.x1.get ().normalize (draw_ctx);
- let y1 = self.y1.get ().normalize (draw_ctx);
- let x2 = self.x2.get ().normalize (draw_ctx);
- let y2 = self.y2.get ().normalize (draw_ctx);
+ let x1 = self.x1.get().normalize(draw_ctx);
+ let y1 = self.y1.get().normalize(draw_ctx);
+ let x2 = self.x2.get().normalize(draw_ctx);
+ let y2 = self.y2.get().normalize(draw_ctx);
- builder.move_to (x1, y1);
- builder.line_to (x2, y2);
+ builder.move_to(x1, y1);
+ builder.line_to(x2, y2);
- render_path_builder (&builder, draw_ctx, node.get_state (), dominate, true);
+ render_path_builder(&builder, draw_ctx, node.get_state(), dominate, true);
}
- fn get_c_impl (&self) -> *const RsvgCNodeImpl {
- unreachable! ();
+ fn get_c_impl(&self) -> *const RsvgCNodeImpl {
+ unreachable!();
}
}
-/***** NodeRect *****/
+/***** NodeRect **** * * * * **/
struct NodeRect {
// x, y, width, height
@@ -250,25 +258,23 @@ struct NodeRect {
// Radiuses for rounded corners
rx: Cell<Option<RsvgLength>>,
- ry: Cell<Option<RsvgLength>>
+ ry: Cell<Option<RsvgLength>>,
}
impl NodeRect {
- fn new () -> NodeRect {
- NodeRect {
- x: Cell::new (RsvgLength::default ()),
- y: Cell::new (RsvgLength::default ()),
- w: Cell::new (RsvgLength::default ()),
- h: Cell::new (RsvgLength::default ()),
-
- rx: Cell::new (None),
- ry: Cell::new (None)
- }
+ fn new() -> NodeRect {
+ NodeRect { x: Cell::new(RsvgLength::default()),
+ y: Cell::new(RsvgLength::default()),
+ w: Cell::new(RsvgLength::default()),
+ h: Cell::new(RsvgLength::default()),
+
+ rx: Cell::new(None),
+ ry: Cell::new(None), }
}
}
impl NodeTrait for NodeRect {
- fn set_atts (&self, _: &RsvgNode, _: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
+ fn set_atts(&self, _: &RsvgNode, _: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
for (_key, attr, value) in pbag.iter() {
match attr {
Attribute::X => self.x.set (parse ("x", value, LengthDir::Horizontal, None)?),
@@ -289,38 +295,38 @@ impl NodeTrait for NodeRect {
}
}
- Ok (())
+ Ok(())
}
- fn draw (&self, node: &RsvgNode, draw_ctx: *const RsvgDrawingCtx, dominate: i32) {
- let x = self.x.get ().normalize (draw_ctx);
- let y = self.y.get ().normalize (draw_ctx);
+ fn draw(&self, node: &RsvgNode, draw_ctx: *const RsvgDrawingCtx, dominate: i32) {
+ let x = self.x.get().normalize(draw_ctx);
+ let y = self.y.get().normalize(draw_ctx);
- let w = self.w.get ().normalize (draw_ctx);
- let h = self.h.get ().normalize (draw_ctx);
+ let w = self.w.get().normalize(draw_ctx);
+ let h = self.h.get().normalize(draw_ctx);
let mut rx;
let mut ry;
- match (self.rx.get (), self.ry.get ()) {
+ match (self.rx.get(), self.ry.get()) {
(None, None) => {
rx = 0.0;
ry = 0.0;
- },
+ }
- (Some (_rx), None) => {
- rx = _rx.normalize (draw_ctx);
- ry = _rx.normalize (draw_ctx);
- },
+ (Some(_rx), None) => {
+ rx = _rx.normalize(draw_ctx);
+ ry = _rx.normalize(draw_ctx);
+ }
- (None, Some (_ry)) => {
- rx = _ry.normalize (draw_ctx);
- ry = _ry.normalize (draw_ctx);
- },
+ (None, Some(_ry)) => {
+ rx = _ry.normalize(draw_ctx);
+ ry = _ry.normalize(draw_ctx);
+ }
- (Some (_rx), Some (_ry)) => {
- rx = _rx.normalize (draw_ctx);
- ry = _ry.normalize (draw_ctx);
+ (Some(_rx), Some(_ry)) => {
+ rx = _rx.normalize(draw_ctx);
+ ry = _ry.normalize(draw_ctx);
}
}
@@ -351,17 +357,17 @@ impl NodeTrait for NodeRect {
rx = 0.0;
}
- let mut builder = RsvgPathBuilder::new ();
+ let mut builder = RsvgPathBuilder::new();
if rx == 0.0 {
/* Easy case, no rounded corners */
- builder.move_to (x, y);
- builder.line_to (x + w, y);
- builder.line_to (x + w, y + h);
- builder.line_to (x, y + h);
- builder.line_to (x, y);
- builder.close_path ();
+ builder.move_to(x, y);
+ builder.line_to(x + w, y);
+ builder.line_to(x + w, y + h);
+ builder.line_to(x, y + h);
+ builder.line_to(x, y);
+ builder.close_path();
} else {
/* Hard case, rounded corners
*
@@ -428,161 +434,173 @@ impl NodeTrait for NodeRect {
builder.close_path ();
}
- render_path_builder (&builder, draw_ctx, node.get_state (), dominate, false);
+ render_path_builder(&builder, draw_ctx, node.get_state(), dominate, false);
}
- fn get_c_impl (&self) -> *const RsvgCNodeImpl {
- unreachable! ();
+ fn get_c_impl(&self) -> *const RsvgCNodeImpl {
+ unreachable!();
}
}
-/***** NodeCircle *****/
+/***** NodeCircle **** * * * * **/
struct NodeCircle {
cx: Cell<RsvgLength>,
cy: Cell<RsvgLength>,
- r: Cell<RsvgLength>
+ r: Cell<RsvgLength>,
}
impl NodeCircle {
- fn new () -> NodeCircle {
- NodeCircle {
- cx: Cell::new (RsvgLength::default ()),
- cy: Cell::new (RsvgLength::default ()),
- r: Cell::new (RsvgLength::default ()),
- }
+ fn new() -> NodeCircle {
+ NodeCircle { cx: Cell::new(RsvgLength::default()),
+ cy: Cell::new(RsvgLength::default()),
+ r: Cell::new(RsvgLength::default()), }
}
}
impl NodeTrait for NodeCircle {
- fn set_atts (&self, _: &RsvgNode, _: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
+ fn set_atts(&self, _: &RsvgNode, _: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
for (_key, attr, value) in pbag.iter() {
match attr {
Attribute::Cx => self.cx.set(parse("cx", value, LengthDir::Horizontal, None)?),
Attribute::Cy => self.cy.set(parse("cy", value, LengthDir::Vertical, None)?),
- Attribute::R => self.r.set (parse("r", value, LengthDir::Both,
- Some(RsvgLength::check_nonnegative))?),
+ Attribute::R => {
+ self.r.set(parse("r",
+ value,
+ LengthDir::Both,
+ Some(RsvgLength::check_nonnegative))?)
+ }
_ => (),
}
}
- Ok (())
+ Ok(())
}
- fn draw (&self, node: &RsvgNode, draw_ctx: *const RsvgDrawingCtx, dominate: i32) {
- let cx = self.cx.get ().normalize (draw_ctx);
- let cy = self.cy.get ().normalize (draw_ctx);
- let r = self.r.get ().normalize (draw_ctx);
+ fn draw(&self, node: &RsvgNode, draw_ctx: *const RsvgDrawingCtx, dominate: i32) {
+ let cx = self.cx.get().normalize(draw_ctx);
+ let cy = self.cy.get().normalize(draw_ctx);
+ let r = self.r.get().normalize(draw_ctx);
- render_ellipse (cx, cy, r, r, node, draw_ctx, dominate);
+ render_ellipse(cx, cy, r, r, node, draw_ctx, dominate);
}
- fn get_c_impl (&self) -> *const RsvgCNodeImpl {
- unreachable! ();
+ fn get_c_impl(&self) -> *const RsvgCNodeImpl {
+ unreachable!();
}
}
-/***** NodeEllipse *****/
+/***** NodeEllipse **** * * * * **/
struct NodeEllipse {
- cx: Cell <RsvgLength>,
- cy: Cell <RsvgLength>,
- rx: Cell <RsvgLength>,
- ry: Cell <RsvgLength>
+ cx: Cell<RsvgLength>,
+ cy: Cell<RsvgLength>,
+ rx: Cell<RsvgLength>,
+ ry: Cell<RsvgLength>,
}
impl NodeEllipse {
- fn new () -> NodeEllipse {
- NodeEllipse {
- cx: Cell::new (RsvgLength::default ()),
- cy: Cell::new (RsvgLength::default ()),
- rx: Cell::new (RsvgLength::default ()),
- ry: Cell::new (RsvgLength::default ()),
- }
+ fn new() -> NodeEllipse {
+ NodeEllipse { cx: Cell::new(RsvgLength::default()),
+ cy: Cell::new(RsvgLength::default()),
+ rx: Cell::new(RsvgLength::default()),
+ ry: Cell::new(RsvgLength::default()), }
}
}
impl NodeTrait for NodeEllipse {
- fn set_atts (&self, _: &RsvgNode, _: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
+ fn set_atts(&self, _: &RsvgNode, _: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
for (_key, attr, value) in pbag.iter() {
match attr {
Attribute::Cx => self.cx.set(parse("cx", value, LengthDir::Horizontal, None)?),
Attribute::Cy => self.cy.set(parse("cy", value, LengthDir::Vertical, None)?),
- Attribute::Rx => self.rx.set(parse("rx", value, LengthDir::Horizontal,
- Some(RsvgLength::check_nonnegative))?),
- Attribute::Ry => self.ry.set(parse("ry", value, LengthDir::Vertical,
- Some(RsvgLength::check_nonnegative))?),
+ Attribute::Rx => {
+ self.rx.set(parse("rx",
+ value,
+ LengthDir::Horizontal,
+ Some(RsvgLength::check_nonnegative))?)
+ }
+ Attribute::Ry => {
+ self.ry.set(parse("ry",
+ value,
+ LengthDir::Vertical,
+ Some(RsvgLength::check_nonnegative))?)
+ }
_ => (),
}
}
- Ok (())
+ Ok(())
}
- fn draw (&self, node: &RsvgNode, draw_ctx: *const RsvgDrawingCtx, dominate: i32) {
- let cx = self.cx.get ().normalize (draw_ctx);
- let cy = self.cy.get ().normalize (draw_ctx);
- let rx = self.rx.get ().normalize (draw_ctx);
- let ry = self.ry.get ().normalize (draw_ctx);
+ fn draw(&self, node: &RsvgNode, draw_ctx: *const RsvgDrawingCtx, dominate: i32) {
+ let cx = self.cx.get().normalize(draw_ctx);
+ let cy = self.cy.get().normalize(draw_ctx);
+ let rx = self.rx.get().normalize(draw_ctx);
+ let ry = self.ry.get().normalize(draw_ctx);
- render_ellipse (cx, cy, rx, ry, node, draw_ctx, dominate);
- }
+ render_ellipse(cx, cy, rx, ry, node, draw_ctx, dominate);
+ }
- fn get_c_impl (&self) -> *const RsvgCNodeImpl {
- unreachable! ();
+ fn get_c_impl(&self) -> *const RsvgCNodeImpl {
+ unreachable!();
}
}
-/***** C Prototypes *****/
+/***** C Prototypes **** * * * * **/
#[no_mangle]
-pub extern fn rsvg_node_path_new (_: *const libc::c_char, raw_parent: *const RsvgNode) -> *const RsvgNode {
- boxed_node_new (NodeType::Path,
- raw_parent,
- Box::new (NodePath::new ()))
+pub extern "C" fn rsvg_node_path_new(_: *const libc::c_char,
+ raw_parent: *const RsvgNode)
+ -> *const RsvgNode {
+ boxed_node_new(NodeType::Path, raw_parent, Box::new(NodePath::new()))
}
#[no_mangle]
-pub extern fn rsvg_node_polygon_new (_: *const libc::c_char, raw_parent: *const RsvgNode) -> *const RsvgNode
{
- boxed_node_new (NodeType::Path,
- raw_parent,
- Box::new (NodePoly::new (PolyKind::Closed)))
+pub extern "C" fn rsvg_node_polygon_new(_: *const libc::c_char,
+ raw_parent: *const RsvgNode)
+ -> *const RsvgNode {
+ boxed_node_new(NodeType::Path,
+ raw_parent,
+ Box::new(NodePoly::new(PolyKind::Closed)))
}
#[no_mangle]
-pub extern fn rsvg_node_polyline_new (_: *const libc::c_char, raw_parent: *const RsvgNode) -> *const
RsvgNode {
- boxed_node_new (NodeType::Path,
- raw_parent,
- Box::new (NodePoly::new (PolyKind::Open)))
+pub extern "C" fn rsvg_node_polyline_new(_: *const libc::c_char,
+ raw_parent: *const RsvgNode)
+ -> *const RsvgNode {
+ boxed_node_new(NodeType::Path,
+ raw_parent,
+ Box::new(NodePoly::new(PolyKind::Open)))
}
#[no_mangle]
-pub extern fn rsvg_node_line_new (_: *const libc::c_char, raw_parent: *const RsvgNode) -> *const RsvgNode {
- boxed_node_new (NodeType::Line,
- raw_parent,
- Box::new (NodeLine::new ()))
+pub extern "C" fn rsvg_node_line_new(_: *const libc::c_char,
+ raw_parent: *const RsvgNode)
+ -> *const RsvgNode {
+ boxed_node_new(NodeType::Line, raw_parent, Box::new(NodeLine::new()))
}
#[no_mangle]
-pub extern fn rsvg_node_rect_new (_: *const libc::c_char, raw_parent: *const RsvgNode) -> *const RsvgNode {
- boxed_node_new (NodeType::Rect,
- raw_parent,
- Box::new (NodeRect::new ()))
+pub extern "C" fn rsvg_node_rect_new(_: *const libc::c_char,
+ raw_parent: *const RsvgNode)
+ -> *const RsvgNode {
+ boxed_node_new(NodeType::Rect, raw_parent, Box::new(NodeRect::new()))
}
#[no_mangle]
-pub extern fn rsvg_node_circle_new (_: *const libc::c_char, raw_parent: *const RsvgNode) -> *const RsvgNode {
- boxed_node_new (NodeType::Circle,
- raw_parent,
- Box::new (NodeCircle::new ()))
+pub extern "C" fn rsvg_node_circle_new(_: *const libc::c_char,
+ raw_parent: *const RsvgNode)
+ -> *const RsvgNode {
+ boxed_node_new(NodeType::Circle, raw_parent, Box::new(NodeCircle::new()))
}
#[no_mangle]
-pub extern fn rsvg_node_ellipse_new (_: *const libc::c_char, raw_parent: *const RsvgNode) -> *const RsvgNode
{
- boxed_node_new (NodeType::Ellipse,
- raw_parent,
- Box::new (NodeEllipse::new ()))
+pub extern "C" fn rsvg_node_ellipse_new(_: *const libc::c_char,
+ raw_parent: *const RsvgNode)
+ -> *const RsvgNode {
+ boxed_node_new(NodeType::Ellipse, raw_parent, Box::new(NodeEllipse::new()))
}
diff --git a/rsvg_internals/src/space.rs b/rsvg_internals/src/space.rs
index afbcd878..937befeb 100644
--- a/rsvg_internals/src/space.rs
+++ b/rsvg_internals/src/space.rs
@@ -1,13 +1,13 @@
-use libc;
use glib::translate::*;
use itertools::Itertools;
+use libc;
use util::utf8_cstr;
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum XmlSpace {
Default,
- Preserve
+ Preserve,
}
/// Implements `xml:space` handling per the SVG spec
@@ -18,7 +18,7 @@ pub enum XmlSpace {
pub fn xml_space_normalize(mode: XmlSpace, s: &str) -> String {
match mode {
XmlSpace::Default => normalize_default(s),
- XmlSpace::Preserve => normalize_preserve(s)
+ XmlSpace::Preserve => normalize_preserve(s),
}
}
@@ -31,18 +31,17 @@ pub fn xml_space_normalize(mode: XmlSpace, s: &str) -> String {
// leading and trailing space characters. Then, all contiguous space
// characters will be consolidated.
fn normalize_default(s: &str) -> String {
- s.trim()
- .chars()
- .filter(|ch| *ch != '\n')
- .map(|ch| match ch {
- '\t' => ' ',
- c => c,
- })
- .coalesce(|current, next| match (current, next) {
- (' ', ' ') => Ok(' '),
- (_, _) => Err((current, next)),
- })
- .collect::<String>()
+ s.trim().chars()
+ .filter(|ch| *ch != '\n')
+ .map(|ch| match ch {
+ '\t' => ' ',
+ c => c,
+ })
+ .coalesce(|current, next| match (current, next) {
+ (' ', ' ') => Ok(' '),
+ (_, _) => Err((current, next)),
+ })
+ .collect::<String>()
}
// From https://www.w3.org/TR/SVG/text.html#WhiteSpace
@@ -56,19 +55,18 @@ fn normalize_default(s: &str) -> String {
// and "b") will produce a larger separation between "a" and "b" than
// "a b" (one space between "a" and "b").
fn normalize_preserve(s: &str) -> String {
- s.chars()
- .map(|ch| {
- match ch {
- '\n' | '\t' => ' ',
+ s.chars().map(|ch| match ch {
+ '\n' | '\t' => ' ',
- c => c
- }
- })
- .collect()
+ c => c,
+ })
+ .collect()
}
#[no_mangle]
-pub extern fn rsvg_xml_space_normalize(mode: XmlSpace, s: *const libc::c_char) -> *const libc::c_char {
+pub extern "C" fn rsvg_xml_space_normalize(mode: XmlSpace,
+ s: *const libc::c_char)
+ -> *const libc::c_char {
let rs = unsafe { utf8_cstr(s) };
xml_space_normalize(mode, rs).to_glib_full()
@@ -80,9 +78,12 @@ mod tests {
#[test]
fn xml_space_default() {
- assert_eq!(xml_space_normalize(XmlSpace::Default, "\n WS example\n indented lines\n "),
+ assert_eq!(xml_space_normalize(XmlSpace::Default,
+ "\n WS example\n indented lines\n "),
"WS example indented lines");
- assert_eq!(xml_space_normalize(XmlSpace::Default, "\n \t \tWS \t\t\texample\n \t indented
lines\t\t \n "),
+ assert_eq!(xml_space_normalize(XmlSpace::Default,
+ "\n \t \tWS \t\t\texample\n \t indented lines\t\t \
+ \n "),
"WS example indented lines");
assert_eq!(xml_space_normalize(XmlSpace::Default, "\n \t \tWS \t\t\texample\n \t duplicate
letters\t\t \n "),
"WS example duplicate letters");
@@ -94,9 +95,12 @@ mod tests {
#[test]
fn xml_space_preserve() {
- assert_eq!(xml_space_normalize(XmlSpace::Preserve, "\n WS example\n indented lines\n "),
+ assert_eq!(xml_space_normalize(XmlSpace::Preserve,
+ "\n WS example\n indented lines\n "),
" WS example indented lines ");
- assert_eq!(xml_space_normalize(XmlSpace::Preserve, "\n \t \tWS \t\t\texample\n \t indented
lines\t\t \n "),
+ assert_eq!(xml_space_normalize(XmlSpace::Preserve,
+ "\n \t \tWS \t\t\texample\n \t indented lines\t\t \
+ \n "),
" WS example indented lines ");
assert_eq!(xml_space_normalize(XmlSpace::Preserve, "\n \t \tWS \t\t\texample\n \t duplicate
letters\t\t \n "),
" WS example duplicate letters ");
diff --git a/rsvg_internals/src/state.rs b/rsvg_internals/src/state.rs
index 0a5a9447..0d210448 100644
--- a/rsvg_internals/src/state.rs
+++ b/rsvg_internals/src/state.rs
@@ -1,6 +1,6 @@
-use libc;
use glib::translate::*;
use glib_sys;
+use libc;
use pango;
use pango_sys;
@@ -20,45 +20,41 @@ pub enum UnicodeBidi {
#[repr(C)]
#[derive(Copy, Clone)]
struct TextDecoration {
- overline: glib_sys::gboolean,
+ overline: glib_sys::gboolean,
underline: glib_sys::gboolean,
- strike: glib_sys::gboolean
+ strike: glib_sys::gboolean,
}
pub struct FontDecor {
- pub overline: bool,
+ pub overline: bool,
pub underline: bool,
- pub strike: bool,
+ pub strike: bool,
}
impl From<TextDecoration> for FontDecor {
fn from(td: TextDecoration) -> FontDecor {
- FontDecor {
- overline: from_glib(td.overline),
- underline: from_glib(td.underline),
- strike: from_glib(td.strike),
- }
+ FontDecor { overline: from_glib(td.overline),
+ underline: from_glib(td.underline),
+ strike: from_glib(td.strike), }
}
}
extern "C" {
- fn rsvg_state_get_language (state: *const RsvgState) -> *const libc::c_char;
- fn rsvg_state_get_unicode_bidi (state: *const RsvgState) -> UnicodeBidi;
- fn rsvg_state_get_text_dir (state: *const RsvgState) -> pango_sys::PangoDirection;
- fn rsvg_state_get_text_gravity (state: *const RsvgState) -> pango_sys::PangoGravity;
- fn rsvg_state_get_font_family (state: *const RsvgState) -> *const libc::c_char;
- fn rsvg_state_get_font_style (state: *const RsvgState) -> pango_sys::PangoStyle;
- fn rsvg_state_get_font_variant (state: *const RsvgState) -> pango_sys::PangoVariant;
- fn rsvg_state_get_font_weight (state: *const RsvgState) -> pango_sys::PangoWeight;
- fn rsvg_state_get_font_stretch (state: *const RsvgState) -> pango_sys::PangoStretch;
- fn rsvg_state_get_letter_spacing (state: *const RsvgState) -> RsvgLength;
- fn rsvg_state_get_font_decor (state: *const RsvgState) -> *const TextDecoration;
+ fn rsvg_state_get_language(state: *const RsvgState) -> *const libc::c_char;
+ fn rsvg_state_get_unicode_bidi(state: *const RsvgState) -> UnicodeBidi;
+ fn rsvg_state_get_text_dir(state: *const RsvgState) -> pango_sys::PangoDirection;
+ fn rsvg_state_get_text_gravity(state: *const RsvgState) -> pango_sys::PangoGravity;
+ fn rsvg_state_get_font_family(state: *const RsvgState) -> *const libc::c_char;
+ fn rsvg_state_get_font_style(state: *const RsvgState) -> pango_sys::PangoStyle;
+ fn rsvg_state_get_font_variant(state: *const RsvgState) -> pango_sys::PangoVariant;
+ fn rsvg_state_get_font_weight(state: *const RsvgState) -> pango_sys::PangoWeight;
+ fn rsvg_state_get_font_stretch(state: *const RsvgState) -> pango_sys::PangoStretch;
+ fn rsvg_state_get_letter_spacing(state: *const RsvgState) -> RsvgLength;
+ fn rsvg_state_get_font_decor(state: *const RsvgState) -> *const TextDecoration;
}
pub fn get_language(state: *const RsvgState) -> Option<String> {
- unsafe {
- from_glib_none(rsvg_state_get_language(state))
- }
+ unsafe { from_glib_none(rsvg_state_get_language(state)) }
}
pub fn get_unicode_bidi(state: *const RsvgState) -> UnicodeBidi {
diff --git a/rsvg_internals/src/stop.rs b/rsvg_internals/src/stop.rs
index ecbc6023..661d739b 100644
--- a/rsvg_internals/src/stop.rs
+++ b/rsvg_internals/src/stop.rs
@@ -1,6 +1,6 @@
-use libc;
use cssparser;
use glib::translate::*;
+use libc;
use std::cell::Cell;
@@ -19,23 +19,21 @@ use state::RsvgState;
pub struct NodeStop {
offset: Cell<f64>,
- rgba: Cell<u32>
+ rgba: Cell<u32>,
}
impl NodeStop {
- fn new () -> NodeStop {
- NodeStop {
- offset: Cell::new (0.0),
- rgba: Cell::new (0)
- }
+ fn new() -> NodeStop {
+ NodeStop { offset: Cell::new(0.0),
+ rgba: Cell::new(0), }
}
- pub fn get_offset (&self) -> f64 {
- self.offset.get ()
+ pub fn get_offset(&self) -> f64 {
+ self.offset.get()
}
- pub fn get_rgba (&self) -> u32 {
- self.rgba.get ()
+ pub fn get_rgba(&self) -> u32 {
+ self.rgba.get()
}
}
@@ -61,16 +59,17 @@ fn validate_offset(length: RsvgLength) -> Result<RsvgLength, AttributeError> {
}
impl NodeTrait for NodeStop {
- fn set_atts (&self, node: &RsvgNode, _: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
- let state = node.get_state ();
+ fn set_atts(&self, node: &RsvgNode, _: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
+ let state = node.get_state();
for (_key, attr, value) in pbag.iter() {
match attr {
Attribute::Offset => {
let length = parse("offset", value, LengthDir::Both, Some(validate_offset))?;
- assert! (length.unit == LengthUnit::Default || length.unit == LengthUnit::Percent);
- self.offset.set (length.length);
- },
+ assert!(length.unit == LengthUnit::Default
+ || length.unit == LengthUnit::Percent);
+ self.offset.set(length.length);
+ }
Attribute::Style => {
// FIXME: this is the only place where rsvg_parse_style() and
@@ -82,22 +81,22 @@ impl NodeTrait for NodeStop {
// rendering time?
unsafe {
- rsvg_parse_style (state, value.to_glib_none ().0);
+ rsvg_parse_style(state, value.to_glib_none().0);
}
- },
+ }
_ => (),
}
}
unsafe {
- rsvg_parse_presentation_attributes (state, pbag.ffi());
+ rsvg_parse_presentation_attributes(state, pbag.ffi());
}
- let inherited_state = drawing_ctx::state_new ();
- let boxed_node = box_node (node.clone ());
- drawing_ctx::state_reconstruct (inherited_state, boxed_node);
- rsvg_node_unref (boxed_node);
+ let inherited_state = drawing_ctx::state_new();
+ let boxed_node = box_node(node.clone());
+ drawing_ctx::state_reconstruct(inherited_state, boxed_node);
+ rsvg_node_unref(boxed_node);
let mut color_rgba: cssparser::RGBA;
@@ -105,37 +104,37 @@ impl NodeTrait for NodeStop {
.map_err (|e| NodeError::attribute_error ("stop-color", e))?;
match stop_color {
- None => color_rgba = cssparser::RGBA::transparent (),
+ None => color_rgba = cssparser::RGBA::transparent(),
- Some (Color::Inherit) => {
+ Some(Color::Inherit) => {
let inherited_stop_color = drawing_ctx::state_get_stop_color (inherited_state)
.map_err (|e| NodeError::attribute_error ("stop-color", e))?;
match inherited_stop_color {
- None => unreachable! (),
+ None => unreachable!(),
- Some (Color::Inherit) => color_rgba = cssparser::RGBA::transparent (),
- Some (Color::CurrentColor) => {
- let color = drawing_ctx::state_get_current_color (inherited_state);
+ Some(Color::Inherit) => color_rgba = cssparser::RGBA::transparent(),
+ Some(Color::CurrentColor) => {
+ let color = drawing_ctx::state_get_current_color(inherited_state);
match color {
- Color::RGBA (rgba) => color_rgba = rgba,
- _ => unreachable! ()
+ Color::RGBA(rgba) => color_rgba = rgba,
+ _ => unreachable!(),
}
- },
-
- Some (Color::RGBA (rgba)) => color_rgba = rgba
+ }
+
+ Some(Color::RGBA(rgba)) => color_rgba = rgba,
}
- },
+ }
- Some (Color::CurrentColor) => {
- let color = drawing_ctx::state_get_current_color (inherited_state);
+ Some(Color::CurrentColor) => {
+ let color = drawing_ctx::state_get_current_color(inherited_state);
match color {
- Color::RGBA (rgba) => color_rgba = rgba,
- _ => unreachable! ()
+ Color::RGBA(rgba) => color_rgba = rgba,
+ _ => unreachable!(),
}
}
- Some (Color::RGBA (rgba)) => color_rgba = rgba
+ Some(Color::RGBA(rgba)) => color_rgba = rgba,
}
let stop_opacity = drawing_ctx::state_get_stop_opacity (state)
@@ -144,50 +143,48 @@ impl NodeTrait for NodeStop {
match stop_opacity {
None => color_rgba.alpha = 0xff,
- Some (Opacity::Inherit) => {
+ Some(Opacity::Inherit) => {
let inherited_opacity = drawing_ctx::state_get_stop_opacity (inherited_state)
.map_err (|e| NodeError::attribute_error ("stop-opacity", e))?;
match inherited_opacity {
- Some (Opacity::Specified (opacity)) => color_rgba.alpha = opacity_to_u8 (opacity),
- _ => color_rgba.alpha = 0xff
+ Some(Opacity::Specified(opacity)) => color_rgba.alpha = opacity_to_u8(opacity),
+ _ => color_rgba.alpha = 0xff,
}
- },
+ }
- Some (Opacity::Specified (opacity)) => color_rgba.alpha = opacity_to_u8 (opacity)
+ Some(Opacity::Specified(opacity)) => color_rgba.alpha = opacity_to_u8(opacity),
}
- self.rgba.set (u32_from_rgba (color_rgba));
+ self.rgba.set(u32_from_rgba(color_rgba));
- drawing_ctx::state_free (inherited_state);
+ drawing_ctx::state_free(inherited_state);
- Ok (())
+ Ok(())
}
- fn draw (&self, _: &RsvgNode, _: *const RsvgDrawingCtx, _: i32) {
+ fn draw(&self, _: &RsvgNode, _: *const RsvgDrawingCtx, _: i32) {
// nothing; paint servers are handled specially
}
- fn get_c_impl (&self) -> *const RsvgCNodeImpl {
- unreachable! ();
+ fn get_c_impl(&self) -> *const RsvgCNodeImpl {
+ unreachable!();
}
}
-fn u32_from_rgba (rgba: cssparser::RGBA) -> u32 {
- (u32::from(rgba.red) << 24) |
- (u32::from(rgba.green) << 16) |
- (u32::from(rgba.blue) << 8) |
- u32::from(rgba.alpha)
+fn u32_from_rgba(rgba: cssparser::RGBA) -> u32 {
+ (u32::from(rgba.red) << 24) | (u32::from(rgba.green) << 16) | (u32::from(rgba.blue) << 8)
+ | u32::from(rgba.alpha)
}
extern "C" {
- fn rsvg_parse_presentation_attributes (state: *mut RsvgState, pbag: *const PropertyBag);
- fn rsvg_parse_style (state: *mut RsvgState, string: *const libc::c_char);
+ fn rsvg_parse_presentation_attributes(state: *mut RsvgState, pbag: *const PropertyBag);
+ fn rsvg_parse_style(state: *mut RsvgState, string: *const libc::c_char);
}
#[no_mangle]
-pub extern fn rsvg_node_stop_new (_: *const libc::c_char, raw_parent: *const RsvgNode) -> *const RsvgNode {
- boxed_node_new (NodeType::Stop,
- raw_parent,
- Box::new (NodeStop::new ()))
+pub extern "C" fn rsvg_node_stop_new(_: *const libc::c_char,
+ raw_parent: *const RsvgNode)
+ -> *const RsvgNode {
+ boxed_node_new(NodeType::Stop, raw_parent, Box::new(NodeStop::new()))
}
diff --git a/rsvg_internals/src/structure.rs b/rsvg_internals/src/structure.rs
index 4507a908..a81ec0ba 100644
--- a/rsvg_internals/src/structure.rs
+++ b/rsvg_internals/src/structure.rs
@@ -1,167 +1,177 @@
use glib::translate::*;
use libc;
-use std::cell::RefCell;
use std::cell::Cell;
+use std::cell::RefCell;
use cairo::MatrixTrait;
use aspect_ratio::*;
use attributes::Attribute;
-use drawing_ctx::RsvgDrawingCtx;
use drawing_ctx;
+use drawing_ctx::RsvgDrawingCtx;
use handle::RsvgHandle;
use length::*;
use node::*;
-use parsers::{Parse, parse};
+use parsers::{parse, Parse};
use property_bag::{OwnedPropertyBag, PropertyBag};
use util::*;
use viewbox::*;
-use viewport::{ClipMode,draw_in_viewport};
+use viewport::{draw_in_viewport, ClipMode};
-/***** NodeGroup *****/
+/***** NodeGroup **** * * * * **/
-struct NodeGroup ();
+struct NodeGroup();
impl NodeGroup {
- fn new () -> NodeGroup {
- NodeGroup ()
+ fn new() -> NodeGroup {
+ NodeGroup()
}
}
impl NodeTrait for NodeGroup {
- fn set_atts (&self, _: &RsvgNode, _: *const RsvgHandle, _: &PropertyBag) -> NodeResult {
- Ok (())
+ fn set_atts(&self, _: &RsvgNode, _: *const RsvgHandle, _: &PropertyBag) -> NodeResult {
+ Ok(())
}
- fn draw (&self, node: &RsvgNode, draw_ctx: *const RsvgDrawingCtx, dominate: i32) {
- node.draw_children (draw_ctx, dominate);
+ fn draw(&self, node: &RsvgNode, draw_ctx: *const RsvgDrawingCtx, dominate: i32) {
+ node.draw_children(draw_ctx, dominate);
}
- fn get_c_impl (&self) -> *const RsvgCNodeImpl {
- unreachable! ();
+ fn get_c_impl(&self) -> *const RsvgCNodeImpl {
+ unreachable!();
}
}
-/***** NodeDefs *****/
+/***** NodeDefs **** * * * * **/
-struct NodeDefs ();
+struct NodeDefs();
impl NodeDefs {
- fn new () -> NodeDefs {
- NodeDefs ()
+ fn new() -> NodeDefs {
+ NodeDefs()
}
}
impl NodeTrait for NodeDefs {
- fn set_atts (&self, _: &RsvgNode, _: *const RsvgHandle, _: &PropertyBag) -> NodeResult {
- Ok (())
+ fn set_atts(&self, _: &RsvgNode, _: *const RsvgHandle, _: &PropertyBag) -> NodeResult {
+ Ok(())
}
- fn draw (&self, _: &RsvgNode, _: *const RsvgDrawingCtx, _: i32) {
+ fn draw(&self, _: &RsvgNode, _: *const RsvgDrawingCtx, _: i32) {
// nothing
}
- fn get_c_impl (&self) -> *const RsvgCNodeImpl {
- unreachable! ();
+ fn get_c_impl(&self) -> *const RsvgCNodeImpl {
+ unreachable!();
}
}
-/***** NodeSwitch *****/
+/***** NodeSwitch **** * * * * **/
-struct NodeSwitch ();
+struct NodeSwitch();
impl NodeSwitch {
- fn new () -> NodeSwitch {
- NodeSwitch ()
+ fn new() -> NodeSwitch {
+ NodeSwitch()
}
}
impl NodeTrait for NodeSwitch {
- fn set_atts (&self, _: &RsvgNode, _: *const RsvgHandle, _: &PropertyBag) -> NodeResult {
- Ok (())
+ fn set_atts(&self, _: &RsvgNode, _: *const RsvgHandle, _: &PropertyBag) -> NodeResult {
+ Ok(())
}
- fn draw (&self, node: &RsvgNode, draw_ctx: *const RsvgDrawingCtx, dominate: i32) {
- drawing_ctx::state_reinherit_top (draw_ctx, node.get_state (), dominate);
+ fn draw(&self, node: &RsvgNode, draw_ctx: *const RsvgDrawingCtx, dominate: i32) {
+ drawing_ctx::state_reinherit_top(draw_ctx, node.get_state(), dominate);
- drawing_ctx::push_discrete_layer (draw_ctx);
+ drawing_ctx::push_discrete_layer(draw_ctx);
node.foreach_child(|child| {
- if drawing_ctx::state_get_cond_true (child.get_state ()) {
- let boxed_child = box_node (child.clone ());
+ if drawing_ctx::state_get_cond_true(child.get_state()) {
+ let boxed_child = box_node(child.clone());
- drawing_ctx::draw_node_from_stack (draw_ctx, boxed_child, 0);
+ drawing_ctx::draw_node_from_stack(draw_ctx, boxed_child, 0);
- rsvg_node_unref (boxed_child);
+ rsvg_node_unref(boxed_child);
- false // just draw this child
- } else {
- true
- }
- });
+ false // just draw this child
+ } else {
+ true
+ }
+ });
- drawing_ctx::pop_discrete_layer (draw_ctx);
+ drawing_ctx::pop_discrete_layer(draw_ctx);
}
- fn get_c_impl (&self) -> *const RsvgCNodeImpl {
- unreachable! ();
+ fn get_c_impl(&self) -> *const RsvgCNodeImpl {
+ unreachable!();
}
}
-/***** NodeSvg *****/
+/***** NodeSvg **** * * * * **/
struct NodeSvg {
preserve_aspect_ratio: Cell<AspectRatio>,
- x: Cell<RsvgLength>,
- y: Cell<RsvgLength>,
- w: Cell<RsvgLength>,
- h: Cell<RsvgLength>,
- vbox: Cell<Option<ViewBox>>,
- pbag: RefCell<Option<OwnedPropertyBag>>
+ x: Cell<RsvgLength>,
+ y: Cell<RsvgLength>,
+ w: Cell<RsvgLength>,
+ h: Cell<RsvgLength>,
+ vbox: Cell<Option<ViewBox>>,
+ pbag: RefCell<Option<OwnedPropertyBag>>,
}
impl NodeSvg {
- fn new () -> NodeSvg {
- NodeSvg {
- preserve_aspect_ratio: Cell::new (AspectRatio::default ()),
- x: Cell::new (RsvgLength::parse ("0", LengthDir::Horizontal).unwrap ()),
- y: Cell::new (RsvgLength::parse ("0", LengthDir::Vertical).unwrap ()),
- w: Cell::new (RsvgLength::parse ("100%", LengthDir::Horizontal).unwrap ()),
- h: Cell::new (RsvgLength::parse ("100%", LengthDir::Vertical).unwrap ()),
- vbox: Cell::new (None),
- pbag: RefCell::new(None)
- }
+ fn new() -> NodeSvg {
+ NodeSvg { preserve_aspect_ratio: Cell::new(AspectRatio::default()),
+ x: Cell::new(RsvgLength::parse("0", LengthDir::Horizontal).unwrap()),
+ y: Cell::new(RsvgLength::parse("0", LengthDir::Vertical).unwrap()),
+ w: Cell::new(RsvgLength::parse("100%", LengthDir::Horizontal).unwrap()),
+ h: Cell::new(RsvgLength::parse("100%", LengthDir::Vertical).unwrap()),
+ vbox: Cell::new(None),
+ pbag: RefCell::new(None), }
}
}
impl NodeTrait for NodeSvg {
- fn set_atts (&self, node: &RsvgNode, _: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
+ fn set_atts(&self, node: &RsvgNode, _: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
// x & y attributes have no effect on outermost svg
// http://www.w3.org/TR/SVG/struct.html#SVGElement
let is_inner_svg = node.get_parent().is_some();
for (_key, attr, value) in pbag.iter() {
match attr {
- Attribute::PreserveAspectRatio =>
- self.preserve_aspect_ratio.set(parse("preserveAspectRatio", value, (), None)?),
+ Attribute::PreserveAspectRatio => {
+ self.preserve_aspect_ratio.set(parse("preserveAspectRatio", value, (), None)?)
+ }
- Attribute::X => if is_inner_svg {
- self.x.set(parse("x", value, LengthDir::Horizontal, None)?);
- },
+ Attribute::X => {
+ if is_inner_svg {
+ self.x.set(parse("x", value, LengthDir::Horizontal, None)?);
+ }
+ }
- Attribute::Y => if is_inner_svg {
- self.y.set(parse("y", value, LengthDir::Vertical, None)?);
- },
+ Attribute::Y => {
+ if is_inner_svg {
+ self.y.set(parse("y", value, LengthDir::Vertical, None)?);
+ }
+ }
- Attribute::Width => self.w.set(parse("width", value, LengthDir::Horizontal,
- Some(RsvgLength::check_nonnegative))?),
+ Attribute::Width => {
+ self.w.set(parse("width",
+ value,
+ LengthDir::Horizontal,
+ Some(RsvgLength::check_nonnegative))?)
+ }
- Attribute::Height => self.h.set(parse("height", value, LengthDir::Vertical,
- Some(RsvgLength::check_nonnegative))?),
+ Attribute::Height => {
+ self.h.set(parse("height",
+ value,
+ LengthDir::Vertical,
+ Some(RsvgLength::check_nonnegative))?)
+ }
- Attribute::ViewBox => self.vbox.set(parse("viewBox", value, (), None)
- .map(Some)?),
+ Attribute::ViewBox => self.vbox.set(parse("viewBox", value, (), None).map(Some)?),
_ => (),
}
@@ -171,21 +181,24 @@ impl NodeTrait for NodeSvg {
// to store other attributes to be applied later.
*self.pbag.borrow_mut() = Some(pbag.to_owned());
- Ok (())
+ Ok(())
}
- fn draw (&self, node: &RsvgNode, draw_ctx: *const RsvgDrawingCtx, dominate: i32) {
- let nx = self.x.get ().normalize (draw_ctx);
- let ny = self.y.get ().normalize (draw_ctx);
- let nw = self.w.get ().normalize (draw_ctx);
- let nh = self.h.get ().normalize (draw_ctx);
+ fn draw(&self, node: &RsvgNode, draw_ctx: *const RsvgDrawingCtx, dominate: i32) {
+ let nx = self.x.get().normalize(draw_ctx);
+ let ny = self.y.get().normalize(draw_ctx);
+ let nw = self.w.get().normalize(draw_ctx);
+ let nh = self.h.get().normalize(draw_ctx);
- drawing_ctx::state_reinherit_top (draw_ctx, node.get_state (), dominate);
+ drawing_ctx::state_reinherit_top(draw_ctx, node.get_state(), dominate);
- let state = drawing_ctx::get_current_state (draw_ctx);
- let do_clip = !drawing_ctx::state_is_overflow (state) && node.get_parent ().is_some ();
+ let state = drawing_ctx::get_current_state(draw_ctx);
+ let do_clip = !drawing_ctx::state_is_overflow(state) && node.get_parent().is_some();
- draw_in_viewport(nx, ny, nw, nh,
+ draw_in_viewport(nx,
+ ny,
+ nw,
+ nh,
ClipMode::ClipToViewport,
do_clip,
self.vbox.get(),
@@ -199,35 +212,33 @@ impl NodeTrait for NodeSvg {
});
}
- fn get_c_impl (&self) -> *const RsvgCNodeImpl {
- unreachable! ();
+ fn get_c_impl(&self) -> *const RsvgCNodeImpl {
+ unreachable!();
}
}
-/***** NodeUse *****/
+/***** NodeUse **** * * * * **/
struct NodeUse {
link: RefCell<Option<String>>,
- x: Cell<RsvgLength>,
- y: Cell<RsvgLength>,
- w: Cell<Option<RsvgLength>>,
- h: Cell<Option<RsvgLength>>,
+ x: Cell<RsvgLength>,
+ y: Cell<RsvgLength>,
+ w: Cell<Option<RsvgLength>>,
+ h: Cell<Option<RsvgLength>>,
}
impl NodeUse {
- fn new () -> NodeUse {
- NodeUse {
- link: RefCell::new (None),
- x: Cell::new (RsvgLength::default ()),
- y: Cell::new (RsvgLength::default ()),
- w: Cell::new (None),
- h: Cell::new (None)
- }
+ fn new() -> NodeUse {
+ NodeUse { link: RefCell::new(None),
+ x: Cell::new(RsvgLength::default()),
+ y: Cell::new(RsvgLength::default()),
+ w: Cell::new(None),
+ h: Cell::new(None), }
}
}
impl NodeTrait for NodeUse {
- fn set_atts (&self, _: &RsvgNode, _: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
+ fn set_atts(&self, _: &RsvgNode, _: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
for (_key, attr, value) in pbag.iter() {
match attr {
Attribute::XlinkHref => *self.link.borrow_mut() = Some(value.to_owned()),
@@ -246,250 +257,256 @@ impl NodeTrait for NodeUse {
}
}
- Ok (())
+ Ok(())
}
- fn draw (&self, node: &RsvgNode, draw_ctx: *const RsvgDrawingCtx, dominate: i32) {
- let link = self.link.borrow ();
+ fn draw(&self, node: &RsvgNode, draw_ctx: *const RsvgDrawingCtx, dominate: i32) {
+ let link = self.link.borrow();
- if link.is_none () {
+ if link.is_none() {
return;
}
- let raw_child = drawing_ctx::acquire_node (draw_ctx, link.as_ref ().unwrap ());
- if raw_child.is_null () {
+ let raw_child = drawing_ctx::acquire_node(draw_ctx, link.as_ref().unwrap());
+ if raw_child.is_null() {
return;
}
let child: &RsvgNode = unsafe { &*raw_child };
- if Node::is_ancestor (node.clone (), child.clone ()) {
+ if Node::is_ancestor(node.clone(), child.clone()) {
// or, if we're <use>'ing ourselves
- drawing_ctx::release_node (draw_ctx, raw_child);
+ drawing_ctx::release_node(draw_ctx, raw_child);
return;
}
- let nx = self.x.get ().normalize (draw_ctx);
- let ny = self.y.get ().normalize (draw_ctx);
+ let nx = self.x.get().normalize(draw_ctx);
+ let ny = self.y.get().normalize(draw_ctx);
// If attributes ‘width’ and/or ‘height’ are not specified,
// [...] use values of '100%' for these attributes.
// From https://www.w3.org/TR/SVG/struct.html#UseElement in
// "If the ‘use’ element references a ‘symbol’ element"
-
- let nw = self.w.get ().unwrap_or_else(|| { RsvgLength::parse ("100%", LengthDir::Horizontal).unwrap
()})
- .normalize (draw_ctx);
- let nh = self.h.get ().unwrap_or_else(|| { RsvgLength::parse ("100%", LengthDir::Vertical).unwrap
()})
- .normalize (draw_ctx);
+
+ let nw = self.w.get()
+ .unwrap_or_else(|| RsvgLength::parse("100%", LengthDir::Horizontal).unwrap())
+ .normalize(draw_ctx);
+ let nh = self.h.get()
+ .unwrap_or_else(|| RsvgLength::parse("100%", LengthDir::Vertical).unwrap())
+ .normalize(draw_ctx);
// width or height set to 0 disables rendering of the element
// https://www.w3.org/TR/SVG/struct.html#UseElementWidthAttribute
- if double_equals (nw, 0.0) || double_equals (nh, 0.0) {
- drawing_ctx::release_node (draw_ctx, raw_child);
+ if double_equals(nw, 0.0) || double_equals(nh, 0.0) {
+ drawing_ctx::release_node(draw_ctx, raw_child);
return;
}
-
- drawing_ctx::state_reinherit_top (draw_ctx, node.get_state (), dominate);
- let state = drawing_ctx::get_current_state (draw_ctx);
+ drawing_ctx::state_reinherit_top(draw_ctx, node.get_state(), dominate);
+
+ let state = drawing_ctx::get_current_state(draw_ctx);
- if child.get_type () != NodeType::Symbol {
- let mut affine = drawing_ctx::get_current_state_affine (draw_ctx);
- affine.translate (nx, ny);
- drawing_ctx::set_current_state_affine (draw_ctx, affine);
+ if child.get_type() != NodeType::Symbol {
+ let mut affine = drawing_ctx::get_current_state_affine(draw_ctx);
+ affine.translate(nx, ny);
+ drawing_ctx::set_current_state_affine(draw_ctx, affine);
- drawing_ctx::push_discrete_layer (draw_ctx);
+ drawing_ctx::push_discrete_layer(draw_ctx);
- let boxed_child = box_node (child.clone ());
- drawing_ctx::draw_node_from_stack (draw_ctx, boxed_child, 1);
- rsvg_node_unref (boxed_child);
+ let boxed_child = box_node(child.clone());
+ drawing_ctx::draw_node_from_stack(draw_ctx, boxed_child, 1);
+ rsvg_node_unref(boxed_child);
- drawing_ctx::release_node (draw_ctx, raw_child);
- drawing_ctx::pop_discrete_layer (draw_ctx);
+ drawing_ctx::release_node(draw_ctx, raw_child);
+ drawing_ctx::pop_discrete_layer(draw_ctx);
} else {
- child.with_impl (|symbol: &NodeSymbol| {
- let do_clip = !drawing_ctx::state_is_overflow (state)
- || (!drawing_ctx::state_has_overflow (state)
- && drawing_ctx::state_is_overflow (child.get_state ()));
-
- draw_in_viewport(nx, ny, nw, nh,
- ClipMode::ClipToVbox,
- do_clip,
- symbol.vbox.get(),
- symbol.preserve_aspect_ratio.get(),
- drawing_ctx::get_current_state_affine(draw_ctx),
- draw_ctx,
- || {
- drawing_ctx::state_push(draw_ctx);
- child.draw_children(draw_ctx, 1);
- drawing_ctx::state_pop(draw_ctx);
- });
- });
-
- drawing_ctx::release_node (draw_ctx, raw_child);
+ child.with_impl(|symbol: &NodeSymbol| {
+ let do_clip =
+ !drawing_ctx::state_is_overflow(state)
+ || (!drawing_ctx::state_has_overflow(state)
+ && drawing_ctx::state_is_overflow(child.get_state()));
+
+ draw_in_viewport(nx,
+ ny,
+ nw,
+ nh,
+ ClipMode::ClipToVbox,
+ do_clip,
+ symbol.vbox.get(),
+ symbol.preserve_aspect_ratio.get(),
+ drawing_ctx::get_current_state_affine(draw_ctx),
+ draw_ctx,
+ || {
+ drawing_ctx::state_push(draw_ctx);
+ child.draw_children(draw_ctx, 1);
+ drawing_ctx::state_pop(draw_ctx);
+ });
+ });
+
+ drawing_ctx::release_node(draw_ctx, raw_child);
}
}
- fn get_c_impl (&self) -> *const RsvgCNodeImpl {
- unreachable! ();
+ fn get_c_impl(&self) -> *const RsvgCNodeImpl {
+ unreachable!();
}
}
-/***** NodeSymbol *****/
+/***** NodeSymbol **** * * * * **/
struct NodeSymbol {
preserve_aspect_ratio: Cell<AspectRatio>,
- vbox: Cell<Option<ViewBox>>
+ vbox: Cell<Option<ViewBox>>,
}
impl NodeSymbol {
- fn new () -> NodeSymbol {
- NodeSymbol {
- preserve_aspect_ratio: Cell::new (AspectRatio::default ()),
- vbox: Cell::new (None)
- }
+ fn new() -> NodeSymbol {
+ NodeSymbol { preserve_aspect_ratio: Cell::new(AspectRatio::default()),
+ vbox: Cell::new(None), }
}
}
impl NodeTrait for NodeSymbol {
- fn set_atts (&self, _: &RsvgNode, _: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
+ fn set_atts(&self, _: &RsvgNode, _: *const RsvgHandle, pbag: &PropertyBag) -> NodeResult {
for (_key, attr, value) in pbag.iter() {
match attr {
- Attribute::PreserveAspectRatio =>
- self.preserve_aspect_ratio.set(parse("preserveAspectRatio", value, (), None)?),
+ Attribute::PreserveAspectRatio => {
+ self.preserve_aspect_ratio.set(parse("preserveAspectRatio", value, (), None)?)
+ }
- Attribute::ViewBox => self.vbox.set(parse("viewBox", value, (), None)
- .map(Some)?),
+ Attribute::ViewBox => self.vbox.set(parse("viewBox", value, (), None).map(Some)?),
_ => (),
}
}
- Ok (())
+ Ok(())
}
- fn draw (&self, _: &RsvgNode, _: *const RsvgDrawingCtx, _: i32) {
+ fn draw(&self, _: &RsvgNode, _: *const RsvgDrawingCtx, _: i32) {
// nothing
}
- fn get_c_impl (&self) -> *const RsvgCNodeImpl {
- unreachable! ();
+ fn get_c_impl(&self) -> *const RsvgCNodeImpl {
+ unreachable!();
}
}
-/***** C Prototypes *****/
+/***** C Prototypes **** * * * * **/
#[no_mangle]
-pub extern fn rsvg_node_group_new (_: *const libc::c_char, raw_parent: *const RsvgNode) -> *const RsvgNode {
- boxed_node_new (NodeType::Group,
- raw_parent,
- Box::new (NodeGroup::new ()))
+pub extern "C" fn rsvg_node_group_new(_: *const libc::c_char,
+ raw_parent: *const RsvgNode)
+ -> *const RsvgNode {
+ boxed_node_new(NodeType::Group, raw_parent, Box::new(NodeGroup::new()))
}
#[no_mangle]
-pub extern fn rsvg_node_defs_new (_: *const libc::c_char, raw_parent: *const RsvgNode) -> *const RsvgNode {
- boxed_node_new (NodeType::Defs,
- raw_parent,
- Box::new (NodeDefs::new ()))
+pub extern "C" fn rsvg_node_defs_new(_: *const libc::c_char,
+ raw_parent: *const RsvgNode)
+ -> *const RsvgNode {
+ boxed_node_new(NodeType::Defs, raw_parent, Box::new(NodeDefs::new()))
}
#[no_mangle]
-pub extern fn rsvg_node_switch_new (_: *const libc::c_char, raw_parent: *const RsvgNode) -> *const RsvgNode {
- boxed_node_new (NodeType::Switch,
- raw_parent,
- Box::new (NodeSwitch::new ()))
+pub extern "C" fn rsvg_node_switch_new(_: *const libc::c_char,
+ raw_parent: *const RsvgNode)
+ -> *const RsvgNode {
+ boxed_node_new(NodeType::Switch, raw_parent, Box::new(NodeSwitch::new()))
}
#[no_mangle]
-pub extern fn rsvg_node_svg_new (_: *const libc::c_char, raw_parent: *const RsvgNode) -> *const RsvgNode {
- boxed_node_new (NodeType::Svg,
- raw_parent,
- Box::new (NodeSvg::new ()))
+pub extern "C" fn rsvg_node_svg_new(_: *const libc::c_char,
+ raw_parent: *const RsvgNode)
+ -> *const RsvgNode {
+ boxed_node_new(NodeType::Svg, raw_parent, Box::new(NodeSvg::new()))
}
#[no_mangle]
-pub extern fn rsvg_node_use_new (_: *const libc::c_char, raw_parent: *const RsvgNode) -> *const RsvgNode {
- boxed_node_new (NodeType::Use,
- raw_parent,
- Box::new (NodeUse::new ()))
+pub extern "C" fn rsvg_node_use_new(_: *const libc::c_char,
+ raw_parent: *const RsvgNode)
+ -> *const RsvgNode {
+ boxed_node_new(NodeType::Use, raw_parent, Box::new(NodeUse::new()))
}
#[no_mangle]
-pub extern fn rsvg_node_symbol_new (_: *const libc::c_char, raw_parent: *const RsvgNode) -> *const RsvgNode {
- boxed_node_new (NodeType::Symbol,
- raw_parent,
- Box::new (NodeSymbol::new ()))
+pub extern "C" fn rsvg_node_symbol_new(_: *const libc::c_char,
+ raw_parent: *const RsvgNode)
+ -> *const RsvgNode {
+ boxed_node_new(NodeType::Symbol, raw_parent, Box::new(NodeSymbol::new()))
}
#[no_mangle]
-pub extern fn rsvg_node_svg_get_size (raw_node: *const RsvgNode, out_width: *mut RsvgLength, out_height:
*mut RsvgLength) {
- assert! (!raw_node.is_null ());
- let node: &RsvgNode = unsafe { & *raw_node };
-
- assert! (!out_width.is_null ());
- assert! (!out_height.is_null ());
-
- node.with_impl (|svg: &NodeSvg| {
- unsafe {
- *out_width = svg.w.get ();
- *out_height = svg.h.get ();
- }
- });
+pub extern "C" fn rsvg_node_svg_get_size(raw_node: *const RsvgNode,
+ out_width: *mut RsvgLength,
+ out_height: *mut RsvgLength) {
+ assert!(!raw_node.is_null());
+ let node: &RsvgNode = unsafe { &*raw_node };
+
+ assert!(!out_width.is_null());
+ assert!(!out_height.is_null());
+
+ node.with_impl(|svg: &NodeSvg| unsafe {
+ *out_width = svg.w.get();
+ *out_height = svg.h.get();
+ });
}
#[no_mangle]
-pub extern fn rsvg_node_svg_get_view_box (raw_node: *const RsvgNode) -> RsvgViewBox {
- assert! (!raw_node.is_null ());
- let node: &RsvgNode = unsafe { & *raw_node };
+pub extern "C" fn rsvg_node_svg_get_view_box(raw_node: *const RsvgNode) -> RsvgViewBox {
+ assert!(!raw_node.is_null());
+ let node: &RsvgNode = unsafe { &*raw_node };
let mut vbox: Option<ViewBox> = None;
- node.with_impl (|svg: &NodeSvg| {
- vbox = svg.vbox.get ();
- });
+ node.with_impl(|svg: &NodeSvg| {
+ vbox = svg.vbox.get();
+ });
- RsvgViewBox::from (vbox)
+ RsvgViewBox::from(vbox)
}
extern "C" {
- fn rsvg_parse_style_attrs (handle: *const RsvgHandle,
- node: *const RsvgNode,
- tag: *const libc::c_char,
- class: *const libc::c_char,
- id: *const libc::c_char,
- pbag: *const PropertyBag);
+ fn rsvg_parse_style_attrs(handle: *const RsvgHandle,
+ node: *const RsvgNode,
+ tag: *const libc::c_char,
+ class: *const libc::c_char,
+ id: *const libc::c_char,
+ pbag: *const PropertyBag);
}
#[no_mangle]
-pub extern fn rsvg_node_svg_apply_atts (raw_node: *const RsvgNode, handle: *const RsvgHandle) {
- assert! (!raw_node.is_null ());
- let node: &RsvgNode = unsafe { & *raw_node };
-
- node.with_impl (|svg: &NodeSvg| {
- if let Some(owned_pbag) = svg.pbag.borrow().as_ref() {
- let pbag = PropertyBag::from_owned(owned_pbag);
-
- let mut class = None;
- let mut id = None;
-
- for (_key, attr, value) in pbag.iter() {
- match attr {
- Attribute::Class => class = Some(value),
-
- Attribute::Id => id = Some(value),
-
- _ => (),
- }
- }
-
- let c_class = class.to_glib_none ();
- let c_id = id.to_glib_none ();
-
- unsafe { rsvg_parse_style_attrs (handle,
- raw_node,
- str::to_glib_none ("svg").0,
- c_class.0,
- c_id.0,
- pbag.ffi()); }
- }
- });
+pub extern "C" fn rsvg_node_svg_apply_atts(raw_node: *const RsvgNode, handle: *const RsvgHandle) {
+ assert!(!raw_node.is_null());
+ let node: &RsvgNode = unsafe { &*raw_node };
+
+ node.with_impl(|svg: &NodeSvg| {
+ if let Some(owned_pbag) = svg.pbag.borrow().as_ref() {
+ let pbag = PropertyBag::from_owned(owned_pbag);
+
+ let mut class = None;
+ let mut id = None;
+
+ for (_key, attr, value) in pbag.iter() {
+ match attr {
+ Attribute::Class => class = Some(value),
+
+ Attribute::Id => id = Some(value),
+
+ _ => (),
+ }
+ }
+
+ let c_class = class.to_glib_none();
+ let c_id = id.to_glib_none();
+
+ unsafe {
+ rsvg_parse_style_attrs(handle,
+ raw_node,
+ str::to_glib_none("svg").0,
+ c_class.0,
+ c_id.0,
+ pbag.ffi());
+ }
+ }
+ });
}
diff --git a/rsvg_internals/src/text.rs b/rsvg_internals/src/text.rs
index eadcc4ce..35bc1dcd 100644
--- a/rsvg_internals/src/text.rs
+++ b/rsvg_internals/src/text.rs
@@ -1,5 +1,5 @@
-use libc;
use glib::translate::*;
+use libc;
use pango::{self, ContextExt, LayoutExt};
use pango_sys;
@@ -7,11 +7,12 @@ use drawing_ctx::{self, RsvgDrawingCtx};
use state::{self, UnicodeBidi};
use util::utf8_cstr;
-// FIXME: should the pango crate provide this like PANGO_GRAVITY_IS_VERTICAL() / PANGO_GRAVITY_IS_IMPROPER()?
+// FIXME: should the pango crate provide this like PANGO_GRAVITY_IS_VERTICAL() /
+// PANGO_GRAVITY_IS_IMPROPER()?
fn gravity_is_vertical(gravity: pango::Gravity) -> bool {
match gravity {
pango::Gravity::East | pango::Gravity::West => true,
- _ => false
+ _ => false,
}
}
@@ -32,9 +33,9 @@ fn create_pango_layout(draw_ctx: *const RsvgDrawingCtx, text: &str) -> pango::La
match unicode_bidi {
UnicodeBidi::Override | UnicodeBidi::Embed => {
pango_context.set_base_dir(state::get_text_dir(state));
- },
+ }
- _ => ()
+ _ => (),
}
let gravity = state::get_text_gravity(state);
@@ -54,7 +55,8 @@ fn create_pango_layout(draw_ctx: *const RsvgDrawingCtx, text: &str) -> pango::La
font_desc.set_stretch(state::get_font_stretch(state));
let (_, dpi_y) = drawing_ctx::get_dpi(draw_ctx);
- font_desc.set_size(to_pango_units(drawing_ctx::get_normalized_font_size(draw_ctx) / dpi_y * 72.0));
+ font_desc.set_size(to_pango_units(drawing_ctx::get_normalized_font_size(draw_ctx) / dpi_y
+ * 72.0));
let layout = pango::Layout::new(&pango_context);
layout.set_font_description(&font_desc);
@@ -68,24 +70,20 @@ fn create_pango_layout(draw_ctx: *const RsvgDrawingCtx, text: &str) -> pango::La
if let Some(font_decor) = state::get_font_decor(state) {
if font_decor.underline {
- attr_list.insert(pango::Attribute::new_underline(pango::Underline::Single)
- .unwrap());
+ attr_list.insert(pango::Attribute::new_underline(pango::Underline::Single).unwrap());
}
if font_decor.strike {
- attr_list.insert(pango::Attribute::new_strikethrough(true)
- .unwrap());
+ attr_list.insert(pango::Attribute::new_strikethrough(true).unwrap());
}
}
layout.set_attributes(&attr_list);
- layout.set_alignment(
- match state::get_text_dir(state) {
- pango::Direction::Ltr => pango::Alignment::Left,
- _ => pango::Alignment::Right,
- }
- );
+ layout.set_alignment(match state::get_text_dir(state) {
+ pango::Direction::Ltr => pango::Alignment::Left,
+ _ => pango::Alignment::Right,
+ });
layout.set_text(text);
@@ -93,8 +91,9 @@ fn create_pango_layout(draw_ctx: *const RsvgDrawingCtx, text: &str) -> pango::La
}
#[no_mangle]
-pub extern fn rsvg_text_create_layout(draw_ctx: *const RsvgDrawingCtx,
- text: *const libc::c_char) -> *const pango_sys::PangoLayout {
+pub extern "C" fn rsvg_text_create_layout(draw_ctx: *const RsvgDrawingCtx,
+ text: *const libc::c_char)
+ -> *const pango_sys::PangoLayout {
assert!(!text.is_null());
let s = unsafe { utf8_cstr(text) };
let layout = create_pango_layout(draw_ctx, s);
diff --git a/rsvg_internals/src/transform.rs b/rsvg_internals/src/transform.rs
index 8ee42843..ecdfb7cc 100644
--- a/rsvg_internals/src/transform.rs
+++ b/rsvg_internals/src/transform.rs
@@ -6,18 +6,18 @@ use libc;
use std::f64::consts::*;
use cairo::MatrixTrait;
-use cssparser::{Parser, ParserInput, Token, ParseError as CssParseError};
+use cssparser::{ParseError as CssParseError, Parser, ParserInput, Token};
use error::*;
-use parsers::{Parse, ParseError, optional_comma};
+use parsers::{optional_comma, Parse, ParseError};
use util::utf8_cstr;
impl Parse for cairo::Matrix {
type Data = ();
type Err = AttributeError;
- fn parse (s: &str, _: ()) -> Result<cairo::Matrix, AttributeError> {
- parse_transform (s)
+ fn parse(s: &str, _: ()) -> Result<cairo::Matrix, AttributeError> {
+ parse_transform(s)
}
}
@@ -28,8 +28,9 @@ impl Parse for cairo::Matrix {
pub fn parse_transform(s: &str) -> Result<cairo::Matrix, AttributeError> {
let matrix = parse_transform_list(s)?;
- matrix.try_invert ().map (|_| matrix)
- .map_err (|_| AttributeError::Value ("invalid transformation matrix".to_string ()))
+ matrix.try_invert()
+ .map(|_| matrix)
+ .map_err(|_| AttributeError::Value("invalid transformation matrix".to_string()))
}
fn parse_transform_list(s: &str) -> Result<cairo::Matrix, AttributeError> {
@@ -63,151 +64,170 @@ fn parse_transform_command(parser: &mut Parser) -> Result<cairo::Matrix, Attribu
Token::Ident(ref name) => {
parser.expect_parenthesis_block()?;
parse_transform_function(name, parser)
- },
+ }
_ => Err(make_expected_function_error()),
}
}
-fn parse_transform_function(name: &str, parser: &mut Parser) -> Result<cairo::Matrix, AttributeError> {
+fn parse_transform_function(name: &str,
+ parser: &mut Parser)
+ -> Result<cairo::Matrix, AttributeError> {
match name {
- "matrix" => parse_matrix_args(parser),
+ "matrix" => parse_matrix_args(parser),
"translate" => parse_translate_args(parser),
- "scale" => parse_scale_args(parser),
- "rotate" => parse_rotate_args(parser),
- "skewX" => parse_skewx_args(parser),
- "skewY" => parse_skewy_args(parser),
- _ => Err(make_expected_function_error()),
+ "scale" => parse_scale_args(parser),
+ "rotate" => parse_rotate_args(parser),
+ "skewX" => parse_skewx_args(parser),
+ "skewY" => parse_skewy_args(parser),
+ _ => Err(make_expected_function_error()),
}
}
fn parse_matrix_args(parser: &mut Parser) -> Result<cairo::Matrix, AttributeError> {
parser.parse_nested_block(|p| {
- let xx = f64::from(p.expect_number()?);
- optional_comma(p);
+ let xx = f64::from(p.expect_number()?);
+ optional_comma(p);
- let yx = f64::from(p.expect_number()?);
- optional_comma(p);
+ let yx = f64::from(p.expect_number()?);
+ optional_comma(p);
- let xy = f64::from(p.expect_number()?);
- optional_comma(p);
+ let xy = f64::from(p.expect_number()?);
+ optional_comma(p);
- let yy = f64::from(p.expect_number()?);
- optional_comma(p);
+ let yy = f64::from(p.expect_number()?);
+ optional_comma(p);
- let x0 = f64::from(p.expect_number()?);
- optional_comma(p);
+ let x0 = f64::from(p.expect_number()?);
+ optional_comma(p);
- let y0 = f64::from(p.expect_number()?);
+ let y0 = f64::from(p.expect_number()?);
- Ok(cairo::Matrix::new(xx, yx, xy, yy, x0, y0))
- }).map_err(CssParseError::<()>::basic)
- .map_err(AttributeError::from)
+ Ok(cairo::Matrix::new(xx, yx, xy, yy, x0, y0))
+ })
+ .map_err(CssParseError::<()>::basic)
+ .map_err(AttributeError::from)
}
fn parse_translate_args(parser: &mut Parser) -> Result<cairo::Matrix, AttributeError> {
parser.parse_nested_block(|p| {
- let tx = f64::from(p.expect_number()?);
+ let tx = f64::from(p.expect_number()?);
- let ty = f64::from(p.try(|p| -> Result<f32, CssParseError<()>> {
- optional_comma(p);
- Ok(p.expect_number()?)
- }).unwrap_or(0.0));
+ let ty = f64::from(p.try(|p| -> Result<f32, CssParseError<()>> {
+ optional_comma(p);
+ Ok(p.expect_number()?)
+ }).unwrap_or(0.0));
- Ok(cairo::Matrix::new(1.0, 0.0, 0.0, 1.0, tx, ty))
- }).map_err(CssParseError::<()>::basic)
- .map_err(AttributeError::from)
+ Ok(cairo::Matrix::new(1.0, 0.0, 0.0, 1.0, tx, ty))
+ })
+ .map_err(CssParseError::<()>::basic)
+ .map_err(AttributeError::from)
}
fn parse_scale_args(parser: &mut Parser) -> Result<cairo::Matrix, AttributeError> {
parser.parse_nested_block(|p| {
- let x = f64::from(p.expect_number()?);
-
- let y = p.try(|p| -> Result<f32, CssParseError<()>> {
- optional_comma(p);
- Ok(p.expect_number()?)
- }).map(f64::from).unwrap_or(x);
-
- Ok(cairo::Matrix::new(x, 0.0, 0.0, y, 0.0, 0.0))
- }).map_err(CssParseError::<()>::basic)
- .map_err(AttributeError::from)
+ let x = f64::from(p.expect_number()?);
+
+ let y = p.try(|p| -> Result<f32, CssParseError<()>> {
+ optional_comma(p);
+ Ok(p.expect_number()?)
+ }).map(f64::from)
+ .unwrap_or(x);
+
+ Ok(cairo::Matrix::new(x, 0.0, 0.0, y, 0.0, 0.0))
+ })
+ .map_err(CssParseError::<()>::basic)
+ .map_err(AttributeError::from)
}
fn parse_rotate_args(parser: &mut Parser) -> Result<cairo::Matrix, AttributeError> {
parser.parse_nested_block(|p| {
- let angle = f64::from(p.expect_number()?) * PI / 180.0;
- let (s, c) = angle.sin_cos();
-
- let (tx, ty) = p.try(|p| -> Result<_, CssParseError<()>> {
- optional_comma(p);
- let tx = f64::from(p.expect_number()?);
-
- optional_comma(p);
- let ty = f64::from(p.expect_number()?);
-
- Ok((tx, ty))
- }).unwrap_or((0.0, 0.0));
-
- let mut m = cairo::Matrix::new (1.0, 0.0, 0.0, 1.0, tx, ty);
-
- m = cairo::Matrix::multiply (&cairo::Matrix::new (c, s, -s, c, 0.0, 0.0), &m);
- m = cairo::Matrix::multiply (&cairo::Matrix::new (1.0, 0.0, 0.0, 1.0, -tx, -ty), &m);
- Ok(m)
- }).map_err(CssParseError::<()>::basic)
- .map_err(AttributeError::from)
+ let angle = f64::from(p.expect_number()?) * PI / 180.0;
+ let (s, c) = angle.sin_cos();
+
+ let (tx, ty) = p.try(|p| -> Result<_, CssParseError<()>> {
+ optional_comma(p);
+ let tx = f64::from(p.expect_number()?);
+
+ optional_comma(p);
+ let ty = f64::from(p.expect_number()?);
+
+ Ok((tx, ty))
+ }).unwrap_or((0.0, 0.0));
+
+ let mut m = cairo::Matrix::new(1.0, 0.0, 0.0, 1.0, tx, ty);
+
+ m = cairo::Matrix::multiply(&cairo::Matrix::new(c,
+ s,
+ -s,
+ c,
+ 0.0,
+ 0.0),
+ &m);
+ m = cairo::Matrix::multiply(&cairo::Matrix::new(1.0,
+ 0.0,
+ 0.0,
+ 1.0,
+ -tx,
+ -ty),
+ &m);
+ Ok(m)
+ })
+ .map_err(CssParseError::<()>::basic)
+ .map_err(AttributeError::from)
}
fn parse_skewx_args(parser: &mut Parser) -> Result<cairo::Matrix, AttributeError> {
parser.parse_nested_block(|p| {
- let a = f64::from(p.expect_number()?) * PI / 180.0;
- Ok(cairo::Matrix::new (1.0, 0.0,
- a.tan (), 1.0,
- 0.0, 0.0))
- }).map_err(CssParseError::<()>::basic)
- .map_err(AttributeError::from)
+ let a = f64::from(p.expect_number()?) * PI / 180.0;
+ Ok(cairo::Matrix::new(1.0, 0.0, a.tan(), 1.0, 0.0, 0.0))
+ })
+ .map_err(CssParseError::<()>::basic)
+ .map_err(AttributeError::from)
}
fn parse_skewy_args(parser: &mut Parser) -> Result<cairo::Matrix, AttributeError> {
parser.parse_nested_block(|p| {
- let a = f64::from(p.expect_number()?) * PI / 180.0;
- Ok(cairo::Matrix::new (1.0, a.tan (),
- 0.0, 1.0,
- 0.0, 0.0))
- }).map_err(CssParseError::<()>::basic)
- .map_err(AttributeError::from)
+ let a = f64::from(p.expect_number()?) * PI / 180.0;
+ Ok(cairo::Matrix::new(1.0, a.tan(), 0.0, 1.0, 0.0, 0.0))
+ })
+ .map_err(CssParseError::<()>::basic)
+ .map_err(AttributeError::from)
}
#[cfg(test)]
-fn make_rotation_matrix (angle_degrees: f64, tx: f64, ty: f64) -> cairo::Matrix {
+fn make_rotation_matrix(angle_degrees: f64, tx: f64, ty: f64) -> cairo::Matrix {
let angle = angle_degrees * PI / 180.0;
- let mut m = cairo::Matrix::new (1.0, 0.0, 0.0, 1.0, tx, ty);
+ let mut m = cairo::Matrix::new(1.0, 0.0, 0.0, 1.0, tx, ty);
- let mut r = cairo::Matrix::identity ();
- r.rotate (angle);
- m = cairo::Matrix::multiply (&r, &m);
+ let mut r = cairo::Matrix::identity();
+ r.rotate(angle);
+ m = cairo::Matrix::multiply(&r, &m);
- m = cairo::Matrix::multiply (&cairo::Matrix::new (1.0, 0.0, 0.0, 1.0, -tx, -ty), &m);
+ m = cairo::Matrix::multiply(&cairo::Matrix::new(1.0, 0.0, 0.0, 1.0, -tx, -ty), &m);
m
}
#[no_mangle]
-pub extern fn rsvg_parse_transform (out_matrix: *mut cairo::Matrix, s: *const libc::c_char) ->
glib_sys::gboolean {
- assert! (!out_matrix.is_null ());
- assert! (!s.is_null ());
+pub extern "C" fn rsvg_parse_transform(out_matrix: *mut cairo::Matrix,
+ s: *const libc::c_char)
+ -> glib_sys::gboolean {
+ assert!(!out_matrix.is_null());
+ assert!(!s.is_null());
let string = unsafe { utf8_cstr(s) };
let matrix: &mut cairo::Matrix = unsafe { &mut *out_matrix };
- match parse_transform (string) {
- Ok (m) => {
+ match parse_transform(string) {
+ Ok(m) => {
*matrix = m;
- true.to_glib ()
- },
+ true.to_glib()
+ }
- Err (_) => {
- *matrix = cairo::Matrix::identity ();
- false.to_glib ()
+ Err(_) => {
+ *matrix = cairo::Matrix::identity();
+ false.to_glib()
}
}
}
@@ -217,25 +237,27 @@ mod test {
use super::*;
#[test]
- fn parses_valid_transform () {
- let t = cairo::Matrix::new (1.0, 0.0, 0.0, 1.0, 20.0, 30.0);
- let s = cairo::Matrix::new (10.0, 0.0, 0.0, 10.0, 0.0, 0.0);
- let r = make_rotation_matrix (30.0, 10.0, 10.0);
-
- let a = cairo::Matrix::multiply (&s, &t);
- assert_eq! (parse_transform ("translate(20, 30), scale (10) rotate (30 10 10)").unwrap (),
- cairo::Matrix::multiply (&r, &a));
+ fn parses_valid_transform() {
+ let t = cairo::Matrix::new(1.0, 0.0, 0.0, 1.0, 20.0, 30.0);
+ let s = cairo::Matrix::new(10.0, 0.0, 0.0, 10.0, 0.0, 0.0);
+ let r = make_rotation_matrix(30.0, 10.0, 10.0);
+
+ let a = cairo::Matrix::multiply(&s, &t);
+ assert_eq!(parse_transform("translate(20, 30), scale (10) rotate (30 10 10)").unwrap(),
+ cairo::Matrix::multiply(&r, &a));
}
fn assert_parse_error(s: &str) {
match parse_transform(s) {
- Err(AttributeError::Parse(_)) => {},
- _ => { panic!(); }
+ Err(AttributeError::Parse(_)) => {}
+ _ => {
+ panic!();
+ }
}
}
#[test]
- fn syntax_error_yields_parse_error () {
+ fn syntax_error_yields_parse_error() {
assert_parse_error("foo");
assert_parse_error("matrix (1 2 3 4 5)");
assert_parse_error("translate(1 2 3 4 5)");
@@ -247,20 +269,26 @@ mod test {
}
#[test]
- fn invalid_transform_yields_value_error () {
- match parse_transform ("matrix (0 0 0 0 0 0)") {
- Err (AttributeError::Value (_)) => {},
- _ => { panic! (); }
+ fn invalid_transform_yields_value_error() {
+ match parse_transform("matrix (0 0 0 0 0 0)") {
+ Err(AttributeError::Value(_)) => {}
+ _ => {
+ panic!();
+ }
}
- match parse_transform ("scale (0), translate (10, 10)") {
- Err (AttributeError::Value (_)) => {},
- _ => { panic! (); }
+ match parse_transform("scale (0), translate (10, 10)") {
+ Err(AttributeError::Value(_)) => {}
+ _ => {
+ panic!();
+ }
}
- match parse_transform ("scale (0), skewX (90)") {
- Err (AttributeError::Value (_)) => {},
- _ => { panic! (); }
+ match parse_transform("scale (0), skewX (90)") {
+ Err(AttributeError::Value(_)) => {}
+ _ => {
+ panic!();
+ }
}
}
}
@@ -270,86 +298,89 @@ mod parser_tests {
use super::*;
#[test]
- fn parses_matrix () {
- assert_eq! (parse_transform ("matrix (1 2 3 4 5 6)").unwrap (),
- cairo::Matrix::new (1.0, 2.0, 3.0, 4.0, 5.0, 6.0));
+ fn parses_matrix() {
+ assert_eq!(parse_transform("matrix (1 2 3 4 5 6)").unwrap(),
+ cairo::Matrix::new(1.0, 2.0, 3.0, 4.0, 5.0, 6.0));
- assert_eq! (parse_transform ("matrix(1,2,3,4 5 6)").unwrap (),
- cairo::Matrix::new (1.0, 2.0, 3.0, 4.0, 5.0, 6.0));
+ assert_eq!(parse_transform("matrix(1,2,3,4 5 6)").unwrap(),
+ cairo::Matrix::new(1.0, 2.0, 3.0, 4.0, 5.0, 6.0));
- assert_eq! (parse_transform ("matrix (1,2.25,-3.25e2,4 5 6)").unwrap (),
- cairo::Matrix::new (1.0, 2.25, -325.0, 4.0, 5.0, 6.0));
+ assert_eq!(parse_transform("matrix (1,2.25,-3.25e2,4 5 6)").unwrap(),
+ cairo::Matrix::new(1.0, 2.25, -325.0, 4.0, 5.0, 6.0));
}
#[test]
- fn parses_translate () {
- assert_eq! (parse_transform ("translate(-1 -2)").unwrap (),
- cairo::Matrix::new (1.0, 0.0, 0.0, 1.0, -1.0, -2.0));
+ fn parses_translate() {
+ assert_eq!(parse_transform("translate(-1 -2)").unwrap(),
+ cairo::Matrix::new(1.0, 0.0, 0.0, 1.0, -1.0, -2.0));
- assert_eq! (parse_transform ("translate(-1, -2)").unwrap (),
- cairo::Matrix::new (1.0, 0.0, 0.0, 1.0, -1.0, -2.0));
+ assert_eq!(parse_transform("translate(-1, -2)").unwrap(),
+ cairo::Matrix::new(1.0, 0.0, 0.0, 1.0, -1.0, -2.0));
- assert_eq! (parse_transform ("translate(-1)").unwrap (),
- cairo::Matrix::new (1.0, 0.0, 0.0, 1.0, -1.0, 0.0));
+ assert_eq!(parse_transform("translate(-1)").unwrap(),
+ cairo::Matrix::new(1.0, 0.0, 0.0, 1.0, -1.0, 0.0));
}
#[test]
fn parses_scale() {
- assert_eq! (parse_transform ("scale (-1)").unwrap (),
- cairo::Matrix::new (-1.0, 0.0, 0.0, -1.0, 0.0, 0.0));
+ assert_eq!(parse_transform("scale (-1)").unwrap(),
+ cairo::Matrix::new(-1.0, 0.0, 0.0, -1.0, 0.0, 0.0));
- assert_eq! (parse_transform ("scale(-1 -2)").unwrap (),
- cairo::Matrix::new (-1.0, 0.0, 0.0, -2.0, 0.0, 0.0));
+ assert_eq!(parse_transform("scale(-1 -2)").unwrap(),
+ cairo::Matrix::new(-1.0, 0.0, 0.0, -2.0, 0.0, 0.0));
- assert_eq! (parse_transform ("scale(-1, -2)").unwrap (),
- cairo::Matrix::new (-1.0, 0.0, 0.0, -2.0, 0.0, 0.0));
+ assert_eq!(parse_transform("scale(-1, -2)").unwrap(),
+ cairo::Matrix::new(-1.0, 0.0, 0.0, -2.0, 0.0, 0.0));
}
#[test]
- fn parses_rotate () {
- assert_eq! (parse_transform ("rotate (30)").unwrap (), make_rotation_matrix (30.0, 0.0, 0.0));
- assert_eq! (parse_transform ("rotate (30,-1,-2)").unwrap (), make_rotation_matrix (30.0, -1.0,
-2.0));
- assert_eq! (parse_transform ("rotate(30, -1, -2)").unwrap (), make_rotation_matrix (30.0, -1.0,
-2.0));
+ fn parses_rotate() {
+ assert_eq!(parse_transform("rotate (30)").unwrap(),
+ make_rotation_matrix(30.0, 0.0, 0.0));
+ assert_eq!(parse_transform("rotate (30,-1,-2)").unwrap(),
+ make_rotation_matrix(30.0, -1.0, -2.0));
+ assert_eq!(parse_transform("rotate(30, -1, -2)").unwrap(),
+ make_rotation_matrix(30.0, -1.0, -2.0));
}
- fn make_skew_x_matrix (angle_degrees: f64) -> cairo::Matrix {
+ fn make_skew_x_matrix(angle_degrees: f64) -> cairo::Matrix {
let a = angle_degrees * PI / 180.0;
- cairo::Matrix::new (1.0, 0.0,
- a.tan (), 1.0,
- 0.0, 0.0)
+ cairo::Matrix::new(1.0, 0.0, a.tan(), 1.0, 0.0, 0.0)
}
- fn make_skew_y_matrix (angle_degrees: f64) -> cairo::Matrix {
- let mut m = make_skew_x_matrix (angle_degrees);
+ fn make_skew_y_matrix(angle_degrees: f64) -> cairo::Matrix {
+ let mut m = make_skew_x_matrix(angle_degrees);
m.yx = m.xy;
m.xy = 0.0;
m
}
#[test]
- fn parses_skew_x () {
- assert_eq! (parse_transform ("skewX (30)").unwrap (), make_skew_x_matrix (30.0));
+ fn parses_skew_x() {
+ assert_eq!(parse_transform("skewX (30)").unwrap(),
+ make_skew_x_matrix(30.0));
}
#[test]
- fn parses_skew_y () {
- assert_eq! (parse_transform ("skewY (30)").unwrap (), make_skew_y_matrix (30.0));
+ fn parses_skew_y() {
+ assert_eq!(parse_transform("skewY (30)").unwrap(),
+ make_skew_y_matrix(30.0));
}
#[test]
- fn parses_transform_list () {
- let t = cairo::Matrix::new (1.0, 0.0, 0.0, 1.0, 20.0, 30.0);
- let s = cairo::Matrix::new (10.0, 0.0, 0.0, 10.0, 0.0, 0.0);
- let r = make_rotation_matrix (30.0, 10.0, 10.0);
+ fn parses_transform_list() {
+ let t = cairo::Matrix::new(1.0, 0.0, 0.0, 1.0, 20.0, 30.0);
+ let s = cairo::Matrix::new(10.0, 0.0, 0.0, 10.0, 0.0, 0.0);
+ let r = make_rotation_matrix(30.0, 10.0, 10.0);
- assert_eq! (parse_transform ("scale(10)rotate(30, 10, 10)").unwrap (),
- cairo::Matrix::multiply (&r, &s));
+ assert_eq!(parse_transform("scale(10)rotate(30, 10, 10)").unwrap(),
+ cairo::Matrix::multiply(&r, &s));
- assert_eq! (parse_transform ("translate(20, 30), scale (10)").unwrap (),
- cairo::Matrix::multiply (&s, &t));
+ assert_eq!(parse_transform("translate(20, 30), scale (10)").unwrap(),
+ cairo::Matrix::multiply(&s, &t));
- let a = cairo::Matrix::multiply (&s, &t);
- assert_eq! (parse_transform ("translate(20, 30), scale (10) rotate (30 10 10)").unwrap (),
- cairo::Matrix::multiply (&r, &a));
+ let a = cairo::Matrix::multiply(&s, &t);
+ assert_eq!(parse_transform("translate(20, 30), scale (10) rotate (30 10 10)").unwrap(),
+ cairo::Matrix::multiply(&r, &a));
}
}
diff --git a/rsvg_internals/src/util.rs b/rsvg_internals/src/util.rs
index f0b62aa7..0035e6f4 100644
--- a/rsvg_internals/src/util.rs
+++ b/rsvg_internals/src/util.rs
@@ -6,9 +6,9 @@ use std::str;
// In paint servers (patterns, gradients, etc.), we have an
// Option<String> for fallback names. This is a utility function to
// clone one of those.
-pub fn clone_fallback_name (fallback: &Option<String>) -> Option<String> {
- if let Some (ref fallback_name) = *fallback {
- Some (fallback_name.clone ())
+pub fn clone_fallback_name(fallback: &Option<String>) -> Option<String> {
+ if let Some(ref fallback_name) = *fallback {
+ Some(fallback_name.clone())
} else {
None
}
@@ -16,8 +16,8 @@ pub fn clone_fallback_name (fallback: &Option<String>) -> Option<String> {
pub const DBL_EPSILON: f64 = 1e-10;
-pub fn double_equals (a: f64, b: f64) -> bool {
- (a - b).abs () < DBL_EPSILON
+pub fn double_equals(a: f64, b: f64) -> bool {
+ (a - b).abs() < DBL_EPSILON
}
/// Converts a `char *` which is known to be valid UTF-8 into a `&str`
diff --git a/rsvg_internals/src/viewbox.rs b/rsvg_internals/src/viewbox.rs
index 8ee4958a..97a03df7 100644
--- a/rsvg_internals/src/viewbox.rs
+++ b/rsvg_internals/src/viewbox.rs
@@ -1,11 +1,11 @@
use cairo;
-use glib_sys;
use glib;
+use glib_sys;
use error::*;
use parsers;
-use parsers::Parse;
use parsers::{ListLength, ParseError};
+use parsers::Parse;
use self::glib::translate::*;
@@ -14,7 +14,7 @@ use self::glib::translate::*;
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct RsvgViewBox {
pub rect: cairo::Rectangle,
- active: glib_sys::gboolean
+ active: glib_sys::gboolean,
}
#[derive(Debug, Copy, Clone, PartialEq)]
@@ -22,27 +22,27 @@ pub struct ViewBox(pub cairo::Rectangle);
impl ViewBox {
pub fn new(x: f64, y: f64, w: f64, h: f64) -> ViewBox {
- assert!(w >= 0.0 && h >= 0.0, "width and height must not be negative");
+ assert!(w >= 0.0 && h >= 0.0,
+ "width and height must not be negative");
- ViewBox(cairo::Rectangle { x: x, y: y, width: w, height: h })
+ ViewBox(cairo::Rectangle { x,
+ y,
+ width: w,
+ height: h, })
}
}
impl From<Option<ViewBox>> for RsvgViewBox {
fn from(v: Option<ViewBox>) -> RsvgViewBox {
if let Some(vb) = v {
- RsvgViewBox {
- rect: vb.0,
- active: true.to_glib ()
- }
+ RsvgViewBox { rect: vb.0,
+ active: true.to_glib(), }
} else {
- RsvgViewBox {
- rect: cairo::Rectangle { x: 0.0,
- y: 0.0,
- width: 0.0,
- height: 0.0 },
- active: false.to_glib ()
- }
+ RsvgViewBox { rect: cairo::Rectangle { x: 0.0,
+ y: 0.0,
+ width: 0.0,
+ height: 0.0, },
+ active: false.to_glib(), }
}
}
}
@@ -59,19 +59,19 @@ impl Parse for ViewBox {
// x, y, w, h
//
// Where w and h must be nonnegative.
- fn parse (s: &str, _: ()) -> Result<ViewBox, AttributeError> {
+ fn parse(s: &str, _: ()) -> Result<ViewBox, AttributeError> {
let v = parsers::number_list (s, ListLength::Exact (4))
.map_err (|_| ParseError::new ("string does not match 'x [,] y [,] w [,] h'"))?;
let (x, y, w, h) = (v[0], v[1], v[2], v[3]);
if w >= 0.0 && h >= 0.0 {
- Ok (ViewBox(cairo::Rectangle { x: x,
- y: y,
- width: w,
- height: h }))
+ Ok(ViewBox(cairo::Rectangle { x,
+ y,
+ width: w,
+ height: h, }))
} else {
- Err (AttributeError::Value ("width and height must not be negative".to_string ()))
+ Err(AttributeError::Value("width and height must not be negative".to_string()))
}
}
}
@@ -81,24 +81,24 @@ mod tests {
use super::*;
#[test]
- fn parses_valid_viewboxes () {
- assert_eq! (ViewBox::parse (" 1 2 3 4", ()),
- Ok (ViewBox::new(1.0, 2.0, 3.0, 4.0)));
+ fn parses_valid_viewboxes() {
+ assert_eq!(ViewBox::parse(" 1 2 3 4", ()),
+ Ok(ViewBox::new(1.0, 2.0, 3.0, 4.0)));
- assert_eq! (ViewBox::parse (" -1.5 -2.5e1,34,56e2 ", ()),
- Ok (ViewBox::new(-1.5, -25.0, 34.0, 5600.0)));
+ assert_eq!(ViewBox::parse(" -1.5 -2.5e1,34,56e2 ", ()),
+ Ok(ViewBox::new(-1.5, -25.0, 34.0, 5600.0)));
}
#[test]
- fn parsing_invalid_viewboxes_yields_error () {
- assert! (is_parse_error (&ViewBox::parse ("", ())));
+ fn parsing_invalid_viewboxes_yields_error() {
+ assert!(is_parse_error(&ViewBox::parse("", ())));
- assert! (is_value_error (&ViewBox::parse (" 1,2,-3,-4 ", ())));
+ assert!(is_value_error(&ViewBox::parse(" 1,2,-3,-4 ", ())));
- assert! (is_parse_error (&ViewBox::parse ("qwerasdfzxcv", ())));
+ assert!(is_parse_error(&ViewBox::parse("qwerasdfzxcv", ())));
- assert! (is_parse_error (&ViewBox::parse (" 1 2 3 4 5", ())));
+ assert!(is_parse_error(&ViewBox::parse(" 1 2 3 4 5", ())));
- assert! (is_parse_error (&ViewBox::parse (" 1 2 foo 3 4", ())));
+ assert!(is_parse_error(&ViewBox::parse(" 1 2 foo 3 4", ())));
}
}
diff --git a/rsvg_internals/src/viewport.rs b/rsvg_internals/src/viewport.rs
index 09bfa269..a190262a 100644
--- a/rsvg_internals/src/viewport.rs
+++ b/rsvg_internals/src/viewport.rs
@@ -10,10 +10,13 @@ use viewbox::*;
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum ClipMode {
ClipToViewport,
- ClipToVbox
+ ClipToVbox,
}
-pub fn draw_in_viewport<F>(vx: f64, vy: f64, vw: f64, vh: f64,
+pub fn draw_in_viewport<F>(vx: f64,
+ vy: f64,
+ vw: f64,
+ vh: f64,
clip_mode: ClipMode,
do_clip: bool,
vbox: Option<ViewBox>,
@@ -26,7 +29,10 @@ pub fn draw_in_viewport<F>(vx: f64, vy: f64, vw: f64, vh: f64,
let mut ctx = RsvgDrawingCtxWrapper(draw_ctx);
in_viewport(&mut ctx,
- vx, vy, vw, vh,
+ vx,
+ vy,
+ vw,
+ vh,
clip_mode,
do_clip,
vbox,
@@ -37,7 +43,7 @@ pub fn draw_in_viewport<F>(vx: f64, vy: f64, vw: f64, vh: f64,
trait ViewportCtx {
fn push_view_box(&mut self, width: f64, height: f64);
- fn pop_view_box(&mut self, );
+ fn pop_view_box(&mut self);
fn push_discrete_layer(&mut self);
fn pop_discrete_layer(&mut self);
fn add_clipping_rect(&mut self, x: f64, y: f64, w: f64, h: f64);
@@ -73,7 +79,10 @@ impl ViewportCtx for RsvgDrawingCtxWrapper {
}
fn in_viewport<F>(ctx: &mut ViewportCtx,
- vx: f64, vy: f64, vw: f64, vh: f64,
+ vx: f64,
+ vy: f64,
+ vw: f64,
+ vh: f64,
clip_mode: ClipMode,
do_clip: bool,
vbox: Option<ViewBox>,
@@ -107,8 +116,8 @@ fn in_viewport<F>(ctx: &mut ViewportCtx,
ctx.push_view_box(vbox.0.width, vbox.0.height);
ctx.push_discrete_layer();
- let (x, y, w, h) = preserve_aspect_ratio.compute(vbox.0.width, vbox.0.height,
- vx, vy, vw, vh);
+ let (x, y, w, h) =
+ preserve_aspect_ratio.compute(vbox.0.width, vbox.0.height, vx, vy, vw, vh);
affine.translate(x, y);
affine.scale(w / vbox.0.width, h / vbox.0.height);
@@ -148,11 +157,11 @@ mod tests {
struct Ctx {
pub view_box_size: Option<(f64, f64)>,
pub clipping_rect: Option<(f64, f64, f64, f64)>,
- pub affine: Option<cairo::Matrix>,
+ pub affine: Option<cairo::Matrix>,
pub expected_view_box_size: Option<(f64, f64)>,
pub expected_clipping_rect: Option<(f64, f64, f64, f64)>,
- pub expected_affine: Option<cairo::Matrix>,
+ pub expected_affine: Option<cairo::Matrix>,
}
impl ViewportCtx for Ctx {
@@ -160,14 +169,11 @@ mod tests {
self.view_box_size = Some((width, height));
}
- fn pop_view_box(&mut self) {
- }
+ fn pop_view_box(&mut self) {}
- fn push_discrete_layer(&mut self) {
- }
+ fn push_discrete_layer(&mut self) {}
- fn pop_discrete_layer(&mut self) {
- }
+ fn pop_discrete_layer(&mut self) {}
fn add_clipping_rect(&mut self, x: f64, y: f64, w: f64, h: f64) {
self.clipping_rect = Some((x, y, w, h));
@@ -178,7 +184,10 @@ mod tests {
}
}
- fn call_in_viewport(vx: f64, vy: f64, vw: f64, vh: f64,
+ fn call_in_viewport(vx: f64,
+ vy: f64,
+ vw: f64,
+ vh: f64,
clip_mode: ClipMode,
do_clip: bool,
vbox: Option<ViewBox>,
@@ -186,7 +195,10 @@ mod tests {
affine: cairo::Matrix,
ctx: &mut Ctx) {
in_viewport(ctx,
- vx, vy, vw, vh,
+ vx,
+ vy,
+ vw,
+ vh,
clip_mode,
do_clip,
vbox,
@@ -204,17 +216,18 @@ mod tests {
let mut affine = cairo::Matrix::identity();
affine.scale(0.25, 0.25);
- let mut ctx = Ctx {
- view_box_size: None,
- clipping_rect: None,
- affine: None,
-
- expected_view_box_size: Some((40.0, 40.0)),
- expected_clipping_rect: Some((10.0, 10.0, 10.0, 10.0)),
- expected_affine: Some(affine)
+ let mut ctx = Ctx { view_box_size: None,
+ clipping_rect: None,
+ affine: None,
+ expected_view_box_size: Some((40.0, 40.0)),
+ expected_clipping_rect: Some((10.0, 10.0, 10.0, 10.0)),
+ expected_affine: Some(affine)
};
- call_in_viewport(10.0, 10.0, 10.0, 10.0,
+ call_in_viewport(10.0,
+ 10.0,
+ 10.0,
+ 10.0,
ClipMode::ClipToViewport,
true,
Some(ViewBox(cairo::Rectangle {
@@ -234,25 +247,24 @@ mod tests {
affine.translate(10.0, 10.0);
affine.scale(0.40, 0.40);
- let mut ctx = Ctx {
- view_box_size: None,
- clipping_rect: None,
- affine: None,
+ let mut ctx = Ctx { view_box_size: None,
+ clipping_rect: None,
+ affine: None,
- expected_view_box_size: Some((50.0, 50.0)),
- expected_clipping_rect: Some((0.0, 0.0, 50.0, 50.0)),
- expected_affine: Some(affine)
- };
+ expected_view_box_size: Some((50.0, 50.0)),
+ expected_clipping_rect: Some((0.0, 0.0, 50.0, 50.0)),
+ expected_affine: Some(affine), };
- call_in_viewport(10.0, 10.0, 20.0, 20.0,
+ call_in_viewport(10.0,
+ 10.0,
+ 20.0,
+ 20.0,
ClipMode::ClipToVbox,
true,
- Some(ViewBox(cairo::Rectangle {
- x: 0.0,
- y: 0.0,
- width: 50.0,
- height: 50.0,
- })),
+ Some(ViewBox(cairo::Rectangle { x: 0.0,
+ y: 0.0,
+ width: 50.0,
+ height: 50.0, })),
AspectRatio::parse("xMidYMid meet", ()).unwrap(),
cairo::Matrix::identity(),
&mut ctx);
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]