-
Notifications
You must be signed in to change notification settings - Fork 133
/
WpfRendererObject.cs
668 lines (546 loc) · 22 KB
/
WpfRendererObject.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
using System;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Media;
using SharpVectors.Dom;
using SharpVectors.Dom.Svg;
namespace SharpVectors.Renderers.Wpf
{
public abstract class WpfRendererObject : DependencyObject, IDisposable
{
#region Private Fields
private static readonly Regex _regFix = new Regex(@"[^[0-9a-zA-Z]]*");
private static readonly Regex _regExCaps = new Regex(@"(?<=[A-Z])(?=[A-Z][a-z]) |
(?<=[^A-Z])(?=[A-Z]) | (?<=[A-Za-z])(?=[^A-Za-z])", RegexOptions.IgnorePatternWhitespace);
#endregion
#region Protected Fields
protected bool _isDisposed; // To detect redundant calls
protected WpfDrawingContext _context;
// TODO-PAUL: Consider the possibility of providing this as option!
protected bool _flattenClosedPath; // Experiental options
protected double _flattenTolerance;
protected ToleranceType _flattenToleranceType;
#endregion
#region Constructors and Destructor
protected WpfRendererObject()
{
_flattenClosedPath = false;
_flattenTolerance = 0.0022;
_flattenToleranceType = ToleranceType.Relative;
}
protected WpfRendererObject(WpfDrawingContext context)
: this()
{
_context = context;
}
// TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
~WpfRendererObject()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
this.Dispose(false);
}
#endregion
#region Public Properties
public bool IsDisposed
{
get {
return _isDisposed;
}
}
public virtual WpfDrawingContext Context
{
get {
return _context;
}
}
public virtual bool IsInitialized
{
get {
return (_context != null);
}
}
#endregion
#region Public Methods
public static bool IsNullOrIdentity(Transform transform)
{
return (transform == null || transform.Value.IsIdentity);
}
public static bool SplitByCaps(string input, out string output)
{
output = input;
if (string.IsNullOrWhiteSpace(input))
{
return false;
}
output = _regExCaps.Replace(input, " ");
return output.Length > input.Length;
}
public static string GetElementName(SvgElement element, WpfDrawingContext context = null)
{
if (element == null)
{
return string.Empty;
}
if (context != null && context.IDVisitor != null)
{
return context.IDVisitor.Visit(element, context);
}
string elementId = element.Id;
if (string.IsNullOrWhiteSpace(elementId))
{
return string.Empty;
}
elementId = elementId.Trim();
if (IsValidIdentifier(elementId))
{
return elementId;
}
return _regFix.Replace(elementId, "_");
}
public static string GetElementClassName(SvgElement element, WpfDrawingContext context = null)
{
if (element == null)
{
return string.Empty;
}
if (context != null && context.ClassVisitor != null)
{
return context.ClassVisitor.Visit(element, context);
}
string className = (element as ISvgStylable)?.ClassName?.BaseVal?.Trim();
return string.IsNullOrWhiteSpace(className) ? string.Empty : className;
}
public static bool IsValidIdentifier(string identifier)
{
if (string.IsNullOrWhiteSpace(identifier))
{
return false;
}
if (!IsIdentifierStart(identifier[0]))
{
return false;
}
for (int i = 1; i < identifier.Length; i++)
{
if (!IsIdentifierPart(identifier[i]))
{
return false;
}
}
return true;
}
public static bool IsIdentifierStart(char c)
{
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || char.IsLetter(c);
}
public static bool IsIdentifierPart(char c)
{
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
|| c == '_' || (c >= '0' && c <= '9') || char.IsLetter(c);
}
public static Transform Combine(Transform first, Transform second,
bool groupedFormat, bool checkEquality = true)
{
if (first == null && second == null)
{
return null;
}
if (first == null)
{
return second;
}
if (second == null)
{
return first;
}
if (first.Value.IsIdentity)
{
return second;
}
if (second.Value.IsIdentity)
{
return first;
}
if (checkEquality && Matrix.Equals(first.Value, second.Value))
{
return first;
}
if (groupedFormat)
{
TransformGroup transformGroup = new TransformGroup();
transformGroup.Children.Add(first);
transformGroup.Children.Add(second);
return transformGroup;
}
return new MatrixTransform(Matrix.Multiply(first.Value, second.Value));
}
#endregion
#region Geometry Methods
public Geometry CreateGeometry(ISvgElement element, bool optimizePath)
{
if (element == null || element.RenderingHint != SvgRenderingHint.Shape)
{
return null;
}
try
{
string localName = element.LocalName;
switch (localName)
{
case SvgConstants.TagEllipse:
return CreateGeometry((SvgEllipseElement)element);
case SvgConstants.TagRect:
return CreateGeometry((SvgRectElement)element);
case SvgConstants.TagLine:
return CreateGeometry((SvgLineElement)element);
case SvgConstants.TagPath:
if (optimizePath)
{
return CreateGeometryEx((SvgPathElement)element);
}
return CreateGeometry((SvgPathElement)element);
case SvgConstants.TagCircle:
return CreateGeometry((SvgCircleElement)element);
case SvgConstants.TagPolyline:
return CreateGeometry((SvgPolylineElement)element);
case SvgConstants.TagPolygon:
return CreateGeometry((SvgPolygonElement)element);
}
}
catch (Exception ex)
{
Trace.TraceError(ex.ToString());
return null;
}
return null;
}
#region SvgEllipseElement Geometry
public Geometry CreateGeometry(SvgEllipseElement element)
{
double _cx = Math.Round(element.Cx.AnimVal.Value, 4);
double _cy = Math.Round(element.Cy.AnimVal.Value, 4);
double _rx = Math.Round(element.Rx.AnimVal.Value, 4);
double _ry = Math.Round(element.Ry.AnimVal.Value, 4);
// New in SVG 2. The auto value for rx and ry was added to allow consistent parsing of these properties for both ellipses and rectangles.
// Previously, if either rx or ry was unspecified, the ellipse would not render.
double r = Math.Max(_rx, _ry);
if (_rx <= 0 || _ry <= 0)
{
if (r <= 0)
{
return null;
}
else
{
if (_rx <= 0 && !element.HasAttribute("rx"))
{
_rx = r;
}
else if (_ry <= 0 && !element.HasAttribute("ry"))
{
_ry = r;
}
}
if (_rx <= 0 || _ry <= 0)
{
return null;
}
}
EllipseGeometry geometry = new EllipseGeometry(new Point(_cx, _cy), _rx, _ry);
return geometry;
}
#endregion
#region SvgRectElement Geometry
public Geometry CreateGeometry(SvgRectElement element)
{
double dx = Math.Round(element.X.AnimVal.Value, 4);
double dy = Math.Round(element.Y.AnimVal.Value, 4);
double width = Math.Round(element.Width.AnimVal.Value, 4);
double height = Math.Round(element.Height.AnimVal.Value, 4);
double rx = Math.Round(element.Rx.AnimVal.Value, 4);
double ry = Math.Round(element.Ry.AnimVal.Value, 4);
if (width <= 0 || height <= 0)
{
return null;
}
if (rx <= 0 && ry > 0)
{
rx = ry;
}
else if (rx > 0 && ry <= 0)
{
ry = rx;
}
return new RectangleGeometry(new Rect(dx, dy, width, height), rx, ry);
}
#endregion
#region SvgLineElement Geometry
public Geometry CreateGeometry(SvgLineElement element)
{
return new LineGeometry(new Point(Math.Round(element.X1.AnimVal.Value, 4),
Math.Round(element.Y1.AnimVal.Value, 4)),
new Point(Math.Round(element.X2.AnimVal.Value, 4), Math.Round(element.Y2.AnimVal.Value, 4)));
}
#endregion
#region SvgPathElement Geometry
public Geometry CreateGeometryEx(SvgPathElement element)
{
PathGeometry geometry = new PathGeometry();
string pathScript = element.PathScript;
if (string.IsNullOrWhiteSpace(pathScript))
{
return geometry;
}
var comparer = StringComparison.OrdinalIgnoreCase;
string fillRule = element.GetPropertyValue("fill-rule");
string clipRule = element.GetAttribute("clip-rule");
if (!string.IsNullOrWhiteSpace(clipRule) && string.Equals(clipRule, "evenodd", comparer)
|| string.Equals(clipRule, CssConstants.ValNonzero, comparer))
{
fillRule = clipRule;
}
if (string.Equals(fillRule, "evenodd", comparer))
geometry.FillRule = FillRule.EvenOdd;
else if (string.Equals(fillRule, CssConstants.ValNonzero, comparer))
geometry.FillRule = FillRule.Nonzero;
try
{
geometry.Figures = PathFigureCollection.Parse(pathScript);
if (_flattenClosedPath && element.IsClosed &&
geometry.MayHaveCurves() == element.MayHaveCurves)
{
int closedCount = 0;
foreach (var figure in geometry.Figures)
{
if (figure.IsClosed)
{
closedCount++;
}
}
if (geometry.Figures.Count == closedCount)
{
return geometry.GetFlattenedPathGeometry(_flattenTolerance, _flattenToleranceType);
}
}
return geometry;
}
catch (FormatException ex)
{
Trace.TraceError(ex.GetType().Name + ": " + ex.Message);
//return null;
return CreateGeometry(element);
}
}
public Geometry CreateGeometry(SvgPathElement element)
{
PathGeometry geometry = new PathGeometry();
var comparer = StringComparison.OrdinalIgnoreCase;
string fillRule = element.GetPropertyValue("fill-rule");
string clipRule = element.GetAttribute("clip-rule");
if (!string.IsNullOrWhiteSpace(clipRule) && string.Equals(clipRule, "evenodd", comparer)
|| string.Equals(clipRule, CssConstants.ValNonzero, comparer))
{
fillRule = clipRule;
}
if (string.Equals(fillRule, "evenodd", comparer))
geometry.FillRule = FillRule.EvenOdd;
else if (string.Equals(fillRule, CssConstants.ValNonzero, comparer))
geometry.FillRule = FillRule.Nonzero;
SvgPointF initPoint = new SvgPointF(0, 0);
SvgPointF lastPoint = new SvgPointF(0, 0);
SvgPointF ptXY = new SvgPointF(0, 0);
SvgPathSeg segment = null;
SvgPathSegMoveto pathMoveTo = null;
SvgPathSegLineto pathLineTo = null;
SvgPathSegCurveto pathCurveTo = null;
SvgPathSegArc pathArc = null;
SvgPathSegList segments = element.PathSegList;
int numSegs = segments.NumberOfItems;
if (numSegs == 0)
{
return geometry;
}
PathFigure pathFigure = null;
for (int i = 0; i < numSegs; i++)
{
segment = segments.GetItem(i);
switch (segment.PathType)
{
case SvgPathType.MoveTo: //if (DynamicCast.Cast(segment, out pathMoveTo))
pathMoveTo = (SvgPathSegMoveto)segment;
if (pathFigure != null)
{
pathFigure.IsClosed = false;
pathFigure.IsFilled = true;
geometry.Figures.Add(pathFigure);
pathFigure = null;
}
lastPoint = initPoint = pathMoveTo.AbsXY;
pathFigure = new PathFigure();
pathFigure.StartPoint = new Point(initPoint.ValueX, initPoint.ValueY);
break;
case SvgPathType.LineTo: //else if (DynamicCast.Cast(segment, out pathLineTo))
pathLineTo = (SvgPathSegLineto)segment;
ptXY = pathLineTo.AbsXY;
pathFigure.Segments.Add(new LineSegment(new Point(ptXY.ValueX, ptXY.ValueY), true));
lastPoint = ptXY;
break;
case SvgPathType.CurveTo: //else if (DynamicCast.Cast(segment, out pathCurveTo))
pathCurveTo = (SvgPathSegCurveto)segment;
SvgPointF xy = pathCurveTo.AbsXY;
SvgPointF x1y1 = pathCurveTo.CubicX1Y1;
SvgPointF x2y2 = pathCurveTo.CubicX2Y2;
pathFigure.Segments.Add(new BezierSegment(new Point(x1y1.ValueX, x1y1.ValueY),
new Point(x2y2.ValueX, x2y2.ValueY), new Point(xy.ValueX, xy.ValueY), true));
lastPoint = xy;
break;
case SvgPathType.ArcTo: //else if (DynamicCast.Cast(segment, out pathArc))
pathArc = (SvgPathSegArc)segment;
ptXY = pathArc.AbsXY;
if (lastPoint.Equals(ptXY))
{
// If the endpoints (x, y) and (x0, y0) are identical, then this
// is equivalent to omitting the elliptical arc segment entirely.
}
else if (pathArc.R1.Equals(0) || pathArc.R2.Equals(0))
{
// Ensure radii are valid
pathFigure.Segments.Add(new LineSegment(new Point(ptXY.ValueX, ptXY.ValueY), true));
}
else
{
CalculatedArcValues calcValues = pathArc.GetCalculatedArcValues();
pathFigure.Segments.Add(new ArcSegment(new Point(ptXY.ValueX, ptXY.ValueY),
new Size(pathArc.R1, pathArc.R2), pathArc.Angle, pathArc.LargeArcFlag,
pathArc.SweepFlag ? SweepDirection.Clockwise : SweepDirection.Counterclockwise,
true));
}
lastPoint = ptXY;
break;
case SvgPathType.Close://else if (segment is SvgPathSegClosePath)
if (pathFigure != null)
{
pathFigure.IsClosed = true;
pathFigure.IsFilled = true;
geometry.Figures.Add(pathFigure);
pathFigure = null;
}
lastPoint = initPoint;
break;
}
}
if (pathFigure != null)
{
pathFigure.IsClosed = false;
pathFigure.IsFilled = true;
geometry.Figures.Add(pathFigure);
}
return geometry;
}
#endregion
#region SvgCircleElement Geometry
public Geometry CreateGeometry(SvgCircleElement element)
{
double _cx = Math.Round(element.Cx.AnimVal.Value, 4);
double _cy = Math.Round(element.Cy.AnimVal.Value, 4);
double _r = Math.Round(element.R.AnimVal.Value, 4);
if (_r <= 0)
{
return null;
}
EllipseGeometry geometry = new EllipseGeometry(new Point(_cx, _cy), _r, _r);
return geometry;
}
#endregion
#region SvgPolylineElement Geometry
public Geometry CreateGeometry(SvgPolylineElement element)
{
ISvgPointList list = element.AnimatedPoints;
ulong nElems = list.NumberOfItems;
if (nElems == 0)
{
return null;
}
PointCollection points = new PointCollection((int)nElems);
for (uint i = 0; i < nElems; i++)
{
ISvgPoint point = list.GetItem(i);
points.Add(new Point(Math.Round(point.X, 4), Math.Round(point.Y, 4)));
}
PolyLineSegment polyline = new PolyLineSegment();
polyline.Points = points;
PathFigure polylineFigure = new PathFigure();
polylineFigure.StartPoint = points[0];
polylineFigure.IsClosed = false;
polylineFigure.IsFilled = true;
polylineFigure.Segments.Add(polyline);
PathGeometry geometry = new PathGeometry();
string fillRule = element.GetPropertyValue("fill-rule");
string clipRule = element.GetAttribute("clip-rule");
if (!string.IsNullOrWhiteSpace(clipRule) &&
string.Equals(clipRule, "evenodd") || string.Equals(clipRule, CssConstants.ValNonzero))
{
fillRule = clipRule;
}
if (fillRule == "evenodd")
geometry.FillRule = FillRule.EvenOdd;
else if (fillRule == CssConstants.ValNonzero)
geometry.FillRule = FillRule.Nonzero;
geometry.Figures.Add(polylineFigure);
return geometry;
}
#endregion
#region SvgPolygonElement Geometry
public Geometry CreateGeometry(SvgPolygonElement element)
{
ISvgPointList list = element.AnimatedPoints;
ulong nElems = list.NumberOfItems;
if (nElems < 3)
{
return null;
}
PointCollection points = new PointCollection((int)nElems);
for (uint i = 0; i < nElems; i++)
{
ISvgPoint point = list.GetItem(i);
points.Add(new Point(Math.Round(point.X, 4), Math.Round(point.Y, 4)));
}
PolyLineSegment polyline = new PolyLineSegment();
polyline.Points = points;
PathFigure polylineFigure = new PathFigure();
polylineFigure.StartPoint = points[0];
polylineFigure.IsClosed = true;
polylineFigure.IsFilled = true;
polylineFigure.Segments.Add(polyline);
PathGeometry geometry = new PathGeometry();
string fillRule = element.GetPropertyValue("fill-rule");
string clipRule = element.GetAttribute("clip-rule");
if (!string.IsNullOrWhiteSpace(clipRule) &&
string.Equals(clipRule, "evenodd") || string.Equals(clipRule, CssConstants.ValNonzero))
{
fillRule = clipRule;
}
if (fillRule == "evenodd")
geometry.FillRule = FillRule.EvenOdd;
else if (fillRule == CssConstants.ValNonzero)
geometry.FillRule = FillRule.Nonzero;
geometry.Figures.Add(polylineFigure);
return geometry;
}
#endregion
#endregion
#region IDisposable Members
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
_isDisposed = true;
}
#endregion
}
}