96 lines
5.3 KiB
C#

using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Security.Cryptography;
using System.Text;
namespace PlotDirector.Companion.Protocol.Manuscript;
[DataContract]
public sealed class ChapterPictureAnchor
{
[DataMember] public int Offset { get; set; }
[DataMember] public int ShapeId { get; set; }
[DataMember] public int ShapeType { get; set; }
}
// Word positions and UTF-16 text units are different coordinates. These are
// measured paragraph spans, with explicit one-position, zero-text picture anchors.
public static class ChapterWordPositions
{
public const string Version = "native-picture-positions-v1";
public const int MaxFrameCharacters = 2 * 1024 * 1024;
public static int Span(ChapterParagraph paragraph) => paragraph.WordLength == 0 ? paragraph.Length : paragraph.WordLength;
public static void ValidateRows(ChapterParagraph[] rows)
{
if (rows.Length == 0 || rows.Length > ChapterFingerprint.MaxParagraphs || rows.Any(p => p == null || p.WordLength <= 0 || p.Length <= 0 || p.WordLength > ChapterFingerprint.MaxCharacters || WordParagraphIdentity.Normalise(p.NativeId) != p.NativeId || p.Outline < 1 || p.Outline > 10 || p.Anchors == null || p.Anchors.Length > 256 || p.WordLength - p.Length != p.Anchors.Length) || rows.Sum(p => (long)p.WordLength) > ChapterFingerprint.MaxCharacters)
throw new ArgumentException("Native Word spans require complete text lengths and explicit picture anchor evidence.");
if(rows.Sum(p=>(long)p.Anchors.Length)>4096)throw new ArgumentException("More than 4096 native picture anchors in one chapter exceeds the bounded position reader.");
var shapes = new HashSet<int>();
foreach (var row in rows)
{
var previous = -1;
foreach (var anchor in row.Anchors)
{
if (anchor == null || anchor.Offset <= previous || anchor.Offset >= row.WordLength || anchor.ShapeId <= 0 || !shapes.Add(anchor.ShapeId) || anchor.ShapeType is not (11 or 13))
throw new ArgumentException("Native picture anchors must be ordered, unique, in range and supported floating pictures.");
previous = anchor.Offset;
}
}
}
// Content/identity v1 remain unchanged. Geometry has its own digest so the
// existing text/identity checkpoints do not acquire different identities.
public static string Hash(ChapterParagraph[] rows)
{
ValidateRows(rows);
using var buffer = new MemoryStream();
using (var writer = new BinaryWriter(buffer, Encoding.UTF8, true))
{
writer.Write(Version); writer.Write(rows.Length);
foreach (var row in rows)
{
writer.Write(row.NativeId); writer.Write(row.Length); writer.Write(row.Outline); writer.Write(row.WordLength); writer.Write(row.Anchors.Length);
foreach (var anchor in row.Anchors) { writer.Write(anchor.Offset); writer.Write(anchor.ShapeId); writer.Write(anchor.ShapeType); }
}
}
using var sha = SHA256.Create();
return BitConverter.ToString(sha.ComputeHash(buffer.ToArray())).Replace("-", "");
}
public static void Validate(ChapterParagraph[] rows, int start, int end, string? hash)
{
if (rows == null || rows.Length == 0 || rows.Any(p => p == null || p.Anchors == null) || start < 0 || end <= start)
throw new ArgumentException("Incomplete native chapter positions.");
var physical = rows.Any(p => p.WordLength != 0 || p.Anchors.Length != 0);
if (physical ? string.IsNullOrEmpty(hash) || Hash(rows) != hash : !string.IsNullOrEmpty(hash))
throw new ArgumentException("Native Word position digest is missing or inconsistent.");
if (rows.Sum(p => (long)Span(p)) != (long)end - start)
throw new ArgumentException("Native paragraph spans do not cover the chapter's Word positions.");
}
private static DataContractJsonSerializer Serializer() => new(typeof(ChapterParagraph[]), new DataContractJsonSerializerSettings { MaxItemsInObjectGraph = 500000 });
public static string Encode(ChapterParagraph[] rows)
{
ValidateRows(rows);
if (rows.Any(p => p.Text != null)) throw new ArgumentException("Position frames contain metadata only.");
using var buffer = new MemoryStream(); Serializer().WriteObject(buffer, rows);
var result = Encoding.UTF8.GetString(buffer.ToArray());
if (result.Length > MaxFrameCharacters) throw new ArgumentException("Native position evidence exceeds the bounded transport.");
return result;
}
public static ChapterParagraph[] Decode(string frames)
{
if (frames.Length > MaxFrameCharacters) throw new ArgumentException("Native position evidence exceeds the bounded transport.");
try
{
using var buffer = new MemoryStream(Encoding.UTF8.GetBytes(frames));
var rows = (ChapterParagraph[]?)Serializer().ReadObject(buffer) ?? throw new ArgumentException("Missing native position evidence.");
ValidateRows(rows);
if (rows.Any(p => p.Text != null)) throw new ArgumentException("Position frames contain metadata only.");
return rows;
}
catch (SerializationException) { throw new ArgumentException("Malformed native position evidence."); }
}
}