using System;
using System.Text.RegularExpressions;
using Microsoft.Xna.Framework;
using Newtonsoft.Json.Linq;
using StardewModdingAPI.Toolkit.Serialization;
using StardewModdingAPI.Toolkit.Serialization.Converters;
namespace StardewModdingAPI.Framework.Serialization
{
/// Handles deserialization of for crossplatform compatibility.
///
/// - Linux/Mac format: { "X": 1, "Y": 2, "Width": 3, "Height": 4 }
/// - Windows format: "{X:1 Y:2 Width:3 Height:4}"
///
internal class RectangleConverter : SimpleReadOnlyConverter
{
/*********
** Protected methods
*********/
/// Read a JSON object.
/// The JSON object to read.
/// The path to the current JSON node.
protected override Rectangle ReadObject(JObject obj, string path)
{
int x = obj.ValueIgnoreCase(nameof(Rectangle.X));
int y = obj.ValueIgnoreCase(nameof(Rectangle.Y));
int width = obj.ValueIgnoreCase(nameof(Rectangle.Width));
int height = obj.ValueIgnoreCase(nameof(Rectangle.Height));
return new Rectangle(x, y, width, height);
}
/// Read a JSON string.
/// The JSON string value.
/// The path to the current JSON node.
protected override Rectangle ReadString(string str, string path)
{
if (string.IsNullOrWhiteSpace(str))
return Rectangle.Empty;
var match = Regex.Match(str, @"^\{X:(?\d+) Y:(?\d+) Width:(?\d+) Height:(?\d+)\}$", RegexOptions.IgnoreCase);
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);
}
}
}