SvgPathBuilder.cs 22.9 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;
Tebjan Halm's avatar
Tebjan Halm committed
7
using System.Linq;
Tebjan Halm's avatar
Tebjan Halm committed
8
using System.Text.RegularExpressions;
9
10
11
using System.Threading;

using Svg.Pathing;
davescriven's avatar
davescriven committed
12
13
14

namespace Svg
{
Eric Domke's avatar
Eric Domke committed
15
16
17
18
19
20
21
22
    public static class PointFExtensions
    {
        public static string ToSvgString(this PointF p)
        {
            return p.X.ToString() + " " + p.Y.ToString();
        }
    }

23
    public class SvgPathBuilder : TypeConverter
davescriven's avatar
davescriven committed
24
    {
25
26
27
28
        /// <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
29
30
31
        public static SvgPathSegmentList Parse(string path)
        {
            if (string.IsNullOrEmpty(path))
32
            {
davescriven's avatar
davescriven committed
33
                throw new ArgumentNullException("path");
34
            }
davescriven's avatar
davescriven committed
35

36
            var segments = new SvgPathSegmentList();
davescriven's avatar
davescriven committed
37
38
39

            try
            {
40
41
42
                char command;
                bool isRelative;

43
                foreach (var commandSet in SplitCommands(path.TrimEnd(null)))
davescriven's avatar
davescriven committed
44
                {
45
46
                    command = commandSet[0];
                    isRelative = char.IsLower(command);
davescriven's avatar
davescriven committed
47
48
                    // http://www.w3.org/TR/SVG11/paths.html#PathDataGeneralInformation

Eric Domke's avatar
Eric Domke committed
49
                    CreatePathSegment(command, segments, new CoordinateParser(commandSet.Trim()), isRelative);
50
51
52
53
54
55
56
57
58
59
                }
            }
            catch (Exception exc)
            {
                Trace.TraceError("Error parsing path \"{0}\": {1}", path, exc.Message);
            }

            return segments;
        }

Eric Domke's avatar
Eric Domke committed
60
        private static void CreatePathSegment(char command, SvgPathSegmentList segments, CoordinateParser parser, bool isRelative)
61
        {
62

Eric Domke's avatar
Eric Domke committed
63
            var coords = new float[6];
64

Eric Domke's avatar
Eric Domke committed
65
66
67
68
69
70
71
72
            switch (command)
            {
                case 'm': // relative moveto
                case 'M': // moveto
                    if (parser.TryGetFloat(out coords[0]) && parser.TryGetFloat(out coords[1]))
                    {
                        segments.Add(new SvgMoveToSegment(ToAbsolute(coords[0], coords[1], segments, isRelative)));
                    }
73

Eric Domke's avatar
Eric Domke committed
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
                    while (parser.TryGetFloat(out coords[0]) && parser.TryGetFloat(out coords[1]))
                    {
                        segments.Add(new SvgLineSegment(segments.Last.End,
                            ToAbsolute(coords[0], coords[1], segments, isRelative)));
                    }
                    break;
                case 'a':
                case 'A':
                    bool size;
                    bool sweep;

                    while (parser.TryGetFloat(out coords[0]) && parser.TryGetFloat(out coords[1]) &&
                           parser.TryGetFloat(out coords[2]) && parser.TryGetBool(out size) &&
                           parser.TryGetBool(out sweep) && parser.TryGetFloat(out coords[3]) &&
                           parser.TryGetFloat(out coords[4]))
                    {
                        // A|a rx ry x-axis-rotation large-arc-flag sweep-flag x y
                        segments.Add(new SvgArcSegment(segments.Last.End, coords[0], coords[1], coords[2],
                            (size ? SvgArcSize.Large : SvgArcSize.Small), 
                            (sweep ? SvgArcSweep.Positive : SvgArcSweep.Negative), 
                            ToAbsolute(coords[3], coords[4], segments, isRelative)));
                    }
                    break;
                case 'l': // relative lineto
                case 'L': // lineto
                    while (parser.TryGetFloat(out coords[0]) && parser.TryGetFloat(out coords[1]))
                    {
                        segments.Add(new SvgLineSegment(segments.Last.End,
                            ToAbsolute(coords[0], coords[1], segments, isRelative)));
                    }
                    break;
                case 'H': // horizontal lineto
                case 'h': // relative horizontal lineto
                    while (parser.TryGetFloat(out coords[0]))
                    {
                        segments.Add(new SvgLineSegment(segments.Last.End,
                            ToAbsolute(coords[0], segments.Last.End.Y, segments, isRelative, false)));
                    }
                    break;
                case 'V': // vertical lineto
                case 'v': // relative vertical lineto
                    while (parser.TryGetFloat(out coords[0]))
                    {
                        segments.Add(new SvgLineSegment(segments.Last.End,
                            ToAbsolute(segments.Last.End.X, coords[0], segments, false, isRelative)));
                    }
                    break;
                case 'Q': // curveto
                case 'q': // relative curveto
                    while (parser.TryGetFloat(out coords[0]) && parser.TryGetFloat(out coords[1]) &&
                           parser.TryGetFloat(out coords[2]) && parser.TryGetFloat(out coords[3]))
                    {
                        segments.Add(new SvgQuadraticCurveSegment(segments.Last.End,
                            ToAbsolute(coords[0], coords[1], segments, isRelative),
                            ToAbsolute(coords[2], coords[3], segments, isRelative)));
                    }
                    break;
                case 'T': // shorthand/smooth curveto
                case 't': // relative shorthand/smooth curveto
                    while (parser.TryGetFloat(out coords[0]) && parser.TryGetFloat(out coords[1]))
                    {
                        var lastQuadCurve = segments.Last as SvgQuadraticCurveSegment;
davescriven's avatar
davescriven committed
136

Eric Domke's avatar
Eric Domke committed
137
138
139
                        var controlPoint = lastQuadCurve != null
                            ? Reflect(lastQuadCurve.ControlPoint, segments.Last.End)
                            : segments.Last.End;
davescriven's avatar
davescriven committed
140

Eric Domke's avatar
Eric Domke committed
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
                        segments.Add(new SvgQuadraticCurveSegment(segments.Last.End, controlPoint,
                            ToAbsolute(coords[0], coords[1], segments, isRelative)));
                    }
                    break;
                case 'C': // curveto
                case 'c': // relative curveto
                    while (parser.TryGetFloat(out coords[0]) && parser.TryGetFloat(out coords[1]) &&
                           parser.TryGetFloat(out coords[2]) && parser.TryGetFloat(out coords[3]) &&
                           parser.TryGetFloat(out coords[4]) && parser.TryGetFloat(out coords[5]))
                    {
                        segments.Add(new SvgCubicCurveSegment(segments.Last.End,
                            ToAbsolute(coords[0], coords[1], segments, isRelative),
                            ToAbsolute(coords[2], coords[3], segments, isRelative),
                            ToAbsolute(coords[4], coords[5], segments, isRelative)));
                    }
                    break;
                case 'S': // shorthand/smooth curveto
                case 's': // relative shorthand/smooth curveto
                    while (parser.TryGetFloat(out coords[0]) && parser.TryGetFloat(out coords[1]) &&
                           parser.TryGetFloat(out coords[2]) && parser.TryGetFloat(out coords[3]))
                    {
                        var lastCubicCurve = segments.Last as SvgCubicCurveSegment;
163

Eric Domke's avatar
Eric Domke committed
164
165
166
                        var controlPoint = lastCubicCurve != null
                            ? Reflect(lastCubicCurve.SecondControlPoint, segments.Last.End)
                            : segments.Last.End;
167

Eric Domke's avatar
Eric Domke committed
168
169
170
                        segments.Add(new SvgCubicCurveSegment(segments.Last.End, controlPoint,
                            ToAbsolute(coords[0], coords[1], segments, isRelative),
                            ToAbsolute(coords[2], coords[3], segments, isRelative)));
davescriven's avatar
davescriven committed
171
                    }
Eric Domke's avatar
Eric Domke committed
172
173
174
175
176
177
                    break;
                case 'Z': // closepath
                case 'z': // relative closepath
                    segments.Add(new SvgClosePathSegment());
                    break;
            }
davescriven's avatar
davescriven committed
178
179
180
181
        }

        private static PointF Reflect(PointF point, PointF mirror)
        {
Matt Bowers's avatar
Matt Bowers committed
182
183
184
            float x, y, dx, dy;
            dx = Math.Abs(mirror.X - point.X);
            dy = Math.Abs(mirror.Y - point.Y);
davescriven's avatar
davescriven committed
185

Matt Bowers's avatar
Matt Bowers committed
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
            if (mirror.X >= point.X)
            {
                x = mirror.X + dx;
            }
            else
            {
                x = mirror.X - dx;
            }
            if (mirror.Y >= point.Y)
            {
                y = mirror.Y + dy;
            }
            else
            {
                y = mirror.Y - dy;
            }

            return new PointF(x, y);
davescriven's avatar
davescriven committed
204
205
        }

206
207
208
209
210
211
212
213
214
        /// <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
215
        {
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
            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;

236
                // if the last element is a SvgClosePathSegment the position of the previous element should be used because the position of SvgClosePathSegment is 0,0
Eric Domke's avatar
Eric Domke committed
237
                if (lastSegment is SvgClosePathSegment) lastSegment = segments.Reverse().OfType<SvgMoveToSegment>().First();
238

239
                if (isRelativeX)
240
                {
241
                    point.X += lastSegment.End.X;
242
                }
243
244

                if (isRelativeY)
245
                {
246
                    point.Y += lastSegment.End.Y;
247
                }
248
249
250
            }

            return point;
davescriven's avatar
davescriven committed
251
252
253
254
        }

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

257
            for (var i = 0; i < path.Length; i++)
davescriven's avatar
davescriven committed
258
            {
259
                string command;
Eric Domke's avatar
Eric Domke committed
260
                if (char.IsLetter(path[i]) && path[i] != 'e') //e is used in scientific notiation. but not svg path
davescriven's avatar
davescriven committed
261
262
263
264
265
                {
                    command = path.Substring(commandStart, i - commandStart).Trim();
                    commandStart = i;

                    if (!string.IsNullOrEmpty(command))
266
                    {
davescriven's avatar
davescriven committed
267
                        yield return command;
268
                    }
davescriven's avatar
davescriven committed
269
270

                    if (path.Length == i + 1)
271
                    {
davescriven's avatar
davescriven committed
272
                        yield return path[i].ToString();
273
                    }
davescriven's avatar
davescriven committed
274
275
276
277
278
279
                }
                else if (path.Length == i + 1)
                {
                    command = path.Substring(commandStart, i - commandStart + 1).Trim();

                    if (!string.IsNullOrEmpty(command))
280
                    {
davescriven's avatar
davescriven committed
281
                        yield return command;
282
                    }
davescriven's avatar
davescriven committed
283
284
285
286
                }
            }
        }

Eric Domke's avatar
Eric Domke committed
287
        
davescriven's avatar
davescriven committed
288

Eric Domke's avatar
Eric Domke committed
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
        //private static IEnumerable<float> ParseCoordinates(string coords)
        //{
        //    if (string.IsNullOrEmpty(coords) || coords.Length < 2) yield break;

        //    var pos = 0;
        //    var currState = NumState.separator;
        //    var newState = NumState.separator;

        //    for (int i = 1; i < coords.Length; i++)
        //    {
        //        switch (currState)
        //        {
        //            case NumState.separator:
        //                if (char.IsNumber(coords[i]))
        //                {
        //                    newState = NumState.integer;
        //                }
        //                else if (IsCoordSeparator(coords[i]))
        //                {
        //                    newState = NumState.separator;
        //                }
        //                else
        //                {
        //                    switch (coords[i])
        //                    {
        //                        case '.':
        //                            newState = NumState.decPlace;
        //                            break;
        //                        case '+':
        //                        case '-':
        //                            newState = NumState.prefix;
        //                            break;
        //                        default:
        //                            newState = NumState.invalid;
        //                            break;
        //                    }
        //                }
        //                break;
        //            case NumState.prefix:
        //                if (char.IsNumber(coords[i]))
        //                {
        //                    newState = NumState.integer;
        //                }
        //                else if (coords[i] == '.')
        //                {
        //                    newState = NumState.decPlace;
        //                }
        //                else
        //                {
        //                    newState = NumState.invalid;
        //                }
        //                break;
        //            case NumState.integer:
        //                if (char.IsNumber(coords[i]))
        //                {
        //                    newState = NumState.integer;
        //                }
        //                else if (IsCoordSeparator(coords[i]))
        //                {
        //                    newState = NumState.separator;
        //                }
        //                else
        //                {
        //                    switch (coords[i])
        //                    {
        //                        case '.':
        //                            newState = NumState.decPlace;
        //                            break;
        //                        case 'e':
        //                            newState = NumState.exponent;
        //                            break;
        //                        case '+':
        //                        case '-':
        //                            newState = NumState.prefix;
        //                            break;
        //                        default:
        //                            newState = NumState.invalid;
        //                            break;
        //                    }
        //                }
        //                break;
        //            case NumState.decPlace:
        //                if (char.IsNumber(coords[i]))
        //                {
        //                    newState = NumState.fraction;
        //                }
        //                else if (IsCoordSeparator(coords[i]))
        //                {
        //                    newState = NumState.separator;
        //                }
        //                else
        //                {
        //                    switch (coords[i])
        //                    {
        //                        case 'e':
        //                            newState = NumState.exponent;
        //                            break;
        //                        case '+':
        //                        case '-':
        //                            newState = NumState.prefix;
        //                            break;
        //                        default:
        //                            newState = NumState.invalid;
        //                            break;
        //                    }
        //                }
        //                break;
        //            case NumState.fraction:
        //                if (char.IsNumber(coords[i]))
        //                {
        //                    newState = NumState.fraction;
        //                }
        //                else if (IsCoordSeparator(coords[i]))
        //                {
        //                    newState = NumState.separator;
        //                }
        //                else
        //                {
        //                    switch (coords[i])
        //                    {
        //                        case '.':
        //                            newState = NumState.decPlace;
        //                            break;
        //                        case 'e':
        //                            newState = NumState.exponent;
        //                            break;
        //                        case '+':
        //                        case '-':
        //                            newState = NumState.prefix;
        //                            break;
        //                        default:
        //                            newState = NumState.invalid;
        //                            break;
        //                    }
        //                }
        //                break;
        //            case NumState.exponent:
        //                if (char.IsNumber(coords[i]))
        //                {
        //                    newState = NumState.expValue;
        //                }
        //                else if (IsCoordSeparator(coords[i]))
        //                {
        //                    newState = NumState.invalid;
        //                }
        //                else
        //                {
        //                    switch (coords[i])
        //                    {
        //                        case '+':
        //                        case '-':
        //                            newState = NumState.expPrefix;
        //                            break;
        //                        default:
        //                            newState = NumState.invalid;
        //                            break;
        //                    }
        //                }
        //                break;
        //            case NumState.expPrefix:
        //                if (char.IsNumber(coords[i]))
        //                {
        //                    newState = NumState.expValue;
        //                }
        //                else
        //                {
        //                    newState = NumState.invalid;
        //                }
        //                break;
        //            case NumState.expValue:
        //                if (char.IsNumber(coords[i]))
        //                {
        //                    newState = NumState.expValue;
        //                }
        //                else if (IsCoordSeparator(coords[i]))
        //                {
        //                    newState = NumState.separator;
        //                }
        //                else
        //                {
        //                    switch (coords[i])
        //                    {
        //                        case '.':
        //                            newState = NumState.decPlace;
        //                            break;
        //                        case '+':
        //                        case '-':
        //                            newState = NumState.prefix;
        //                            break;
        //                        default:
        //                            newState = NumState.invalid;
        //                            break;
        //                    }
        //                }
        //                break;
        //        }

        //        if (newState < currState)
        //        {
        //            yield return float.Parse(coords.Substring(pos, i - pos), NumberStyles.Float, CultureInfo.InvariantCulture);
        //            pos = i;
        //        }
        //        else if (newState != currState && currState == NumState.separator)
        //        {
        //            pos = i;
        //        }

        //        if (newState == NumState.invalid) yield break;
        //        currState = newState;
        //    }

        //    if (currState != NumState.separator)
        //    {
        //        yield return float.Parse(coords.Substring(pos, coords.Length - pos), NumberStyles.Float, CultureInfo.InvariantCulture);
        //    }
        //}

506
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
davescriven's avatar
davescriven committed
507
508
        {
            if (value is string)
509
            {
510
                return Parse((string)value);
511
            }
davescriven's avatar
davescriven committed
512
513

            return base.ConvertFrom(context, culture, value);
Tebjan Halm's avatar
Tebjan Halm committed
514
        }
Eric Domke's avatar
Eric Domke committed
515
516
517
518

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(string))
Tebjan Halm's avatar
Tebjan Halm committed
519
520
521
522
523
            {
                var paths = value as SvgPathSegmentList;

                if (paths != null)
                {
Eric Domke's avatar
Eric Domke committed
524
                    var curretCulture = CultureInfo.CurrentCulture;
525
526
527
528
529
530
531
532
533
534
                    try {
                        Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
                        var s = string.Join(" ", paths.Select(p => p.ToString()).ToArray());
                        return s;
                    }
                    finally
                    {
                        // Make sure to set back the old culture even an error occurred.
                        Thread.CurrentThread.CurrentCulture = curretCulture;
                    }
Tebjan Halm's avatar
Tebjan Halm committed
535
536
537
                }
            }

Eric Domke's avatar
Eric Domke committed
538
539
540
541
            return base.ConvertTo(context, culture, value, destinationType);
        }

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
Tebjan Halm's avatar
Tebjan Halm committed
542
543
544
545
546
547
548
        {
            if (destinationType == typeof(string))
            {
                return true;
            }

            return base.CanConvertTo(context, destinationType);
davescriven's avatar
davescriven committed
549
550
551
        }
    }
}