summaryrefslogtreecommitdiff
path: root/src/SMAPI/Framework/Serialisation/Converters
diff options
context:
space:
mode:
authorJesse Plamondon-Willard <github@jplamondonw.com>2018-01-20 21:29:47 -0500
committerJesse Plamondon-Willard <github@jplamondonw.com>2018-01-20 21:29:47 -0500
commit894fd25a18cd5ddf31a905860aca95c438894efd (patch)
tree186d873b91e0b1bee2927aeef96b6513710af497 /src/SMAPI/Framework/Serialisation/Converters
parent9636d5b3aac99459e5933bc4fa6ddb8ca84917af (diff)
downloadSMAPI-894fd25a18cd5ddf31a905860aca95c438894efd.tar.gz
SMAPI-894fd25a18cd5ddf31a905860aca95c438894efd.tar.bz2
SMAPI-894fd25a18cd5ddf31a905860aca95c438894efd.zip
move converters into namespace
Diffstat (limited to 'src/SMAPI/Framework/Serialisation/Converters')
-rw-r--r--src/SMAPI/Framework/Serialisation/Converters/ColorConverter.cs46
-rw-r--r--src/SMAPI/Framework/Serialisation/Converters/PointConverter.cs42
-rw-r--r--src/SMAPI/Framework/Serialisation/Converters/RectangleConverter.cs51
-rw-r--r--src/SMAPI/Framework/Serialisation/Converters/SFieldConverter.cs121
-rw-r--r--src/SMAPI/Framework/Serialisation/Converters/StringEnumConverter.cs22
5 files changed, 282 insertions, 0 deletions
diff --git a/src/SMAPI/Framework/Serialisation/Converters/ColorConverter.cs b/src/SMAPI/Framework/Serialisation/Converters/ColorConverter.cs
new file mode 100644
index 00000000..7f830a0e
--- /dev/null
+++ b/src/SMAPI/Framework/Serialisation/Converters/ColorConverter.cs
@@ -0,0 +1,46 @@
+using System;
+using Microsoft.Xna.Framework;
+using Newtonsoft.Json.Linq;
+using StardewModdingAPI.Framework.Exceptions;
+
+namespace StardewModdingAPI.Framework.Serialisation.Converters
+{
+ /// <summary>Handles deserialisation of <see cref="Color"/> for crossplatform compatibility.</summary>
+ /// <remarks>
+ /// - Linux/Mac format: { "B": 76, "G": 51, "R": 25, "A": 102 }
+ /// - Windows format: "26, 51, 76, 102"
+ /// </remarks>
+ internal class ColorConverter : SimpleReadOnlyConverter<Color>
+ {
+ /*********
+ ** Protected methods
+ *********/
+ /// <summary>Read a JSON object.</summary>
+ /// <param name="obj">The JSON object to read.</param>
+ /// <param name="path">The path to the current JSON node.</param>
+ protected override Color ReadObject(JObject obj, string path)
+ {
+ int r = obj.Value<int>(nameof(Color.R));
+ int g = obj.Value<int>(nameof(Color.G));
+ int b = obj.Value<int>(nameof(Color.B));
+ int a = obj.Value<int>(nameof(Color.A));
+ return new Color(r, g, b, a);
+ }
+
+ /// <summary>Read a JSON string.</summary>
+ /// <param name="str">The JSON string value.</param>
+ /// <param name="path">The path to the current JSON node.</param>
+ protected override Color ReadString(string str, string path)
+ {
+ string[] parts = str.Split(',');
+ if (parts.Length != 4)
+ throw new SParseException($"Can't parse {typeof(Color).Name} from invalid value '{str}' (path: {path}).");
+
+ int r = Convert.ToInt32(parts[0]);
+ int g = Convert.ToInt32(parts[1]);
+ int b = Convert.ToInt32(parts[2]);
+ int a = Convert.ToInt32(parts[3]);
+ return new Color(r, g, b, a);
+ }
+ }
+}
diff --git a/src/SMAPI/Framework/Serialisation/Converters/PointConverter.cs b/src/SMAPI/Framework/Serialisation/Converters/PointConverter.cs
new file mode 100644
index 00000000..87d0ff34
--- /dev/null
+++ b/src/SMAPI/Framework/Serialisation/Converters/PointConverter.cs
@@ -0,0 +1,42 @@
+using System;
+using Microsoft.Xna.Framework;
+using Newtonsoft.Json.Linq;
+using StardewModdingAPI.Framework.Exceptions;
+
+namespace StardewModdingAPI.Framework.Serialisation.Converters
+{
+ /// <summary>Handles deserialisation of <see cref="PointConverter"/> for crossplatform compatibility.</summary>
+ /// <remarks>
+ /// - Linux/Mac format: { "X": 1, "Y": 2 }
+ /// - Windows format: "1, 2"
+ /// </remarks>
+ internal class PointConverter : SimpleReadOnlyConverter<Point>
+ {
+ /*********
+ ** Protected methods
+ *********/
+ /// <summary>Read a JSON object.</summary>
+ /// <param name="obj">The JSON object to read.</param>
+ /// <param name="path">The path to the current JSON node.</param>
+ protected override Point ReadObject(JObject obj, string path)
+ {
+ int x = obj.Value<int>(nameof(Point.X));
+ int y = obj.Value<int>(nameof(Point.Y));
+ return new Point(x, y);
+ }
+
+ /// <summary>Read a JSON string.</summary>
+ /// <param name="str">The JSON string value.</param>
+ /// <param name="path">The path to the current JSON node.</param>
+ protected override Point ReadString(string str, string path)
+ {
+ string[] parts = str.Split(',');
+ if (parts.Length != 2)
+ throw new SParseException($"Can't parse {typeof(Point).Name} from invalid value '{str}' (path: {path}).");
+
+ int x = Convert.ToInt32(parts[0]);
+ int y = Convert.ToInt32(parts[1]);
+ return new Point(x, y);
+ }
+ }
+}
diff --git a/src/SMAPI/Framework/Serialisation/Converters/RectangleConverter.cs b/src/SMAPI/Framework/Serialisation/Converters/RectangleConverter.cs
new file mode 100644
index 00000000..7cf912a7
--- /dev/null
+++ b/src/SMAPI/Framework/Serialisation/Converters/RectangleConverter.cs
@@ -0,0 +1,51 @@
+using System;
+using System.Text.RegularExpressions;
+using Microsoft.Xna.Framework;
+using Newtonsoft.Json.Linq;
+using StardewModdingAPI.Framework.Exceptions;
+
+namespace StardewModdingAPI.Framework.Serialisation.Converters
+{
+ /// <summary>Handles deserialisation of <see cref="Rectangle"/> for crossplatform compatibility.</summary>
+ /// <remarks>
+ /// - Linux/Mac format: { "X": 1, "Y": 2, "Width": 3, "Height": 4 }
+ /// - Windows format: "{X:1 Y:2 Width:3 Height:4}"
+ /// </remarks>
+ internal class RectangleConverter : SimpleReadOnlyConverter<Rectangle>
+ {
+ /*********
+ ** Protected methods
+ *********/
+ /// <summary>Read a JSON object.</summary>
+ /// <param name="obj">The JSON object to read.</param>
+ /// <param name="path">The path to the current JSON node.</param>
+ protected override Rectangle ReadObject(JObject obj, string path)
+ {
+ int x = obj.Value<int>(nameof(Rectangle.X));
+ int y = obj.Value<int>(nameof(Rectangle.Y));
+ int width = obj.Value<int>(nameof(Rectangle.Width));
+ int height = obj.Value<int>(nameof(Rectangle.Height));
+ return new Rectangle(x, y, width, height);
+ }
+
+ /// <summary>Read a JSON string.</summary>
+ /// <param name="str">The JSON string value.</param>
+ /// <param name="path">The path to the current JSON node.</param>
+ protected override Rectangle ReadString(string str, string path)
+ {
+ if (string.IsNullOrWhiteSpace(str))
+ return Rectangle.Empty;
+
+ var match = Regex.Match(str, @"^\{X:(?<x>\d+) Y:(?<y>\d+) Width:(?<width>\d+) Height:(?<height>\d+)\}$");
+ if (!match.Success)
+ throw new SParseException($"Can't parse {typeof(Rectangle).Name} from invalid value '{str}' (path: {path}).");
+
+ int x = Convert.ToInt32(match.Groups["x"].Value);
+ int y = Convert.ToInt32(match.Groups["y"].Value);
+ int width = Convert.ToInt32(match.Groups["width"].Value);
+ int height = Convert.ToInt32(match.Groups["height"].Value);
+
+ return new Rectangle(x, y, width, height);
+ }
+ }
+}
diff --git a/src/SMAPI/Framework/Serialisation/Converters/SFieldConverter.cs b/src/SMAPI/Framework/Serialisation/Converters/SFieldConverter.cs
new file mode 100644
index 00000000..69353491
--- /dev/null
+++ b/src/SMAPI/Framework/Serialisation/Converters/SFieldConverter.cs
@@ -0,0 +1,121 @@
+using System;
+using System.Collections.Generic;
+using Newtonsoft.Json;
+using Newtonsoft.Json.Linq;
+using StardewModdingAPI.Framework.Exceptions;
+using StardewModdingAPI.Framework.Models;
+
+namespace StardewModdingAPI.Framework.Serialisation.Converters
+{
+ /// <summary>Overrides how SMAPI reads and writes <see cref="ISemanticVersion"/> and <see cref="IManifestDependency"/> fields.</summary>
+ internal class SFieldConverter : JsonConverter
+ {
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>Whether this converter can write JSON.</summary>
+ public override bool CanWrite => false;
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Get whether this instance can convert the specified object type.</summary>
+ /// <param name="objectType">The object type.</param>
+ public override bool CanConvert(Type objectType)
+ {
+ return
+ objectType == typeof(ISemanticVersion)
+ || objectType == typeof(IManifestDependency[])
+ || objectType == typeof(ModDataID)
+ || objectType == typeof(ModCompatibility[]);
+ }
+
+ /// <summary>Reads the JSON representation of the object.</summary>
+ /// <param name="reader">The JSON reader.</param>
+ /// <param name="objectType">The object type.</param>
+ /// <param name="existingValue">The object being read.</param>
+ /// <param name="serializer">The calling serializer.</param>
+ public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
+ {
+ // semantic version
+ if (objectType == typeof(ISemanticVersion))
+ {
+ JToken token = JToken.Load(reader);
+ switch (token.Type)
+ {
+ case JTokenType.Object:
+ {
+ JObject obj = (JObject)token;
+ int major = obj.Value<int>(nameof(ISemanticVersion.MajorVersion));
+ int minor = obj.Value<int>(nameof(ISemanticVersion.MinorVersion));
+ int patch = obj.Value<int>(nameof(ISemanticVersion.PatchVersion));
+ string build = obj.Value<string>(nameof(ISemanticVersion.Build));
+ return new LegacyManifestVersion(major, minor, patch, build);
+ }
+
+ case JTokenType.String:
+ {
+ string str = token.Value<string>();
+ if (string.IsNullOrWhiteSpace(str))
+ return null;
+ if (!SemanticVersion.TryParse(str, out ISemanticVersion version))
+ throw new SParseException($"Can't parse semantic version from invalid value '{str}', should be formatted like 1.2, 1.2.30, or 1.2.30-beta.");
+ return version;
+ }
+
+ default:
+ throw new SParseException($"Can't parse semantic version from {token.Type}, must be an object or string.");
+ }
+ }
+
+ // manifest dependencies
+ if (objectType == typeof(IManifestDependency[]))
+ {
+ List<IManifestDependency> result = new List<IManifestDependency>();
+ foreach (JObject obj in JArray.Load(reader).Children<JObject>())
+ {
+ string uniqueID = obj.Value<string>(nameof(IManifestDependency.UniqueID));
+ string minVersion = obj.Value<string>(nameof(IManifestDependency.MinimumVersion));
+ bool required = obj.Value<bool?>(nameof(IManifestDependency.IsRequired)) ?? true;
+ result.Add(new ManifestDependency(uniqueID, minVersion, required));
+ }
+ return result.ToArray();
+ }
+
+ // mod data ID
+ if (objectType == typeof(ModDataID))
+ {
+ JToken token = JToken.Load(reader);
+ return new ModDataID(token.Value<string>());
+ }
+
+ // mod compatibility records
+ if (objectType == typeof(ModCompatibility[]))
+ {
+ List<ModCompatibility> result = new List<ModCompatibility>();
+ foreach (JProperty property in JObject.Load(reader).Properties())
+ {
+ string range = property.Name;
+ ModStatus status = (ModStatus)Enum.Parse(typeof(ModStatus), property.Value.Value<string>(nameof(ModCompatibility.Status)));
+ string reasonPhrase = property.Value.Value<string>(nameof(ModCompatibility.ReasonPhrase));
+
+ result.Add(new ModCompatibility(range, status, reasonPhrase));
+ }
+ return result.ToArray();
+ }
+
+ // unknown
+ throw new NotSupportedException($"Unknown type '{objectType?.FullName}'.");
+ }
+
+ /// <summary>Writes the JSON representation of the object.</summary>
+ /// <param name="writer">The JSON writer.</param>
+ /// <param name="value">The value.</param>
+ /// <param name="serializer">The calling serializer.</param>
+ public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
+ {
+ throw new InvalidOperationException("This converter does not write JSON.");
+ }
+ }
+}
diff --git a/src/SMAPI/Framework/Serialisation/Converters/StringEnumConverter.cs b/src/SMAPI/Framework/Serialisation/Converters/StringEnumConverter.cs
new file mode 100644
index 00000000..0a612c74
--- /dev/null
+++ b/src/SMAPI/Framework/Serialisation/Converters/StringEnumConverter.cs
@@ -0,0 +1,22 @@
+using System;
+using Newtonsoft.Json.Converters;
+
+namespace StardewModdingAPI.Framework.Serialisation.Converters
+{
+ /// <summary>A variant of <see cref="StringEnumConverter"/> which only converts a specified enum.</summary>
+ /// <typeparam name="T">The enum type.</typeparam>
+ internal class StringEnumConverter<T> : StringEnumConverter
+ {
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Get whether this instance can convert the specified object type.</summary>
+ /// <param name="type">The object type.</param>
+ public override bool CanConvert(Type type)
+ {
+ return
+ base.CanConvert(type)
+ && (Nullable.GetUnderlyingType(type) ?? type) == typeof(T);
+ }
+ }
+}