Skip to content

Commit

Permalink
Moving to C# 12
Browse files Browse the repository at this point in the history
  • Loading branch information
monoman committed Nov 15, 2023
1 parent 98d7df6 commit 2646edb
Show file tree
Hide file tree
Showing 17 changed files with 139 additions and 169 deletions.
2 changes: 1 addition & 1 deletion SvgGdiTest/SvgGdiTest.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<ProjectType>Local</ProjectType>
<ProductVersion>8.0.30319</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<LangVersion>10</LangVersion>
<LangVersion>12</LangVersion>
<ProjectGuid>{0C963EB6-C1B4-453D-B694-E81EC26D3AB9}</ProjectGuid>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
Expand Down
4 changes: 2 additions & 2 deletions SvgNet/Elements/SvgElement.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public class SvgElement {
/// <summary>
/// An ArrayList containing this element's children
/// </summary>
public ArrayList Children { get; protected set; } = new ArrayList();
public ArrayList Children { get; protected set; } = [];

public string Id {
get => (string)_atts["id"];
Expand Down Expand Up @@ -175,7 +175,7 @@ public virtual void WriteXmlElements(XmlDocument doc, XmlElement parent) {
_ = parent == null ? doc.AppendChild(me) : parent.AppendChild(me);
}

protected Hashtable _atts = new();
protected Hashtable _atts = [];
protected object FirstChild => Children[0];

protected T GetTypedAttribute<T>(string attributeName, Func<object, T> fromString) where T : new() {
Expand Down
5 changes: 2 additions & 3 deletions SvgNet/Extensions/StringExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@

namespace System;


public static class StringExtensions {
public static int ParseHex(this string s, int startIndex, int length = 1)
#if NET5_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER
Expand All @@ -17,7 +16,6 @@ public static int ParseHex(this string s, int startIndex, int length = 1)
=> int.Parse(s.Substring(startIndex, length), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
#endif


public static IPB IsPrefixedBy(this string s, string prefix)
=> !s.StartsWith(prefix, StringComparison.InvariantCulture)
? new IPB(false, null)
Expand All @@ -36,8 +34,9 @@ public static string SkipFirst(this string s)
=> s.Substring(1);
#endif

private static readonly char[] digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
public static bool TrySplitNumberAndSuffix(this string s, out string number, out string suffix) {
int i = s.LastIndexOfAny(new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }) + 1;
int i = s.LastIndexOfAny(digits) + 1;
suffix = number = null;
if (i == 0)
return false;
Expand Down
7 changes: 2 additions & 5 deletions SvgNet/ImplementedGraphics/GDIGraphics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,7 @@ namespace SvgNet;
/// <summary>
/// An IGraphics implementation that simply passes every call through to a GDI+ <c>Graphics</c> object.
/// </summary>
public sealed class GdiGraphics : IGraphics {

public GdiGraphics(Graphics g) => _g = g ?? throw new ArgumentNullException(nameof(g));

public sealed class GdiGraphics(Graphics g) : IGraphics {
public Region Clip { get => _g.Clip; set => _g.Clip = value; }
public RectangleF ClipBounds => _g.ClipBounds;
public CompositingMode CompositingMode { get => _g.CompositingMode; set => _g.CompositingMode = value; }
Expand Down Expand Up @@ -353,5 +350,5 @@ public SizeF MeasureString(string text, Font font, SizeF layoutArea, StringForma

public void TranslateTransform(float dx, float dy, MatrixOrder order) => _g.TranslateTransform(dx, dy, order);

private readonly Graphics _g;
private readonly Graphics _g = g ?? throw new ArgumentNullException(nameof(g));
}
28 changes: 7 additions & 21 deletions SvgNet/ImplementedGraphics/SVGGraphics.BitmapDrawer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,10 @@
namespace SvgNet;

public sealed partial class SvgGraphics {
private class BitmapDrawer {
public BitmapDrawer(SvgGroupElement g, float x, float y, float scaleX, float scaleY) {
_groupElement = g;
_x = x;
_y = y;
_scaleX = scaleX;
_scaleY = scaleY;
}

private readonly SvgGroupElement _groupElement;
private readonly float _x;
private readonly float _y;
private readonly float _scaleX;
private readonly float _scaleY;

private class BitmapDrawer(SvgGroupElement g, float x, float y, float scaleX, float scaleY) {
public SvgGroupElement DrawBitmapData(Bitmap b) {
for (int line = 0; line < b.Height; ++line) {
float scaledLine = _y + (line * _scaleY);
float scaledLine = y + (line * scaleY);
// Only draws the last 'set' of pixels when a new color is encountered or it's the last pixel in the line.
Color currentColor = GetPixelColor(b, line, 0);
int consecutive = 1;
Expand All @@ -48,19 +34,19 @@ public SvgGroupElement DrawBitmapData(Bitmap b) {
} catch { }
}
}
return _groupElement;
return g;
}

// This could be optimized in an unsafe version of the lib
private static Color GetPixelColor(Bitmap b, int y, int x) => b.GetPixel(x, y);

private void DrawPixel(float scaledLine, int col, int consecutive, Color color) =>
DrawImagePixel(_groupElement,
DrawImagePixel(g,
color,
_x + ((col - consecutive - 1) * _scaleX),
x + ((col - consecutive - 1) * scaleX),
scaledLine,
consecutive * _scaleX,
_scaleY);
consecutive * scaleX,
scaleY);
}
}

4 changes: 2 additions & 2 deletions SvgNet/ImplementedGraphics/SVGGraphics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -618,7 +618,7 @@ public void DrawLine(Pen pen, float x1, float y1, float x2, float y2) {
_cur.AddChild(lin);

DrawEndAnchors(pen, new PointF(x1, y1), new PointF(x2, y2));
} else DrawLines(pen, new PointF[] { new PointF(x1, y1), new PointF(x2, y2) });
} else DrawLines(pen, new PointF[] { new(x1, y1), new(x2, y2) });
}

/// <summary>
Expand Down Expand Up @@ -2234,7 +2234,7 @@ private static SvgPath HandleGraphicsPath(GraphicsPath path) {
/// </summary>
private sealed class MatrixStack : IDisposable {
public MatrixStack() {
_mx = new();
_mx = [];

//we need 2 identity matrices on the stack. This is because we do a resettransform()
//by pop dup (to set current xform to xform of enclosing group).
Expand Down
16 changes: 5 additions & 11 deletions SvgNet/MetafileTools/EmfTools.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,8 @@ protected EmfBinaryRecord() {
/// <summary>
/// Low-level EMF parser
/// </summary>
public class EmfReader : IDisposable {
public EmfReader(Stream stream) {
_stream = stream;
_reader = new BinaryReader(stream);
}

public bool IsEndOfFile => _stream.Length == _stream.Position;
public class EmfReader(Stream stream) : IDisposable {
public bool IsEndOfFile => stream.Length == stream.Position;

public void Dispose() {
if (_reader is not null) {
Expand All @@ -84,7 +79,7 @@ public IBinaryRecord Read() {
var rt = (EmfPlusRecordType)_reader.ReadUInt32();
uint recordSize = _reader.ReadUInt32();

EmfBinaryRecord record = new EmfUnknownRecord {
var record = new EmfUnknownRecord {
RecordType = rt,
RecordSize = recordSize
};
Expand All @@ -101,8 +96,7 @@ public IBinaryRecord Read() {
return record;
}

private readonly Stream _stream;
private BinaryReader _reader;
private BinaryReader _reader = new(stream);
}

public class EmfUnknownRecord : EmfBinaryRecord {
Expand All @@ -116,6 +110,6 @@ public override void Read(BinaryReader reader) {
Data = length > 0 ? reader.ReadBytes(length) : _emptyData;
}

private static readonly byte[] _emptyData = Array.Empty<byte>();
private static readonly byte[] _emptyData = [];
}

25 changes: 8 additions & 17 deletions SvgNet/MetafileTools/MetafileParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public void EnumerateMetafile(Stream emf,
_fillPolygon = fillPolygon;
_zero = destination;
_lineBuffer = new LineBuffer(unitSize);
_objects = new Dictionary<uint, ObjectHandle>();
_objects = [];
_brush = null;

using (var reader = new EmfTools.EmfReader(emf)) {
Expand Down Expand Up @@ -451,9 +451,7 @@ private void ProcessPolygon16(byte[] recordData) {

uint totalNumberOfPoints = _br.ReadUInt32();

int[] numberOfPoints = new int[1];
numberOfPoints[0] = (int)totalNumberOfPoints;

int[] numberOfPoints = [(int)totalNumberOfPoints];
InternalProcessPolyline16(1, totalNumberOfPoints, numberOfPoints, _br);

System.Diagnostics.Debug.Assert(_ms.Position == _ms.Length);
Expand Down Expand Up @@ -601,14 +599,7 @@ public void Dispose() {
_transform?.Dispose();
}

private class LineBuffer {
public LineBuffer(float unitSize) {
_points = new List<NormalizedPoint>();
_normalizedPoints = new List<NormalizedPoint>();
_visualPoints = new List<VisualPoint>();
_epsilonSquare = _unitSizeEpsilon * unitSize * _unitSizeEpsilon * unitSize;
}

private class LineBuffer(float unitSize) {
public bool IsEmpty => _points.Count == 0;

public void Add(PointF[] points, int offset, int count) {
Expand Down Expand Up @@ -668,14 +659,14 @@ public PointF[] GetPoints() {
result.Add(visualPoint.Point);
}

return result.ToArray();
return [.. result];
}

private const float _unitSizeEpsilon = 2.0f;
private readonly float _epsilonSquare;
private readonly List<NormalizedPoint> _normalizedPoints;
private readonly List<NormalizedPoint> _points;
private readonly List<VisualPoint> _visualPoints;
private readonly float _epsilonSquare = _unitSizeEpsilon * unitSize * _unitSizeEpsilon * unitSize;
private readonly List<NormalizedPoint> _normalizedPoints = [];
private readonly List<NormalizedPoint> _points = [];
private readonly List<VisualPoint> _visualPoints = [];

private static bool IsVisuallyIdentical(NormalizedPoint a, NormalizedPoint b) => a.VisualIndex == b.VisualIndex;

Expand Down
12 changes: 5 additions & 7 deletions SvgNet/SvgFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,8 @@ public static Hashtable BuildElementNameDictionary() {
Type[] ta = asm.GetExportedTypes();
foreach (Type t in ta) {
if (t.IsSubclassOf(typeof(SvgElement)) && !t.IsAbstract) {
ConstructorInfo ci = t.GetConstructor(Array.Empty<Type>());
if (ci == null)
throw new InvalidOperationException($"Type {t.Name} doesn't have the mandatory public parameterless constructor");
var e = (SvgElement)ci.Invoke(Array.Empty<object>());
ConstructorInfo ci = t.GetConstructor([]) ?? throw new InvalidOperationException($"Type {t.Name} doesn't have the mandatory public parameterless constructor");
var e = (SvgElement)ci.Invoke([]);
if (e.Name != "?" /* default name of abstract SvgElements */) {
dict[e.Name] = e.GetType();
}
Expand All @@ -45,7 +43,7 @@ public static Hashtable BuildElementNameDictionary() {
/// <param name="el"></param>
/// <returns></returns>
public static SvgElement CloneElement(SvgElement el) {
var clone = (SvgElement)el.GetType().GetConstructor(Array.Empty<Type>()).Invoke(Array.Empty<object>());
var clone = (SvgElement)el.GetType().GetConstructor([]).Invoke([]);

foreach (string key in el.Attributes.Keys) {
clone[key] = el[key].CloneIfPossible();
Expand Down Expand Up @@ -86,7 +84,7 @@ public static SvgElement LoadFromXML(XmlDocument doc, XmlElement el) {

var t = (Type)_elementNameDictionary[el.Name];

var e = (SvgElement)t.GetConstructor(Array.Empty<Type>()).Invoke(Array.Empty<object>());
var e = (SvgElement)t.GetConstructor([]).Invoke([]);

RecLoadFromXML(e, doc, el);

Expand Down Expand Up @@ -207,7 +205,7 @@ private static void RecLoadFromXML(SvgElement e, XmlDocument doc, XmlElement el)

SvgElement childSvg = t switch {
null => new SvgGenericElement(childXml.Name),
_ => (SvgElement)t.GetConstructor(Array.Empty<Type>()).Invoke(Array.Empty<object>()),
_ => (SvgElement)t.GetConstructor([]).Invoke([]),
};
e.AddChild(childSvg);

Expand Down
23 changes: 7 additions & 16 deletions SvgNet/Types/PathSeg.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,10 @@ namespace SvgNet.Types;
/// A segment in an Svg path. This is not a real SVG type; it is not in the SVG spec. It is provided for making paths
/// easier to specify and parse.
/// </summary>
public class PathSeg : ICloneable {
public float[] _data;
public SvgPathSegType _type;
public class PathSeg(SvgPathSegType type, bool abs, float[] data) : ICloneable {
public bool Abs { get; } = abs;

public PathSeg(SvgPathSegType t, bool a, float[] arr) {
_type = t;
Abs = a;
_data = arr;
}

public bool Abs { get; }

public string Char => _type switch {
public string Char => type switch {
SvgPathSegType.SVG_SEGTYPE_MOVETO => Abs ? "M" : "m",
SvgPathSegType.SVG_SEGTYPE_CLOSEPATH => "z",
SvgPathSegType.SVG_SEGTYPE_LINETO => Abs ? "L" : "l",
Expand All @@ -35,12 +26,12 @@ public PathSeg(SvgPathSegType t, bool a, float[] arr) {
SvgPathSegType.SVG_SEGTYPE_SMOOTHBEZIERTO => Abs ? "T" : "t",
SvgPathSegType.SVG_SEGTYPE_ARCTO => Abs ? "A" : "a",

_ => throw new SvgException("Invalid PathSeg type", _type.ToString()),
_ => throw new SvgException("Invalid PathSeg type", type.ToString()),
};

public float[] Data => _data;
public float[] Data => data;

public SvgPathSegType Type => _type;
public SvgPathSegType Type => type;

public object Clone() => new PathSeg(_type, Abs, (float[])_data.Clone());
public object Clone() => new PathSeg(type, Abs, (float[])data.Clone());
};
14 changes: 14 additions & 0 deletions SvgNet/Types/SvgHelpers.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/*
Copyright © 2003 RiskCare Ltd. All rights reserved.
Copyright © 2010 SvgNet & SvgGdi Bridge Project. All rights reserved.
Copyright © 2015-2023 Rafael Teixeira, Mojmír Němeček, Benjamin Peterson and Other Contributors
Original source code licensed with BSD-2-Clause spirit, treat it thus, see accompanied LICENSE for more
*/

namespace SvgNet;

internal static class SvgHelpers {

public static readonly char[] CommonSeparators = [',', ' ', '\t', '\r', '\n'];
}
4 changes: 2 additions & 2 deletions SvgNet/Types/SvgNumList.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public float this[int idx] {

public static float[] String2Floats(string s) {
try {
string[] sa = s.Split(new char[] { ',', ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
string[] sa = s.Split(SvgHelpers.CommonSeparators, StringSplitOptions.RemoveEmptyEntries);
var arr = new ArrayList();
foreach (string str in sa) if (!string.IsNullOrWhiteSpace(str)) _ = arr.Add(float.Parse(str.Trim(), CultureInfo.InvariantCulture));
return (float[])arr.ToArray(typeof(float));
Expand Down Expand Up @@ -59,5 +59,5 @@ public override string ToString() {
return builder.ToString();
}

private readonly ArrayList _pts = new();
private readonly ArrayList _pts = [];
}
4 changes: 2 additions & 2 deletions SvgNet/Types/SvgPath.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,15 @@ public object Clone() =>
/// </summary>
/// <param name="s"></param>
public void FromString(string s) {
string[] sa = s.Split(new char[] { ' ', ',', '\t', '\r', '\n' });
string[] sa = s.Split(SvgHelpers.CommonSeparators);

PathSeg ps;
int datasize = 0;
SvgPathSegType pt = SvgPathSegType.SVG_SEGTYPE_UNKNOWN;
bool abs = false;
int i = 0;
char segTypeChar;
_path = new ArrayList();
_path = [];

while (i < sa.Length) {
if (sa[i]?.Length == 0) {
Expand Down
2 changes: 1 addition & 1 deletion SvgNet/Types/SvgPoints.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,5 +60,5 @@ public override string ToString() {
return builder.ToString();
}

private readonly ArrayList _pts = new();
private readonly ArrayList _pts = [];
}
Loading

0 comments on commit 2646edb

Please sign in to comment.