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 ? string.Format("{0} of {1} chapters accepted", serverChapterProgress.Matching, serverChapterProgress.Total) : " "; 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; } private readonly Dictionary chapterReads=new Dictionary(); 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 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&&(!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){ range=Com(()=>doc.Document.Range(read.Seek,Math.Min(read.Seek+1,doc.End)));read.NextId=WordParagraphIdentity.Read(Com(()=>range.WordOpenXML,"chapter-next-heading-identity"));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.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.Xml; if(read.OffsetReadChapterStep(doc))){CancelChapterRead(doc);Reply(read.Command,"Chapter validation stopped: Word queue is busy. Accepted checkpoints are preserved.");}} } } }