183 lines
14 KiB
C#

using System;
using System.Collections.Generic;
using System.Diagnostics;
using Word=Microsoft.Office.Interop.Word;
using PlotDirector.Companion.Protocol;
using PlotDirector.Companion.Protocol.Manuscript;
namespace PlotDirector.WordAddIn
{
public sealed partial class WordAdapter
{
private string serverBook = "", serverChapter = "", serverScene = "";
private int serverBookId;
private long serverRevision = -1;
private ChapterSyncProgress serverChapterProgress;
public bool HasRibbonBook => active != null && ConnectionState == "connected" && serverBookId > 0;
public string RibbonBook => HasRibbonBook && serverBook.Length > 0 ? serverBook : "No linked book";
private bool HasCurrentRibbonState => HasRibbonBook && active.Revision == serverRevision;
public string RibbonLocation => HasCurrentRibbonState && serverScene.Length > 0
? (serverChapter.Length == 0 ? serverScene : serverChapter + " · " + serverScene)
: "Location unverified";
public string ChapterStatusLabel
{
get
{
if (ConnectionState != "connected") return "Not connected";
if (!HasRibbonBook) return "No linked book";
if (!HasCurrentRibbonState) return "Changes found";
if (serverChapterProgress == null) return "Not yet checked";
switch (serverChapterProgress.State)
{
case "Checking": return "Synchronising";
case "Synchronised":
if (serverChapterProgress.Total > 0 && serverChapterProgress.Matching == serverChapterProgress.Total)
return "Up to date";
return "Review needed";
case "Needs review": return "Review needed";
case "Changed": return "Changes found";
default: return "Not yet checked";
}
}
}
public string RibbonSyncProgress => ChapterStatusLabel == "Synchronising" && serverChapterProgress.Total > 0
? serverChapterProgress.Message
: ChapterStatusLabel == "Review needed" ? "See status tooltip" : " ";
public string ChapterStatusTip => (HasCurrentRibbonState ? serverChapterProgress?.Message : null)
?? "Synchronise to verify the manuscript position.";
public void OpenWritingWorkspace(string command)
{
if (HasRibbonBook)
link.TryPost(new Message { Kind = command, SessionId = active.Session, Revision = active.Revision });
}
public void RequestChapterSynchronisation(bool repair)
{
if (!HasRibbonBook) { lastResult = "Open a linked manuscript and connect Companion first."; return; }
if (!link.TryPost(new Message { Kind = repair ? "tray-repair" : "tray-sync", SessionId = active.Session, Revision = active.Revision }))
{
lastResult = "Local queue is busy. Word remains usable; retry shortly.";
return;
}
serverChapterProgress = null;
invalidateRibbon();
}
public void ShowTroubleshooting() => System.Windows.Forms.MessageBox.Show(Diagnostics, "PlotDirector Troubleshooting");
private void ReceiveChapterStatus(Message message)
{
if (active == null || active.Session != message.SessionId || active.Revision != message.Revision) return;
if (serverBookId == message.BookId && serverRevision == message.Revision &&
serverBook == message.BookTitle && serverChapter == message.ChapterTitle && serverScene == message.SceneTitle &&
serverChapterProgress?.State == message.ChapterProgress?.State &&
serverChapterProgress?.Total == message.ChapterProgress?.Total &&
serverChapterProgress?.Matching == message.ChapterProgress?.Matching &&
serverChapterProgress?.Message == message.ChapterProgress?.Message) return;
serverBookId = message.BookId;
serverRevision = message.Revision;
serverBook = message.BookTitle ?? "";
serverChapter = message.ChapterTitle ?? "";
serverScene = message.SceneTitle ?? "";
serverChapterProgress = message.ChapterProgress;
invalidateRibbon();
}
private void ChangeActiveDocument(LocalDocument document)
{
if (active == document) return;
active = document;
serverBookId = 0;
serverRevision = -1;
serverBook = serverChapter = serverScene = "";
serverChapterProgress = null;
invalidateRibbon();
}
private sealed class ChapterRead
{
public AdapterCommand Command;public int Phase,Seek,Steps,Start,End,Offset;public string Text="",Xml="",NextId="";public bool Begun; public int IdentityPosition; public readonly System.Text.StringBuilder Identities = new System.Text.StringBuilder(); public string IdentityFrames = "";
}
private readonly Dictionary<Guid,ChapterRead> chapterReads=new Dictionary<Guid,ChapterRead>();
private void CancelChapterRead(LocalDocument doc){chapterReads.Remove(doc.Session);scheduler.Cancel("chapter:"+doc.Session);}
private void StartChapterRead(LocalDocument doc,AdapterCommand command)
{
if(doc.Extraction!=null||doc.Maintenance!=null)throw new InvalidOperationException("Word already has an explicit read or maintenance request. Retry chapter validation afterwards.");
if(chapterReads.Count>=2&&!chapterReads.ContainsKey(doc.Session))throw new InvalidOperationException("Two document chapter reads are already pending. Activate this manuscript and retry.");
CancelChapterRead(doc);chapterReads[doc.Session]=new ChapterRead{Command=command,Seek=Math.Max(0,Math.Min(command.Chapter==null?0:command.Chapter.Start,doc.End-1))};
if(!scheduler.Post("chapter:"+doc.Session,()=>ReadChapterStep(doc))){CancelChapterRead(doc);throw new InvalidOperationException("Word queue is busy; accepted checkpoints are preserved. Retry shortly.");}
}
private string ReadLiveParagraphId(Word.Paragraph paragraph)
{
var value = Com(() => paragraph.ParaID, "chapter-paragraph-id");
var id = WordParagraphIdentity.Normalise(value.ToString("X8", System.Globalization.CultureInfo.InvariantCulture));
if (id.Length == 0) throw new InvalidOperationException("Word did not provide a native paragraph ID. Review this chapter or use the explicit fallback.");
return id;
}
private void ReadChapterStep(LocalDocument doc)
{
ChapterRead read;if(!chapterReads.TryGetValue(doc.Session,out read))return;
if(!documents.ContainsKey(doc.Document)||doc.Revision!=read.Command.Revision||closing.Contains(doc.Document)||ConnectionState!="connected"){CancelChapterRead(doc);return;}
var watch=Stopwatch.StartNew();Word.Range point=null,heading=null,range=null;Word.Paragraphs paragraphs=null;Word.Paragraph paragraph=null;
try
{
if((read.Phase<4||read.Phase==6||read.Phase==7)&&(!Com(()=>doc.Document.Saved)||Com(()=>application.BackgroundSavingStatus)!=0))throw new InvalidOperationException("Save Word and wait for background saving before validating chapters.");
if(read.Phase==0){
if(++read.Steps>128)throw new InvalidOperationException("No bounded Heading 1 boundary could be verified. Use manuscript repair; existing mappings are preserved.");
point=Com(()=>doc.Document.Range(read.Seek,read.Seek));paragraphs=Com(()=>point.Paragraphs);paragraph=Com(()=>paragraphs[1]);range=Com(()=>paragraph.Range);
var start=Com(()=>range.Start);var outline=(int)Com(()=>paragraph.OutlineLevel);
if(outline==1){read.Start=start;read.Seek=start+1;read.Phase=1;}
else{heading=Com(()=>point.GoTo(What:Word.WdGoToItem.wdGoToHeading,Which:Word.WdGoToDirection.wdGoToPrevious));var previous=Com(()=>heading.Start);if(previous>=read.Seek||previous==0&&start==0){read.Start=-1;read.Seek=0;read.Phase=1;}else read.Seek=previous;}
}else if(read.Phase==1){
if(++read.Steps>256)throw new InvalidOperationException("Chapter boundary search exceeded its bound; review the document structure.");
point=Com(()=>doc.Document.Range(read.Seek,read.Seek));heading=Com(()=>point.GoTo(What:Word.WdGoToItem.wdGoToHeading,Which:Word.WdGoToDirection.wdGoToNext));var next=Com(()=>heading.Start);
if(next<=read.Seek||next>=doc.End){if(read.Start<0)throw new InvalidOperationException("No Heading 1 chapter is available at this Word location.");read.End=DocumentEnd(doc.Document);read.Phase=2;}
else{paragraphs=Com(()=>heading.Paragraphs);paragraph=Com(()=>paragraphs[1]);var level=(int)Com(()=>paragraph.OutlineLevel);
if(level==1){if(read.Start<0){read.Start=next;read.Seek=next+1;}else{read.End=next;read.Seek=next;read.Phase=6;}}
else read.Seek=next+1;
}
}else if(read.Phase==6){
point=Com(()=>doc.Document.Range(read.Seek,read.Seek));
paragraphs=Com(()=>point.Paragraphs);paragraph=Com(()=>paragraphs[1]);
range=Com(()=>paragraph.Range);
if (Com(()=>range.Start) != read.End || (int)Com(()=>paragraph.OutlineLevel) != 1)
throw new InvalidOperationException("The next chapter boundary changed during validation.");
read.NextId=ReadLiveParagraphId(paragraph);read.Phase=2;
}else if(read.Phase==2){
if(read.End<=read.Start||read.End-read.Start>ChapterFingerprint.MaxCharacters)throw new InvalidOperationException("This chapter exceeds the bounded fast reader. Use bounded manuscript synchronisation; no mapping was guessed.");
if(!read.Begun){if(!link.TryPost(new Message{Kind="chapter-begin",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=read.Command.Id,OperationId=read.Command.OperationId,BookId=read.Command.BookId,DocumentEnd=doc.End,Start=read.Start,End=read.End,WordSaved=true,ChapterTitle=read.NextId}))return;read.Begun=true;}
range=Com(()=>doc.Document.Range(read.Start,read.End));read.Text=Com(()=>range.Text,"chapter-range-text")??"";
if(read.Text.Length!=read.End-read.Start)throw new InvalidOperationException("Word range length contains unsupported structural content; positions were not guessed.");read.Phase=3;
}else if(read.Phase==3){
range=Com(()=>doc.Document.Range(read.Start,read.End));read.Xml=Com(()=>range.WordOpenXML,"chapter-range-xml")??"";
if(read.Xml.Length>8*1024*1024)throw new InvalidOperationException("Chapter XML exceeds the bounded transport. Use existing bounded synchronisation.");
read.IdentityPosition=read.Start;read.Phase=7;
}else if(read.Phase==7){
// One paragraph per scheduler turn. Word COM objects never leave the STA.
point=Com(()=>doc.Document.Range(read.IdentityPosition,read.IdentityPosition));
paragraphs=Com(()=>point.Paragraphs);paragraph=Com(()=>paragraphs[1]);range=Com(()=>paragraph.Range);
var start=Com(()=>range.Start);var end=Com(()=>range.End);
if(start!=read.IdentityPosition||end<=start||end>read.End||read.Identities.Length/16>=ChapterFingerprint.MaxParagraphs)
throw new InvalidOperationException("Live Word paragraph boundaries do not match the chapter.");
read.Identities.Append(ReadLiveParagraphId(paragraph));
read.Identities.Append((end-start).ToString("X8",System.Globalization.CultureInfo.InvariantCulture));
read.IdentityPosition=end;
if(end==read.End){read.IdentityFrames=read.Identities.ToString();read.Phase=4;}
}else{
if(!read.Begun){if(!link.TryPost(new Message{Kind="chapter-begin",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=read.Command.Id,OperationId=read.Command.OperationId,BookId=read.Command.BookId,DocumentEnd=doc.End,Start=read.Start,End=read.End,WordSaved=true,ChapterTitle=read.NextId}))return;read.Begun=true;}
for(int n=0;n<4&&watch.ElapsedMilliseconds<20;n++){
var source=read.Phase==4?read.Text:read.Phase==5?read.Xml:read.IdentityFrames;
if(read.Offset<source.Length){var count=Math.Min(2048,source.Length-read.Offset);if(!link.TryPost(new Message{Kind="chapter-chunk",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=read.Command.Id,Action=read.Phase==4?"text":read.Phase==5?"xml":"ids",Start=read.Offset,OperationMessage=source.Substring(read.Offset,count)}))return;read.Offset+=count;}
else if(read.Phase<8){read.Phase=read.Phase==4?5:8;read.Offset=0;}
else{if(!link.TryPost(new Message{Kind="chapter-end",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=read.Command.Id}))return;CancelChapterRead(doc);return;}
}
}
}
catch(Exception error)when(error is System.Runtime.InteropServices.COMException||error is InvalidOperationException||error is ArgumentException||error is NullReferenceException){CancelChapterRead(doc);Reply(read.Command,"Chapter validation stopped: "+error.Message);lastResult="Chapter validation stopped; existing accepted mappings are preserved.";}
finally{Release(range);Release(paragraph);Release(paragraphs);Release(heading);Release(point);Metric("chapter-ui-step",watch.Elapsed.TotalMilliseconds);if(chapterReads.ContainsKey(doc.Session)&&!scheduler.Post("chapter:"+doc.Session,()=>ReadChapterStep(doc))){CancelChapterRead(doc);Reply(read.Command,"Chapter validation stopped: Word queue is busy. Accepted checkpoints are preserved.");}}
}
}
}