81 lines
9.2 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 ChapterSyncProgress serverChapterProgress;
public string ChapterStatusLabel=>active==null?"No active manuscript":serverChapterProgress==null?"Chapters not yet checked":$"Chapters {serverChapterProgress.Matching}/{serverChapterProgress.Total} · {serverChapterProgress.State}";
public string ChapterStatusTip=>string.Join("\n",new[]{serverBook,serverChapter,serverScene,serverChapterProgress==null?"Connect and validate the current chapter.":serverChapterProgress.Message});
public void RequestChapterSynchronisation(bool repair)
{if(active==null||ConnectionState!="connected"){lastResult="Open a 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.";}
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;var before=ChapterStatusLabel+ChapterStatusTip;serverBook=message.BookTitle;serverChapter=message.ChapterTitle;serverScene=message.SceneTitle;serverChapterProgress=message.ChapterProgress;if(before!=ChapterStatusLabel+ChapterStatusTip)invalidateRibbon();}
private void ChangeActiveDocument(LocalDocument document)
{if(active==document)return;active=document;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<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 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.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":"xml",Start=read.Offset,OperationMessage=source.Substring(read.Offset,count)}))return;read.Offset+=count;}
else if(read.Phase==4){read.Phase=5;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.");}}
}
}
}