SvgPathBuilder.cs 10.4 KB
Newer Older
davescriven's avatar
davescriven committed
1
2
using System;
using System.Collections.Generic;
3
using System.ComponentModel;
davescriven's avatar
davescriven committed
4
using System.Diagnostics;
5
using System.Drawing;
6
using System.Globalization;
davescriven's avatar
davescriven committed
7
8
9
10
11
12
13

using Svg.Pathing;

namespace Svg
{
    internal class SvgPathBuilder : TypeConverter
    {
14
15
16
17
        /// <summary>
        /// Parses the specified string into a collection of path segments.
        /// </summary>
        /// <param name="path">A <see cref="string"/> containing path data.</param>
davescriven's avatar
davescriven committed
18
19
20
        public static SvgPathSegmentList Parse(string path)
        {
            if (string.IsNullOrEmpty(path))
21
            {
davescriven's avatar
davescriven committed
22
                throw new ArgumentNullException("path");
23
            }
davescriven's avatar
davescriven committed
24

25
            var segments = new SvgPathSegmentList();
davescriven's avatar
davescriven committed
26
27
28

            try
            {
29
                foreach (var commandSet in SplitCommands(path.TrimEnd(null)))
davescriven's avatar
davescriven committed
30
                {
31
32
33
                    var coords = new List<float>(ParseCoordinates(commandSet));
                    var command = commandSet[0];
                    var isRelative = char.IsLower(command);
davescriven's avatar
davescriven committed
34
35
36
37
38
39
                    // http://www.w3.org/TR/SVG11/paths.html#PathDataGeneralInformation

                    switch (command)
                    {
                        case 'm': // relative moveto
                        case 'M': // moveto
40
41
42
43
                            segments.Add(
                                new SvgMoveToSegment(ToAbsolute(coords[0], coords[1], segments, isRelative)));

                            for (var i = 2; i < coords.Count; i += 2)
davescriven's avatar
davescriven committed
44
                            {
45
46
                                segments.Add(new SvgLineSegment(segments.Last.End,
                                    ToAbsolute(coords[i], coords[i + 1], segments, isRelative)));
davescriven's avatar
davescriven committed
47
48
49
50
51
52
53
                            }
                            break;
                        case 'a':
                        case 'A':
                            throw new NotImplementedException("Arc segments are not yet implemented");
                        case 'l': // relative lineto
                        case 'L': // lineto
54
                            for (var i = 0; i < coords.Count; i += 2)
davescriven's avatar
davescriven committed
55
                            {
56
57
                                segments.Add(new SvgLineSegment(segments.Last.End,
                                    ToAbsolute(coords[i], coords[i + 1], segments, isRelative)));
davescriven's avatar
davescriven committed
58
59
60
61
                            }
                            break;
                        case 'H': // horizontal lineto
                        case 'h': // relative horizontal lineto
62
63
64
                            foreach (var value in coords)
                                segments.Add(new SvgLineSegment(segments.Last.End,
                                    ToAbsolute(value, segments.Last.End.Y, segments, isRelative, false)));
davescriven's avatar
davescriven committed
65
66
67
                            break;
                        case 'V': // vertical lineto
                        case 'v': // relative vertical lineto
68
69
70
                            foreach (var value in coords)
                                segments.Add(new SvgLineSegment(segments.Last.End,
                                    ToAbsolute(segments.Last.End.X, value, segments, false, isRelative)));
davescriven's avatar
davescriven committed
71
72
73
                            break;
                        case 'Q': // curveto
                        case 'q': // relative curveto
74
                            for (var i = 0; i < coords.Count; i += 4)
davescriven's avatar
davescriven committed
75
                            {
76
77
78
                                segments.Add(new SvgQuadraticCurveSegment(segments.Last.End,
                                    ToAbsolute(coords[i], coords[i + 1], segments, isRelative),
                                    ToAbsolute(coords[i + 2], coords[i + 3], segments, isRelative)));
davescriven's avatar
davescriven committed
79
80
81
82
                            }
                            break;
                        case 'T': // shorthand/smooth curveto
                        case 't': // relative shorthand/smooth curveto
83
                            for (var i = 0; i < coords.Count; i += 2)
davescriven's avatar
davescriven committed
84
                            {
85
                                var lastQuadCurve = segments.Last as SvgQuadraticCurveSegment;
davescriven's avatar
davescriven committed
86

87
88
89
                                var controlPoint = lastQuadCurve != null
                                    ? Reflect(lastQuadCurve.ControlPoint, segments.Last.End)
                                    : segments.Last.End;
davescriven's avatar
davescriven committed
90

91
92
                                segments.Add(new SvgQuadraticCurveSegment(segments.Last.End, controlPoint,
                                    ToAbsolute(coords[i], coords[i + 1], segments, isRelative)));
davescriven's avatar
davescriven committed
93
94
95
96
                            }
                            break;
                        case 'C': // curveto
                        case 'c': // relative curveto
97
                            for (var i = 0; i < coords.Count; i += 6)
davescriven's avatar
davescriven committed
98
                            {
99
100
101
102
                                segments.Add(new SvgCubicCurveSegment(segments.Last.End,
                                    ToAbsolute(coords[i], coords[i + 1], segments, isRelative),
                                    ToAbsolute(coords[i + 2], coords[i + 3], segments, isRelative),
                                    ToAbsolute(coords[i + 4], coords[i + 5], segments, isRelative)));
davescriven's avatar
davescriven committed
103
104
105
106
107
                            }
                            break;
                        case 'S': // shorthand/smooth curveto
                        case 's': // relative shorthand/smooth curveto

108
                            for (var i = 0; i < coords.Count; i += 4)
davescriven's avatar
davescriven committed
109
                            {
110
111
112
113
114
115
116
117
118
                                var lastCubicCurve = segments.Last as SvgCubicCurveSegment;

                                var controlPoint = lastCubicCurve != null
                                    ? Reflect(lastCubicCurve.SecondControlPoint, segments.Last.End)
                                    : segments.Last.End;

                                segments.Add(new SvgCubicCurveSegment(segments.Last.End, controlPoint,
                                    ToAbsolute(coords[i], coords[i + 1], segments, isRelative),
                                    ToAbsolute(coords[i + 2], coords[i + 3], segments, isRelative)));
davescriven's avatar
davescriven committed
119
120
121
122
123
124
125
126
127
                            }
                            break;
                        case 'Z': // closepath
                        case 'z': // relative closepath
                            segments.Add(new SvgClosePathSegment());
                            break;
                    }
                }
            }
128
            catch (Exception exc)
davescriven's avatar
davescriven committed
129
            {
130
                Trace.TraceError("Error parsing path \"{0}\": {1}", path, exc.Message);
davescriven's avatar
davescriven committed
131
132
133
134
135
136
137
138
            }

            return segments;
        }

        private static PointF Reflect(PointF point, PointF mirror)
        {
            // TODO: Only works left to right???
139
140
            var x = mirror.X + (mirror.X - point.X);
            var y = mirror.Y + (mirror.Y - point.Y);
davescriven's avatar
davescriven committed
141
142
143
144

            return new PointF(Math.Abs(x), Math.Abs(y));
        }

145
146
147
148
149
150
151
152
153
        /// <summary>
        /// Creates point with absolute coorindates.
        /// </summary>
        /// <param name="x">Raw X-coordinate value.</param>
        /// <param name="y">Raw Y-coordinate value.</param>
        /// <param name="segments">Current path segments.</param>
        /// <param name="isRelativeBoth"><b>true</b> if <paramref name="x"/> and <paramref name="y"/> contains relative coordinate values, otherwise <b>false</b>.</param>
        /// <returns><see cref="PointF"/> that contains absolute coordinates.</returns>
        private static PointF ToAbsolute(float x, float y, SvgPathSegmentList segments, bool isRelativeBoth)
davescriven's avatar
davescriven committed
154
        {
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
            return ToAbsolute(x, y, segments, isRelativeBoth, isRelativeBoth);
        }

        /// <summary>
        /// Creates point with absolute coorindates.
        /// </summary>
        /// <param name="x">Raw X-coordinate value.</param>
        /// <param name="y">Raw Y-coordinate value.</param>
        /// <param name="segments">Current path segments.</param>
        /// <param name="isRelativeX"><b>true</b> if <paramref name="x"/> contains relative coordinate value, otherwise <b>false</b>.</param>
        /// <param name="isRelativeY"><b>true</b> if <paramref name="y"/> contains relative coordinate value, otherwise <b>false</b>.</param>
        /// <returns><see cref="PointF"/> that contains absolute coordinates.</returns>
        private static PointF ToAbsolute(float x, float y, SvgPathSegmentList segments, bool isRelativeX, bool isRelativeY)
        {
            var point = new PointF(x, y);

            if ((isRelativeX || isRelativeY) && segments.Count > 0)
            {
                var lastSegment = segments.Last;

                if (isRelativeX)
                    point.X += lastSegment.End.X;

                if (isRelativeY)
                    point.Y += lastSegment.End.Y;
            }

            return point;
davescriven's avatar
davescriven committed
183
184
185
186
        }

        private static IEnumerable<string> SplitCommands(string path)
        {
187
            var commandStart = 0;
davescriven's avatar
davescriven committed
188

189
            for (var i = 0; i < path.Length; i++)
davescriven's avatar
davescriven committed
190
            {
191
                string command;
davescriven's avatar
davescriven committed
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
                if (char.IsLetter(path[i]))
                {
                    command = path.Substring(commandStart, i - commandStart).Trim();
                    commandStart = i;

                    if (!string.IsNullOrEmpty(command))
                        yield return command;

                    if (path.Length == i + 1)
                        yield return path[i].ToString();
                }
                else if (path.Length == i + 1)
                {
                    command = path.Substring(commandStart, i - commandStart + 1).Trim();

                    if (!string.IsNullOrEmpty(command))
                        yield return command;
                }
            }
        }

213
        private static IEnumerable<float> ParseCoordinates(string coords)
davescriven's avatar
davescriven committed
214
215
        {
            // TODO: Handle "1-1" (new PointF(1, -1);
216
217
            var parts = coords.Remove(0, 1).Replace("-", " -").Split(new[] {',', ' '},
                StringSplitOptions.RemoveEmptyEntries);
davescriven's avatar
davescriven committed
218

219
220
            for (var i = 0; i < parts.Length; i ++)
                yield return float.Parse(parts[i], NumberStyles.Float, CultureInfo.InvariantCulture);
davescriven's avatar
davescriven committed
221
222
        }

223
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
davescriven's avatar
davescriven committed
224
225
        {
            if (value is string)
226
                return Parse((string) value);
davescriven's avatar
davescriven committed
227
228
229
230
231

            return base.ConvertFrom(context, culture, value);
        }
    }
}