547 lines
37 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 readonly Stopwatch selectionClock = 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 bool activationPending,traySupported;
public string WordCountSummary=>active?.WordCount?.ToString("N0")??"not read / stale";
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 " + typeof(WordAdapter).Assembly.GetName().Version + "\nAgent: " + ConnectionState
+ "\nOpen sessions: " + documents.Count
+ "\nIPC queued: " + link.QueueDepth + "\nWord work queued: " + scheduler.Depth
+ "\nAgent startup: " + AgentProcess.LaunchStatus
+ "\nMain document words: " + WordCountSummary
+ "\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")
{traySupported=false;
foreach(var doc in documents.Values){StopAi(doc,"Agent disconnected. Successful AI suggestions retained; reconnect before retrying.");}
}
if (state == "connected")
{
foreach (var doc in documents.Values) { CancelExtraction(doc); doc.NeedsSnapshot = true; }
ScheduleSelection();
}
invalidateRibbon();
});
link.Received += message => {
if(message.Status=="ready")PostToUi(()=>traySupported=(message.Capabilities??"").Split(',').Contains(ProtocolVersion.TrayCapability));
if(message.Command!=null)PostToUi(()=>HandleCommand(message.Command));
if(message.WordCount.HasValue)PostToUi(()=>{var doc=documents.Values.FirstOrDefault(d=>d.Session==message.SessionId&&d.Revision==message.Revision);if(doc!=null)doc.WordCount=message.WordCount;});
if(message.Status!="ok"&&message.Status!="ready")lastResult=message.Status;
};
scheduler.Measured += (_, elapsed) => lastBatchMs = elapsed;
scheduler.Failed += error => {
busyFailures++;
var frame=new StackTrace(error,true).GetFrames()?.FirstOrDefault(f=>f.GetMethod()?.DeclaringType?.FullName?.Contains("WordAdapter")==true);
lastWordError = error.GetType().Name + " 0x" + error.HResult.ToString("X8") + " · " + (error.Data["WordOperation"]??frame?.GetMethod()?.Name??error.TargetSite?.Name??"Word callback")+" line "+(frame?.GetFileLineNumber()??0);
foreach(var doc in documents.Values)if(doc.Extraction!=null)ReportReadFailure(doc,"Word access failed; retry after editing stops.");
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(); }
catch(Exception error){error.Data["WordOperation"]=operation;throw;}
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(document==null)return;
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.DisplayName=Com(()=>document.Name);
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.AssociationSite=ReadProperty(document,"PlotDirector.Native.ServerUrl");
if(DocumentBinding.ReadAssociation(ReadProperty(document,DocumentBinding.AssociationProperty),out var identity,out var rememberedBook,out var rememberedSite))
{state.Identity=identity;state.IdentityPersisted=true;state.ProjectId=null;state.BookId=rememberedBook;state.AssociationSite=rememberedSite;}
state.End = DocumentEnd(document); state.WasSaved = Com(() => document.Saved);
documents.Add(document,state); RegisterState(state);
ScheduleSelection();
})) pendingOpen.Remove(document);
}
private void Activate(Word.Document document,Word.Window window) { activationPending=true;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);
if(selection==null){active=null;invalidateRibbon();return;}
var document = Com(() => selection.Document);
if(document==null){active=null;invalidateRibbon();return;}
if (!documents.TryGetValue(document,out var state)) { Open(document); return; }
range = Com(() => selection.Range);
if(range==null)return;
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))
{
StopAi(state,"Document changed. Detect chapters again before analysis.");
state.End = documentEnd; state.Revision++; state.NeedsSnapshot = true;
state.WordCount=null;state.ChapterTitle="";state.SceneTitle="";
CancelExtraction(state); RegisterState(state);
}
state.WasSaved = saved;
if(active!=state||activationPending){link.TryPost(new Message {Kind="active",SessionId=state.Session,Revision=state.Revision});activationPending=false;}
active = state;
link.TryPost(new Message {Kind="selection",SessionId=state.Session,Revision=state.Revision,Start=start,End=end,Metrics=DrainMetrics(),QueueDepth=link.QueueDepth});
// Prose is read only on an explicit Companion request; cursor observations never rescan it.
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,Title=doc.DisplayName,RememberedBook=doc.BookId,AssociationSite=doc.AssociationSite,
ProjectId=doc.BookId.HasValue?doc.ProjectId:null,BookId=doc.ProjectId.HasValue?doc.BookId:null,
Revision=doc.Revision,IdentityPersisted=doc.IdentityPersisted,AssociationVerified=false
};
public void OpenCompanion()
{
if(ConnectionState=="connected"){if(!traySupported){MessageBox.Show("The running agent needs updating. Close Word normally and rerun the existing installer with -StopAgent.","PlotDirector Companion recovery");return;}link.TryPost(new Message{Kind="tray-open"});return;}
System.Threading.Tasks.Task.Run(()=>{try{AgentProcess.Start(true);if(!AgentProcess.LaunchStatus.StartsWith("Starting",StringComparison.Ordinal))PostToUi(()=>MessageBox.Show(AgentProcess.LaunchStatus,"PlotDirector Companion recovery"));}catch(Exception){PostToUi(()=>MessageBox.Show("Companion unavailable. Reinstall the complete developer package. Word remains usable.","PlotDirector Companion recovery"));}});
}
private void HandleCommand(AdapterCommand command)
{
var doc=documents.Values.FirstOrDefault(d=>d.Session==command.SessionId);
if(doc==null||doc.Revision!=command.Revision){Reply(command,"Document closed or changed; request again.");return;}
if(!scheduler.Post("command:"+doc.Session,()=>{
if(!documents.ContainsKey(doc.Document)||doc.Revision!=command.Revision){Reply(command,"Document changed; request again.");return;}
try{
if(command.Kind=="detect"){
CancelExtraction(doc);doc.End=DocumentEnd(doc.Document);if(!ScheduleSnapshot(doc,true))throw new InvalidOperationException("Word queue unavailable. Retry detection.");
}
else if(command.Kind=="extract-ai"&&command.Chapter!=null){
var chapter=command.Chapter;
if(chapter.Start<0||chapter.End<=chapter.Start||chapter.End>doc.End||DocumentEnd(doc.Document)!=doc.End)throw new InvalidOperationException("Chapter changed. Detect chapters again.");
CancelExtraction(doc);doc.AiChapter=command.Chapter;doc.AiBook=command.BookId;doc.AiAuthenticationContext=command.AuthenticationContext;doc.AiJob=command.Id;
doc.Extraction=new Extraction{Snapshot=command.Id,Revision=doc.Revision,Position=chapter.Start,Limit=chapter.End,IsAi=true};
if(!scheduler.Post("extract:"+doc.Session,()=>ExtractBatch(doc))){CancelExtraction(doc);throw new InvalidOperationException("Word queue is busy.");}
}
else if(command.Kind=="cancel"){CancelExtraction(doc);doc.AiJob=Guid.Empty;}
else if(command.Kind=="navigate"&&command.Chapter!=null){
var position=command.Chapter.Start;if(position<0||position>DocumentEnd(doc.Document))throw new InvalidOperationException("Position no longer exists.");
Word.Range range=null;try{range=Com(()=>doc.Document.Range(position,position));Com(()=>{range.Select();return true;});}finally{Release(range);}
}
else if(command.Kind=="associate"){
if(command.Remember){
if(Com(()=>doc.Document.ReadOnly))throw new InvalidOperationException("Document is read-only; select for this session without Remember.");
WriteProperty(doc.Document,DocumentBinding.AssociationProperty,DocumentBinding.AssociationValue(doc.Identity,command.BookId,command.Site),Microsoft.Office.Core.MsoDocProperties.msoPropertyTypeString);
doc.IdentityPersisted=true;doc.BookId=command.BookId;doc.AssociationSite=command.Site;link.Register(Descriptor(doc));
}
}
else throw new InvalidOperationException("Unsupported adapter request.");
Reply(command,"ok");
}catch(Exception e)when(e is COMException||e is InvalidOperationException||e is ArgumentException){Reply(command,"Word operation unavailable: "+e.GetType().Name+". Retry or select without Remember.");}
}))Reply(command,"Word queue busy. Retry from Companion.");
}
private void Reply(AdapterCommand command,string result)=>link.TryPost(new Message{Kind="adapter-result",SessionId=command.SessionId,Revision=command.Revision,SnapshotId=command.Id,OperationMessage=result});
private bool ScheduleSnapshot(LocalDocument doc,bool analyse=false)
{
if (doc.Extraction != null || ConnectionState != "connected") return false;
doc.Extraction = new Extraction { Snapshot = Guid.NewGuid(), Revision=doc.Revision,Analyse=analyse,Limit=doc.End };
if (!scheduler.Post("extract:"+doc.Session,() => ExtractBatch(doc)))
{doc.Extraction=null;return false;}
return true;
}
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=extraction.IsAi?"ai-begin":"snapshot-begin",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=extraction.Snapshot,Start=extraction.Position,End=extraction.Limit,BookId=doc.AiBook,AuthenticationContext=doc.AiAuthenticationContext,RequestAnalysis=extraction.Analyse,ChapterTitle=doc.AiChapter?.Title??""}))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<extraction.Limit)
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>=extraction.Limit)
{
if(!link.TryPost(new Message{Kind=extraction.IsAi?"ai-submit":"snapshot-end",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=extraction.Snapshot}))return;
if(!extraction.IsAi)doc.NeedsSnapshot=false;doc.Extraction=null;
// The committed snapshot resolves the current positional selection.
scheduler.Post("selection",CaptureSelection);return;
}
}
}
catch(COMException)
{ if(extraction.IsAi)StopAi(doc,"Word was busy. AI upload stopped; try again.");busyFailures++;ReportReadFailure(doc,"Word was busy; request chapters again.");doc.NeedsSnapshot=true;scheduler.PrioritizeAuthor(TimeSpan.FromSeconds(1)); }
catch(InvalidOperationException error)
{ if(extraction.IsAi)StopAi(doc,"Word range unavailable. AI upload stopped.");ReportReadFailure(doc,"Word range unavailable; detect chapters again.");doc.NeedsSnapshot=false;lastResult="Snapshot stopped: " + error.Message; }
catch(NullReferenceException)
{ CancelExtraction(doc);doc.NeedsSnapshot=false;lastResult="Snapshot stopped while reading Word.";throw; }
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]);
if (paragraph == null) throw new InvalidOperationException("Word did not return a paragraph.");
paragraphRange=Com(()=>paragraph.Range);
if (paragraphRange == null) throw new InvalidOperationException("Word did not return a 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(extraction.Limit,Math.Min(extraction.ParagraphEnd,start+ProtocolVersion.MaxParagraphCharacters));
if(end<=start)throw new InvalidOperationException("Non-advancing Word range.");
textRange=Com(()=>doc.Document.Range(start,end));
if (textRange == null) throw new InvalidOperationException("Word did not return the requested text range.");
var text=Com(()=>textRange.Text) ?? "";
extraction.Position=end;
return new Message{Kind=extraction.IsAi?"ai-fragment":"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 ?? 0);
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);
if (bookmarks == null) return tags.Distinct().ToArray();
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(!string.IsNullOrEmpty(name)&&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=doc.Extraction.IsAi?"ai-cancel":"snapshot-cancel",SessionId=doc.Session,Revision=doc.Revision,SnapshotId=doc.Extraction.Snapshot})&&doc.Extraction.IsAi)link.Reset();
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)){StopAi(state,"Save or close interrupted AI analysis. Successful results retained.");scheduler.Cancel("analyse:"+state.Session);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;
StopAi(state,"Save or close interrupted AI analysis. Successful results retained.");scheduler.Cancel("analyse:"+state.Session);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();
// Paste and some Word edits do not raise WindowSelectionChange. Probe only
// position/length/saved state; reuse the existing bounded reader if changed.
if(!disposed&&active!=null&&selectionClock.ElapsedMilliseconds>=1000)
{selectionClock.Restart();scheduler.Post("selection",CaptureSelection);}
if(!disposed)scheduler.Pump();
if(!disposed&&ConnectionState=="connected"&&metricClock.ElapsedMilliseconds>=1000)
{
metricClock.Restart();scheduler.Post("selection",CaptureSelection);
if(active!=null)link.TryPost(new Message{Kind="metrics",SessionId=active.Session,Revision=active.Revision,Metrics=DrainMetrics(),QueueDepth=link.QueueDepth,OperationMessage=Diagnostics});
}
}
private void RegisterState(LocalDocument doc)=>link.Register(Descriptor(doc));
private void ReportReadFailure(LocalDocument doc,string reason){CancelExtraction(doc);link.TryPost(new Message{Kind="adapter-result",SessionId=doc.Session,Revision=doc.Revision,OperationMessage=reason});lastResult=reason;}
private void StopAi(LocalDocument doc,string reason)
{
if(doc.Extraction?.IsAi==true)CancelExtraction(doc);
doc.AiJob=Guid.Empty;lastResult=reason;
}
// 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;
if(property==null)return "";
return Com<string>(() => Convert.ToString(value.Value));
}
catch(COMException){return "";}finally{Release(property);Release(properties);}
}
private void WriteProperty(Word.Document document,string name,object value,Microsoft.Office.Core.MsoDocProperties type)
{
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)){}
catch(COMException error) when(error.HResult==unchecked((int)0x8002000B)||error.HResult==unchecked((int)0x80070057)){}
if(property==null)property=Com<object>(()=>collection.Add(name,false,type,value));
else {dynamic existing=property;Com(()=>{existing.Value=value;return true;});}
}
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 string DisplayName;
public string AssociationSite="",ChapterTitle="",SceneTitle="";
public int? WordCount;
public Guid AiAuthenticationContext,AiJob;public int AiBook;public StructureSuggestion AiChapter;
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,Limit;public int OutlineLevel;public bool Begun,Analyse,IsAi;public Message Pending;}
}
}