464 lines
28 KiB
C#

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Windows.Forms;
using Message = PlotDirector.Companion.Protocol.Message;
using PlotDirector.Companion.Client;
using PlotDirector.Companion.Protocol;
using Word = Microsoft.Office.Interop.Word;
namespace PlotDirector.WordAddIn
{
// This object and every retained RCW are owned exclusively by Word's UI thread.
// AgentLink sees only fresh value DTOs. It never receives this object as a callback.
public sealed class WordAdapter : IDisposable
{
private readonly int ownerThread = Environment.CurrentManagedThreadId;
private readonly Word.Application application;
private readonly Word.ApplicationEvents4_Event events;
private readonly Dictionary<Word.Document, LocalDocument> documents = new Dictionary<Word.Document,LocalDocument>();
private readonly HashSet<Word.Document> pendingOpen = new HashSet<Word.Document>();
private readonly HashSet<Word.Document> closing = new HashSet<Word.Document>();
private readonly WordAccessScheduler scheduler = new WordAccessScheduler();
private readonly Control dispatch = new Control();
private readonly Timer timer = new Timer { Interval = 25 };
private readonly AgentLink link;
private readonly Action invalidateRibbon;
private readonly Queue<double> operationTimes = new Queue<double>();
private readonly Queue<UiMetric> pendingMetrics = new Queue<UiMetric>();
private readonly Stopwatch tickClock = Stopwatch.StartNew();
private readonly Stopwatch metricClock = Stopwatch.StartNew();
private void Metric(string name,double milliseconds)
{
if(pendingMetrics.Count==256)pendingMetrics.Dequeue();
pendingMetrics.Enqueue(new UiMetric{Operation=name,Milliseconds=milliseconds});
}
private UiMetric[] DrainMetrics()
{
var values=new List<UiMetric>();
while(values.Count<32&&pendingMetrics.Count>0)values.Add(pendingMetrics.Dequeue());
return values.ToArray();
}
private LocalDocument active;
private bool disposed;
private long busyFailures;
private string lastWordError;
private int documentCollectionGeneration;
private double lastBatchMs;
private string lastResult = "Waiting for local structural snapshot";
public string ConnectionState { get; private set; } = "Connecting";
public bool HasActiveDocument => active != null;
public string Diagnostics => "PlotDirector by Nick Beckley — Phase 1\nAgent: " + ConnectionState
+ "\nServer authentication / prose sync: unavailable\nOpen sessions: " + documents.Count
+ "\nIPC queued: " + link.QueueDepth + "\nWord work queued: " + scheduler.Depth
+ "\nLast UI batch ms: " + lastBatchMs.ToString("F2") + "\nMax recorded COM call ms: " + (operationTimes.Count == 0 ? 0 : operationTimes.Max()).ToString("F2")
+ "\nCOM busy/errors: " + busyFailures + (lastWordError == null ? "" : " (last: " + lastWordError + ")") + "\n" + lastResult;
public WordAdapter(Word.Application application, Action invalidateRibbon)
{
if(System.Threading.Thread.CurrentThread.GetApartmentState()!=System.Threading.ApartmentState.STA)throw new InvalidOperationException("Word adapter requires the Word STA.");
this.application = application; this.invalidateRibbon = invalidateRibbon;
// Force a handle here; BeginInvoke always returns callbacks to this STA.
var handle = dispatch.Handle;
link = new AgentLink(AgentProcess.PipeName(), Guid.NewGuid(), AgentProcess.VerifyOwner, AgentProcess.Start);
link.StateChanged += state => PostToUi(() => {
ConnectionState = state;
if (state == "connected")
{
foreach (var doc in documents.Values) { CancelExtraction(doc); doc.NeedsSnapshot = true; }
ScheduleSelection();
}
invalidateRibbon();
});
link.Received += message => {
var description = message.Status + (string.IsNullOrEmpty(message.ChapterTitle) ? "" : " · " + message.ChapterTitle)
+ (string.IsNullOrEmpty(message.SceneTitle) ? "" : " / " + message.SceneTitle);
if (message.Status != "ok" || !string.IsNullOrEmpty(message.ChapterTitle)) PostToUi(() => {
if(message.Status!="ok"&&message.Status!="ready"&&message.Status!="awaiting-structure")
{
var failed=documents.Values.FirstOrDefault(d=>d.Session==message.SessionId&&d.Revision==message.Revision);
if(failed!=null){CancelExtraction(failed);failed.NeedsSnapshot=false;}
}
if(active != null && active.Session == message.SessionId && active.Revision == message.Revision)lastResult = description;
});
};
scheduler.Measured += (_, elapsed) => lastBatchMs = elapsed;
scheduler.Failed += error => {
busyFailures++;
lastWordError = error.GetType().Name + " 0x" + error.HResult.ToString("X8");
scheduler.PrioritizeAuthor(TimeSpan.FromSeconds(1));
};
events = (Word.ApplicationEvents4_Event)application;
events.DocumentOpen += Open;
events.NewDocument += Open;
events.DocumentChange += ScheduleSelection;
events.WindowActivate += Activate;
events.WindowSelectionChange += SelectionChanged;
events.DocumentBeforeClose += BeforeClose;
events.DocumentBeforeSave += BeforeSave;
timer.Tick += Tick;
timer.Start(); link.Start();
// Already-open documents are registered in bounded UI actions, not a background COM enumeration.
scheduler.Post("discover", DiscoverOpenDocuments);
}
private void PostToUi(Action callback)
{
if (disposed) return;
try { dispatch.BeginInvoke(new Action(() => { if (!disposed) callback(); })); }
catch(InvalidOperationException) { }
}
private T Com<T>(Func<T> read,[CallerMemberName]string operation="")
{
if(Environment.CurrentManagedThreadId!=ownerThread)throw new InvalidOperationException("Cross-thread Word access refused.");
var watch = Stopwatch.StartNew();
try { return read(); }
finally { if(operationTimes.Count == 256)operationTimes.Dequeue(); operationTimes.Enqueue(watch.Elapsed.TotalMilliseconds);Metric(operation,watch.Elapsed.TotalMilliseconds); }
}
private void DiscoverOpenDocuments() => DiscoverAt(1);
private void DiscoverAt(int index)
{
Word.Documents collection = null;
try
{
collection = Com(() => application.Documents);
var count = Math.Min(ProtocolVersion.MaxDocuments,Com(() => collection.Count));
if(index<=count)
{
var doc=Com(()=>collection[index]);Open(doc);
scheduler.Post("discover",()=>DiscoverAt(index+1));
}
else ScheduleSelection();
}
finally { Release(collection); }
}
private void Open(Word.Document document)
{
if (documents.ContainsKey(document) || documents.Count >= ProtocolVersion.MaxDocuments || !pendingOpen.Add(document)) return;
documentCollectionGeneration++;
if (!scheduler.Post("open:" + Guid.NewGuid().ToString("N"), () => {
pendingOpen.Remove(document);
if (documents.ContainsKey(document) || documents.Count >= ProtocolVersion.MaxDocuments) return;
var state = new LocalDocument(document);
state.Identity = ReadGuidProperty(document,"PlotDirector.Native.DocumentGuid") ?? Guid.NewGuid();
state.IdentityPersisted = ReadGuidProperty(document,"PlotDirector.Native.DocumentGuid").HasValue;
state.ProjectId = ReadPositiveProperty(document,"PlotDirector.Native.ProjectID");
state.BookId = ReadPositiveProperty(document,"PlotDirector.Native.BookID");
state.End = DocumentEnd(document); state.WasSaved = Com(() => document.Saved);
documents.Add(document,state); link.Register(Descriptor(state));
ScheduleSelection();
})) pendingOpen.Remove(document);
}
private void Activate(Word.Document document,Word.Window window) { Open(document); ScheduleSelection(); }
private void SelectionChanged(Word.Selection selection) { ScheduleSelection(); }
private void ScheduleSelection()
{
if (disposed) return;
// Repeated events collapse to one read. The event's Selection RCW is not retained.
scheduler.PrioritizeAuthor(TimeSpan.FromMilliseconds(120));
scheduler.Post("selection", CaptureSelection);
if(closing.Count>0)scheduler.Post("retire",ReconcileClosedDocuments);
}
private void CaptureSelection()
{
Word.Selection selection = null; Word.Range range = null;
try
{
selection = Com(() => application.Selection);
var document = Com(() => selection.Document);
if (!documents.TryGetValue(document,out var state)) { Open(document); return; }
range = Com(() => selection.Range);
var start = Com(() => range.Start); var end = Com(() => range.End);
var documentEnd = DocumentEnd(document); var saved = Com(() => document.Saved);
if (documentEnd != state.End || (state.WasSaved && !saved))
{
state.End = documentEnd; state.Revision++; state.NeedsSnapshot = true;
CancelExtraction(state); link.Register(Descriptor(state));
}
state.WasSaved = saved;
active = state;
link.TryPost(new Message {Kind="active",SessionId=state.Session,Revision=state.Revision});
link.TryPost(new Message {Kind="selection",SessionId=state.Session,Revision=state.Revision,Start=start,End=end,Metrics=DrainMetrics(),QueueDepth=link.QueueDepth});
if(state.NeedsSnapshot && ConnectionState == "connected") ScheduleSnapshot(state);
invalidateRibbon();
}
finally { Release(range); Release(selection); }
}
private int DocumentEnd(Word.Document document)
{
Word.Range range = null;
try { range = Com(() => document.Content); return Com(() => range.End); }
finally { Release(range); }
}
private DocumentDescriptor Descriptor(LocalDocument doc) => new DocumentDescriptor {
SessionId=doc.Session,ManuscriptId=doc.Identity,ProjectId=doc.ProjectId,BookId=doc.BookId,
Revision=doc.Revision,IdentityPersisted=doc.IdentityPersisted,AssociationVerified=false
};
public void RequestSnapshot()
{
if (active == null) return;
active.Revision++; active.NeedsSnapshot = true; CancelExtraction(active);
link.Register(Descriptor(active)); ScheduleSnapshot(active);
}
private void ScheduleSnapshot(LocalDocument doc)
{
if (doc.Extraction != null || ConnectionState != "connected") return;
doc.Extraction = new Extraction { Snapshot = Guid.NewGuid(), Revision=doc.Revision };
scheduler.Post("extract:"+doc.Session,() => ExtractBatch(doc));
}
private void ExtractBatch(LocalDocument doc)
{
var extraction = doc.Extraction;
if(extraction == null || !documents.ContainsKey(doc.Document) || extraction.Revision != doc.Revision || closing.Contains(doc.Document)) return;
if(ConnectionState != "connected") { doc.Extraction=null; return; }
var watch=Stopwatch.StartNew();
try
{
if(!extraction.Begun)
{
if(!link.TryPost(new Message{Kind="snapshot-begin",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=extraction.Snapshot,End=doc.End}))return;
extraction.Begun=true;
}
// At most four <=2048-character fragments and a cooperative ~20ms budget.
// A single COM call cannot be preempted; every call is measured separately.
for(var count=0;count<4 && watch.ElapsedMilliseconds<20;count++)
{
if(extraction.Pending == null && extraction.Position<doc.End)
extraction.Pending = ReadFragment(doc,extraction);
if(extraction.Pending != null)
{
if(!link.TryPost(extraction.Pending))return; // Keep this value; do not reread Word under backpressure.
extraction.Pending=null;
}
if(extraction.Position>=doc.End)
{
if(!link.TryPost(new Message{Kind="snapshot-end",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=extraction.Snapshot}))return;
doc.NeedsSnapshot=false;doc.Extraction=null;
// The committed snapshot resolves the current positional selection.
scheduler.Post("selection",CaptureSelection);return;
}
}
}
catch(COMException)
{ busyFailures++;CancelExtraction(doc);doc.NeedsSnapshot=true;scheduler.PrioritizeAuthor(TimeSpan.FromSeconds(1)); }
catch(InvalidOperationException)
{ CancelExtraction(doc);doc.NeedsSnapshot=false;lastResult="Snapshot stopped: unsupported range/marker density. Use Diagnostics; Word remains usable."; }
finally
{
lastBatchMs=watch.Elapsed.TotalMilliseconds;Metric("snapshot-batch",lastBatchMs);
if(doc.Extraction != null)scheduler.Post("extract:"+doc.Session,()=>ExtractBatch(doc));
}
}
private Message ReadFragment(LocalDocument doc,Extraction extraction)
{
Word.Range point=null,paragraphRange=null,textRange=null; Word.Paragraphs paragraphs=null;Word.Paragraph paragraph=null;
try
{
string[] tags=Array.Empty<string>();
if(extraction.Position>=extraction.ParagraphEnd)
{
point=Com(()=>doc.Document.Range(extraction.Position,extraction.Position));
paragraphs=Com(()=>point.Paragraphs);paragraph=Com(()=>paragraphs[1]);
paragraphRange=Com(()=>paragraph.Range);
extraction.ParagraphEnd=Com(()=>paragraphRange.End);
extraction.OutlineLevel=(int)Com(()=>paragraph.OutlineLevel);
extraction.ParagraphIndex++;
tags=ReadMarkers(paragraphRange);
}
var start=extraction.Position;var end=Math.Min(doc.End,Math.Min(extraction.ParagraphEnd,start+ProtocolVersion.MaxParagraphCharacters));
if(end<=start)throw new InvalidOperationException("Non-advancing Word range.");
textRange=Com(()=>doc.Document.Range(start,end));var text=Com(()=>textRange.Text) ?? "";
extraction.Position=end;
return new Message{Kind="snapshot-fragment",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=extraction.Snapshot,
Metrics=DrainMetrics(),QueueDepth=link.QueueDepth,Fragment=new ParagraphFragment{ParagraphIndex=extraction.ParagraphIndex,Start=start,End=end,OutlineLevel=extraction.OutlineLevel,
Text=text,MarkerTags=tags,CompletesParagraph=end>=extraction.ParagraphEnd}};
}
finally { Release(textRange);Release(paragraphRange);Release(paragraph);Release(paragraphs);Release(point); }
}
private string[] ReadMarkers(Word.Range range)
{
var tags=new List<string>();Word.ContentControls controls=null;Word.Bookmarks bookmarks=null;
try
{
// A PD control may surround this paragraph rather than be a child
// of its Range. Only its start is a structural boundary, never every
// paragraph enclosed by a chapter-spanning control.
Word.ContentControl parent=Com(()=>range.ParentContentControl);
var paragraphStart=Com(()=>range.Start);
try
{
for(var depth=0;parent!=null&&depth<4;depth++)
{
Word.Range parentRange=null;
try
{
parentRange=Com(()=>parent.Range);
if(Com(()=>parentRange.Start)==paragraphStart)
{var tag=Com(()=>parent.Tag);if(!string.IsNullOrEmpty(tag)&&tag.Length<=128)tags.Add(tag);}
}
finally{Release(parentRange);}
Word.ContentControl next=null;
try{next=Com(()=>parent.ParentContentControl);}catch(COMException){ }
Release(parent);parent=next;
}
if(parent!=null)throw new InvalidOperationException("Content-control ancestry exceeds bounded read.");
}
finally{Release(parent);}
controls=Com(()=>range.ContentControls);var count=Com(()=>controls.Count);
if(count>8)throw new InvalidOperationException("Too many nested controls for a bounded marker read.");
for(var index=1;index<=count;index++)
{ Word.ContentControl control=null;try{control=Com(()=>controls[index]);var tag=Com(()=>control.Tag);if(!string.IsNullOrEmpty(tag)&&tag.Length<=128)tags.Add(tag);}finally{Release(control);} }
bookmarks=Com(()=>range.Bookmarks);var hidden=Com(()=>bookmarks.ShowHidden);
try
{
Com(()=>{bookmarks.ShowHidden=true;return true;});count=Com(()=>bookmarks.Count);
if(count>8)throw new InvalidOperationException("Too many bookmarks for a bounded marker read.");
for(var index=1;index<=count;index++)
{ Word.Bookmark bookmark=null;try{object key=index;bookmark=Com(()=>bookmarks.get_Item(ref key));var name=Com(()=>bookmark.Name);if(name.Length<=128)tags.Add(name);}finally{Release(bookmark);} }
}
finally {Com(()=>{bookmarks.ShowHidden=hidden;return true;});}
if(tags.Distinct().Count()>16)throw new InvalidOperationException("Marker density exceeds bounded read.");
return tags.Distinct().ToArray();
}
finally {Release(bookmarks);Release(controls);}
}
private void CancelExtraction(LocalDocument doc)
{
scheduler.Cancel("extract:"+doc.Session);
if(doc.Extraction!=null)link.TryPost(new Message{Kind="snapshot-cancel",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=doc.Extraction.Snapshot});
doc.Extraction=null;
}
private void BeforeSave(Word.Document document,ref bool saveAsUI,ref bool cancel)
{
// Never set Cancel, wait for IPC, read prose or force a document save.
scheduler.PrioritizeAuthor(TimeSpan.FromMilliseconds(500));
if(documents.TryGetValue(document,out var state)){CancelExtraction(state);state.NeedsSnapshot=true;}
}
private void BeforeClose(Word.Document document,ref bool cancel)
{
scheduler.PrioritizeAuthor(TimeSpan.FromMilliseconds(250));
if(!documents.TryGetValue(document,out var state))return;
CancelExtraction(state);
documentCollectionGeneration++;
closing.Add(document);
scheduler.Post("retire",ReconcileClosedDocuments);
}
private void ReconcileClosedDocuments() => ProbeOpenDocuments(1,-1,documentCollectionGeneration,new HashSet<Word.Document>());
private void ProbeOpenDocuments(int index,int expectedCount,int generation,HashSet<Word.Document> present)
{
if(generation!=documentCollectionGeneration){scheduler.Post("retire",ReconcileClosedDocuments);return;}
Word.Documents open=null;
try
{
open=Com(()=>application.Documents);var count=Com(()=>open.Count);
if(count>ProtocolVersion.MaxDocuments){lastResult="Document capacity exceeded; close reconciliation waits for at most 32 open documents.";return;}
if(expectedCount>=0&&count!=expectedCount){scheduler.Post("retire",ReconcileClosedDocuments);return;}
if(index<=Math.Min(count,ProtocolVersion.MaxDocuments))
{
present.Add(Com(()=>open[index]));
scheduler.Post("retire",()=>ProbeOpenDocuments(index+1,count,generation,present));return;
}
// No COM in the retirement loop. Cancelled close keeps its exact session.
foreach(var doc in closing.ToArray())
{
if(!present.Contains(doc)&&documents.TryGetValue(doc,out var state))
{CancelExtraction(state);documents.Remove(doc);link.Retire(state.Session);if(active==state)active=null;}
closing.Remove(doc);
}
}
finally{Release(open);invalidateRibbon();}
}
private void Tick(object sender,EventArgs args)
{
Metric("ui-tick-delay",Math.Max(0,tickClock.Elapsed.TotalMilliseconds-25));tickClock.Restart();
if(!disposed)scheduler.Pump();
if(!disposed&&active!=null&&ConnectionState=="connected"&&metricClock.ElapsedMilliseconds>=1000)
{
metricClock.Restart();
link.TryPost(new Message{Kind="metrics",SessionId=active.Session,Revision=active.Revision,Metrics=DrainMetrics(),QueueDepth=link.QueueDepth});
}
}
public void Reconnect() { link.Reset(); }
public void PersistNativeIdentity()
{
var doc=active;if(doc==null||doc.IdentityPersisted)return;
scheduler.Post("identity:"+doc.Session,()=>{
dynamic properties=doc.Document.CustomDocumentProperties;
try{properties.Add("PlotDirector.Native.DocumentGuid",false,Microsoft.Office.Core.MsoDocProperties.msoPropertyTypeString,doc.Identity.ToString("D"));}
finally{Release(properties);}
doc.IdentityPersisted=true;link.Register(Descriptor(doc));
});
}
// Future marker writes are explicitly scoped to a known document and exact range.
// No remote mutation command is exposed in protocol v1.
internal void AttachMarker(Word.Document document,int start,int end,string tag)
{
if(!tag.StartsWith("PD-CHAPTER-",StringComparison.Ordinal)||tag.Length>128)
if(!tag.StartsWith("PD-SCENE-",StringComparison.Ordinal)||tag.Length>128)throw new ArgumentException("Invalid marker.");
scheduler.Post("marker",()=>{
Word.Range range=null;Word.ContentControls controls=null;Word.ContentControl control=null;
try{range=document.Range(start,end);controls=document.ContentControls;control=controls.Add(Word.WdContentControlType.wdContentControlRichText,range);control.Tag=tag;control.Title="PlotDirector";control.Appearance=Word.WdContentControlAppearance.wdContentControlHidden;}
finally{Release(control);Release(controls);Release(range);}
});
}
internal void RemoveMarkerPreservingText(Word.ContentControl control)
=> scheduler.Post("marker-remove",()=>control.Delete(false)); // Interop false preserves prose; Office.js uses true.
internal void AttachBookmark(Word.Document document,int position,string name)
{
if(name.Length>40||(!name.StartsWith("_PD_SCENE_",StringComparison.Ordinal)&&!name.StartsWith("_PD_CHAPTER_",StringComparison.Ordinal)))throw new ArgumentException("Invalid bookmark marker.");
scheduler.Post("bookmark",()=>{
Word.Range range=null;Word.Bookmarks bookmarks=null;Word.Bookmark marker=null;
try{range=document.Range(position,position);bookmarks=document.Bookmarks;marker=bookmarks.Add(name,range);}
finally{Release(marker);Release(bookmarks);Release(range);}
});
}
internal void RemoveBookmark(Word.Document document,string name)
{
if(!name.StartsWith("_PD_SCENE_",StringComparison.Ordinal)&&!name.StartsWith("_PD_CHAPTER_",StringComparison.Ordinal))throw new ArgumentException("Invalid bookmark marker.");
scheduler.Post("bookmark-remove",()=>{
Word.Bookmarks bookmarks=null;Word.Bookmark marker=null;
try{bookmarks=document.Bookmarks;object key=name;marker=bookmarks.get_Item(ref key);marker.Delete();}
finally{Release(marker);Release(bookmarks);}
});
}
private Guid? ReadGuidProperty(Word.Document document,string name) {Guid value;return Guid.TryParse(ReadProperty(document,name),out value)&&value!=Guid.Empty?(Guid?)value:null;}
private int? ReadPositiveProperty(Word.Document document,string name) {int value;return int.TryParse(ReadProperty(document,name),out value)&&value>0?(int?)value:null;}
private string ReadProperty(Word.Document document,string name)
{
object properties=null,property=null;
try
{
properties = Com(() => document.CustomDocumentProperties);
dynamic collection = properties;
try { property = Com<object>(() => collection[name]); }
catch (ArgumentException error) when (error.HResult == unchecked((int)0x80070057))
{
// Word can report a missing named custom property as E_INVALIDARG.
return "";
}
dynamic value = property;
return Com<string>(() => Convert.ToString(value.Value));
}
catch(COMException){return "";}finally{Release(property);Release(properties);}
}
private static void Release(object value) {if(value!=null&&Marshal.IsComObject(value))Marshal.ReleaseComObject(value);}
public void Dispose()
{
if(disposed)return;disposed=true;timer.Stop();timer.Dispose();scheduler.Clear();
events.DocumentOpen-=Open;events.NewDocument-=Open;events.DocumentChange-=ScheduleSelection;events.WindowActivate-=Activate;
events.WindowSelectionChange-=SelectionChanged;events.DocumentBeforeClose-=BeforeClose;events.DocumentBeforeSave-=BeforeSave;
link.Dispose();documents.Clear();pendingOpen.Clear();closing.Clear();dispatch.Dispose();
}
private sealed class LocalDocument
{
public readonly Word.Document Document;public readonly Guid Session=Guid.NewGuid();public Guid Identity;public bool IdentityPersisted;
public int? ProjectId,BookId;public long Revision;public int End;public bool WasSaved;public bool NeedsSnapshot=true;public Extraction Extraction;
public LocalDocument(Word.Document document){Document=document;}
}
private sealed class Extraction
{public Guid Snapshot;public long Revision;public int Position,ParagraphEnd,ParagraphIndex;public int OutlineLevel;public bool Begun;public Message Pending;}
}
}