43 lines
2.6 KiB
C#

namespace PlotDirector.Companion.Protocol.Manuscript;
// Range.Text includes Word's paragraph terminators. No paragraph COM enumeration is
// needed to calculate content, but content alone must never certify native identity.
public enum ChapterRangeResult { RequiresDetailed, Matching, Changed }
public sealed class ChapterRangeCheck
{
public ChapterRangeResult Result {get;set;}
public string IdentityFrames {get;set;}="";
}
public static class ChapterRangeVerification
{
public static string Content(string text)
{
if(text.Length==0||text.Length>ChapterFingerprint.MaxCharacters||text[text.Length-1]!='\r')
throw new ArgumentException("A complete bounded chapter range is required.");
var rows=new List<string>();var start=0;
for(var i=0;i<text.Length;i++)if(text[i]=='\r'){rows.Add(text.Substring(start,i-start+1));start=i+1;}
return ChapterFingerprint.Content(rows);
}
public static ChapterRangeResult Compare(string text,string xml,ChapterManifestItem baseline,string nextHeading)=>Check(text,xml,baseline,nextHeading).Result;
public static ChapterRangeCheck Check(string text,string xml,ChapterManifestItem baseline,string nextHeading)
{
try
{
if(!baseline.DurableAccepted||baseline.Algorithm!=ChapterFingerprint.Version||baseline.State=="Needs review"||baseline.PositionHash!="")return new(){Result=ChapterRangeResult.RequiresDetailed};
if(baseline.NextHeadingId!=nextHeading||Content(text)!=baseline.ContentHash)return new(){Result=ChapterRangeResult.Changed};
// Missing XML native IDs, pictures, fields, revisions, section breaks,
// ambiguous styles or geometry all fall back to the qualified live reader.
var rows=ChapterFingerprint.ReadXml(xml,text);
var matches=rows.Length==baseline.ParagraphCount&&rows[0].NativeId==baseline.HeadingNativeId&&
rows[0].Outline==1&&!rows.Skip(1).Any(p=>p.Outline==1)&&
ChapterFingerprint.Identity(rows)==baseline.IdentityHash&&ChapterFingerprint.Content(rows.Select(p=>p.Text!))==baseline.ContentHash;
return new(){Result=matches?ChapterRangeResult.Matching:ChapterRangeResult.Changed,
IdentityFrames=matches?string.Concat(rows.Select(p=>p.NativeId+p.Length.ToString("X8",System.Globalization.CultureInfo.InvariantCulture)+p.Outline.ToString("X8",System.Globalization.CultureInfo.InvariantCulture))):""};
}
catch(Exception e)when(e is ArgumentException or System.Xml.XmlException){return new(){Result=ChapterRangeResult.RequiresDetailed};}
}
}