using System.Text.Json.Nodes;
namespace XFEWorkflow.Abstractions;
/// Physical pixels relative to the Windows virtual desktop; X and Y may be negative.
public readonly record struct ScreenRegion(int X, int Y, int Width, int Height)
{
public const long MaximumPixels = 40_000_000;
public long Right => (long)X + Width;
public long Bottom => (long)Y + Height;
public int CenterX => checked(X + Width / 2);
public int CenterY => checked(Y + Height / 2);
public JsonObject ToJson() => new() { ["x"] = X, ["y"] = Y, ["width"] = Width, ["height"] = Height };
public ScreenRegion Validate()
{
if (Width <= 0 || Height <= 0 || (long)Width * Height > MaximumPixels || Right > int.MaxValue || Bottom > int.MaxValue)
throw new ArgumentException("区域宽高必须大于 0,且总像素不能超过 4000 万。");
return this;
}
public void RequireInside(ScreenRegion bounds)
{
Validate();
if (X < bounds.X || Y < bounds.Y || Right > bounds.Right || Bottom > bounds.Bottom)
throw new ArgumentException("识别区域超出屏幕或图像范围,请重新框选。");
}
public static ScreenRegion Parse(JsonNode value)
{
if (value is not JsonObject obj) throw new ArgumentException("区域需要 x、y、width、height 对象。");
return new ScreenRegion(ReadInteger(obj, "x"), ReadInteger(obj, "y"), ReadInteger(obj, "width"), ReadInteger(obj, "height")).Validate();
}
public static int ReadInteger(JsonObject obj, string name)
{
if (obj[name] is JsonValue integer && integer.TryGetValue(out var result)) return result;
if (obj[name] is JsonValue value && value.TryGetValue(out var number) && double.IsFinite(number) && number == Math.Truncate(number) && number is >= int.MinValue and <= int.MaxValue)
return (int)number;
throw new ArgumentException(name + " 必须是整数。");
}
public static ScreenRegion FromDrag(double startX, double startY, double endX, double endY, ScreenRegion bounds, double scale = 1)
{
if (!double.IsFinite(scale) || scale <= 0 || new[] { startX, startY, endX, endY }.Any(v => !double.IsFinite(v)))
throw new ArgumentException("框选坐标或缩放比例无效。");
var left = (int)Math.Clamp(Math.Floor(Math.Min(startX, endX) * scale), 0, bounds.Width);
var top = (int)Math.Clamp(Math.Floor(Math.Min(startY, endY) * scale), 0, bounds.Height);
var right = (int)Math.Clamp(Math.Ceiling(Math.Max(startX, endX) * scale), 0, bounds.Width);
var bottom = (int)Math.Clamp(Math.Ceiling(Math.Max(startY, endY) * scale), 0, bounds.Height);
return new ScreenRegion(checked(bounds.X + left), checked(bounds.Y + top), right - left, bottom - top);
}
}