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 partial class WordAdapter : IDisposable { private readonly int ownerThread = Environment.CurrentManagedThreadId; private readonly Word.Application application; private readonly Word.ApplicationEvents4_Event events; private readonly Dictionary documents = new Dictionary(); private readonly HashSet pendingOpen = new HashSet(); private readonly HashSet closing = new HashSet(); 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 operationTimes = new Queue(); private readonly Queue pendingMetrics = new Queue(); private readonly Stopwatch tickClock = Stopwatch.StartNew(); private readonly Stopwatch metricClock = Stopwatch.StartNew(); private readonly Stopwatch selectionClock = Stopwatch.StartNew(); private readonly Dictionary chapterMetrics=new Dictionary(); private void Metric(string name,double milliseconds,Guid navigationId=default(Guid)) { if(name.StartsWith("chapter-",StringComparison.Ordinal)) { double[] totals;if(!chapterMetrics.TryGetValue(name,out totals)&&chapterMetrics.Count<32)chapterMetrics[name]=totals=new double[3]; if(totals!=null){totals[0]++;totals[1]+=milliseconds;totals[2]=Math.Max(totals[2],milliseconds);} } if(pendingMetrics.Count==256)pendingMetrics.Dequeue(); pendingMetrics.Enqueue(new UiMetric{Operation=name,Milliseconds=milliseconds,NavigationId=navigationId}); } private UiMetric[] DrainMetrics() { var values=new List(); 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 long selectionNotifications,selectionReads; private long navigationExecutions;private Guid lastNavigationId;private readonly Queue completedNavigationIds=new Queue(); 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 + "\nSelection events / observations: " + selectionNotifications + " / " + selectionReads + "\nWord navigation executions: " + navigationExecutions + " · last command: " + lastNavigationId + "\nOpen sessions: " + documents.Count + "\nIPC queued: " + link.QueueDepth + "\nWord work queued: " + scheduler.Depth + "\nWord queue head: " + scheduler.HeadDescription + "\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") + "\nCompleted plain collection batches / RCW releases (process): " + chapterPlainBatches + " / " + chapterRcwReleases + "\nCompleted chapter command polls (process): " + chapterCommandPolls + "\nCompleted chapter native paragraphs / COM calls (process): " + chapterParagraphVisits + " / " + chapterComCalls + "\nChapter reads live / XML (process): " + chapterLiveReads + " / " + chapterXmlReads + "\n" + string.Join("\n",chapterMetrics.Select(p=>p.Key+": count="+p.Value[0]+", total ms="+p.Value[1].ToString("F1")+", max ms="+p.Value[2].ToString("F1"))) + "\nPlotDirector authentication: " + authenticatedState + " · " + authenticationDetail + "\nAudio Review: " + audioState + "\nCOM busy/errors: " + busyFailures + (lastWordError == null ? "" : " (last: " + lastWordError + ")") + "\nLast local protocol status: " + 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.ChapterHandoff += timing=>PostToUi(()=>{if(timing.Reason=="next-command"){Metric("chapter-handoff-wall",timing.WallMs);Metric("chapter-handoff-ipc",timing.ExchangeMs);Metric("chapter-handoff-worker-idle",timing.IdleMs);chapterCommandPolls+=timing.Polls;}else Metric("chapter-handoff-window",timing.WallMs);}); link.StateChanged += state => PostToUi(() => { ConnectionState = state; if(state!="connected") {traySupported=false;nativeChapterTextSupported=false;nativeChapterPositionsSupported=false; ClearBridgeStatus(); 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(!string.IsNullOrEmpty(message.SharedFocusStatus))PostToUi(()=>{sharedFocusStatus=message.SharedFocusStatus;invalidateRibbon?.Invoke();}); if(message.Status=="ready")PostToUi(()=>{var capabilities=(message.Capabilities??"").Split(',');traySupported=capabilities.Contains(ProtocolVersion.TrayCapability);liveChapterTextSupported=capabilities.Contains(ProtocolVersion.LiveChapterTextCapability);nativeChapterTextSupported=capabilities.Contains(ProtocolVersion.NativeChapterTextCapability);nativeChapterPositionsSupported=capabilities.Contains(ProtocolVersion.NativeChapterPositionsCapability);}); if(message.ChapterStatusProvided&&message.SessionId!=Guid.Empty)PostToUi(()=>ReceiveChapterStatus(message)); if((message.Action=="tray-sync"||message.Action=="tray-repair")&&message.Status!="ok")PostToUi(()=>{ if(active?.Session==message.SessionId)ShowChapterCommandFailure("Companion could not accept this command ("+message.Status+"). Check the current document and retry."); }); if(message.Command!=null){var delivery=Stopwatch.StartNew();PostToUi(()=>{if(message.Command.Kind=="chapter-check")Metric("chapter-command-ui-dispatch",delivery.Elapsed.TotalMilliseconds);if(message.Command.Kind=="navigate")Metric("navigation-ui-dispatch",delivery.Elapsed.TotalMilliseconds,message.Command.Id);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.Waited += (key,wait)=>{Guid session;ChapterRead read;if(key.StartsWith("chapter:",StringComparison.Ordinal)&&Guid.TryParse(key.Substring(8),out session)&&chapterReads.TryGetValue(session,out read)){read.QueueMs+=wait.TotalMs;read.QuietMs+=wait.AuthorQuietMs;read.OtherWorkMs+=wait.OtherWorkMs;read.TimerHostMs+=wait.TimerHostIdleMs;}}; scheduler.Measured += (operation, elapsed) => {lastBatchMs=elapsed;if(operation=="chapter-batch")Metric("chapter-ui-batch",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(Func 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(executingChapterRead!=null){executingChapterRead.ComCalls++;executingChapterRead.ComMs+=watch.Elapsed.TotalMilliseconds;}if(operationTimes.Count == 256)operationTimes.Dequeue(); operationTimes.Enqueue(watch.Elapsed.TotalMilliseconds);if(executingChapterRead==null||operation.StartsWith("chapter-",StringComparison.Ordinal))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++; var recognition=Stopwatch.StartNew(); 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); Metric("chapter-document-recognition",recognition.Elapsed.TotalMilliseconds); ScheduleSelection(); })) pendingOpen.Remove(document); } private void Activate(Word.Document document,Word.Window window) { activationPending=true;Open(document); ScheduleSelection(); } private void SelectionChanged(Word.Selection selection) { selectionNotifications++;MarkDeliberateFocus();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() { selectionReads++; var observationStartedUtc = DateTime.UtcNow; Word.Selection selection = null; Word.Range range = null; try { selection = Com(() => application.Selection); if(selection==null){ChangeActiveDocument(null);return;} var document = Com(() => selection.Document); if(document==null){ChangeActiveDocument(null);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;} ChangeActiveDocument(state); var focusObservation=FocusObservation(document,start,end); link.TryPost(new Message {CanSharedFocus=focusObservation.CanSharedFocus,FocusHeld=focusObservation.FocusHeld,AnyFollowingWindows=focusObservation.AnyFollowingWindows,FocusWindowID=focusObservation.FocusWindowID,FocusModeRequest=focusObservation.FocusModeRequest,DeliberateFocusSequence=focusObservation.DeliberateFocusSequence,Kind="selection",SessionId=state.Session,Revision=state.Revision,Start=start,End=end,WordSaved=saved&&Com(()=>application.BackgroundSavingStatus)==0,WordObservedUtc=observationStartedUtc,Metrics=DrainMetrics(),QueueDepth=link.QueueDepth}); // Prose is read only on an explicit Companion request; cursor observations never rescan it. } 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;} var commandClock=Stopwatch.StartNew(); if(!scheduler.Post("command:"+doc.Session,()=>{ if(command.Kind=="navigate")Metric("navigation-scheduler-wait",commandClock.Elapsed.TotalMilliseconds,command.Id); if(!documents.ContainsKey(doc.Document)||doc.Revision!=command.Revision){Reply(command,"Document changed; request again.");return;} try{ if(doc.Maintenance!=null){var previous=doc.Maintenance;scheduler.Cancel("maintenance:"+doc.Session);Reply(previous,"Stopped: superseded by a new document request. Inspect before retrying cleanup.");} if(command.Kind=="chapter-cancel"){CancelChapterRead(doc);Reply(command,"ok");return;} if(command.Kind=="chapter-check"){StartChapterRead(doc,command);return;} if(command.Kind=="chapter-recheck-revision"){InvalidateChapterProbe(doc);return;} if(command.Kind.StartsWith("maintenance-",StringComparison.Ordinal)){StartMaintenance(doc,command);return;} else if((command.Kind=="wizard-capture"||command.Kind=="paragraph-snapshot")){ CancelExtraction(doc); if(command.ParagraphTracking&&!doc.IdentityPersisted){if(Com(()=>doc.Document.ReadOnly))throw new InvalidOperationException("Save a writable copy before enabling persistent paragraph tracking.");WriteProperty(doc.Document,"PlotDirector.Native.DocumentGuid",doc.Identity.ToString("D"),Microsoft.Office.Core.MsoDocProperties.msoPropertyTypeString);doc.IdentityPersisted=true;Com(()=>{doc.Document.Saved=false;return true;});doc.WasSaved=false;} doc.End=DocumentEnd(doc.Document);if(!ScheduleSnapshot(doc,true,command.Id,command.ParagraphTracking))throw new InvalidOperationException("Word queue unavailable. Retry import from PlotDirector."); } else 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"){CancelChapterRead(doc);CancelExtraction(doc);doc.AiJob=Guid.Empty;} else if(command.Kind=="navigate"&&command.Chapter!=null){ var navigationClock=Stopwatch.StartNew(); if(!NavigationPolicy.Current(command,doc.Session,doc.Revision,doc.Identity,DateTime.UtcNow,Com(()=>doc.Document.Saved)))throw new InvalidOperationException("Navigation expired or document changed."); if(completedNavigationIds.Contains(command.Id)){Reply(command,"ok");return;} var position=command.Chapter.Start;if(position<0||position>DocumentEnd(doc.Document))throw new InvalidOperationException("Position no longer exists."); Metric("navigation-identity-and-target",navigationClock.Elapsed.TotalMilliseconds,command.Id);navigationClock.Restart();Word.Range range=null;try{range=Com(()=>doc.Document.Range(position,position));if(command.BackgroundFocus)FollowSharedFocus(doc.Document,command,range);else Com(()=>{range.Select();return true;});Metric("navigation-word-selection",navigationClock.Elapsed.TotalMilliseconds,command.Id);navigationExecutions++;lastNavigationId=command.Id;if(completedNavigationIds.Count==64)completedNavigationIds.Dequeue();completedNavigationIds.Enqueue(command.Id);}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."); var association=DocumentBinding.AssociationValue(doc.Identity,command.BookId,command.Site); WriteProperty(doc.Document,DocumentBinding.AssociationProperty,association,Microsoft.Office.Core.MsoDocProperties.msoPropertyTypeString); // Custom properties can change without Word marking the document dirty. Com(()=>{doc.Document.Saved=false;return true;}); if(ReadProperty(doc.Document,DocumentBinding.AssociationProperty)!=association||Com(()=>doc.Document.Saved)) throw new InvalidOperationException("Word did not verify the association and its unsaved state."); doc.IdentityPersisted=true;doc.BookId=command.BookId;doc.AssociationSite=command.Site;link.Register(Descriptor(doc)); Reply(command,"association-written");return; } } 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."); } // Retain no collection/range RCWs between scheduler turns. One marker per turn; typing/save/close take priority. public void RemoveLegacyMarkers() { const string title="Remove Legacy Markers"; try { var document=Com(()=>application.ActiveDocument); if(document==null||!documents.TryGetValue(document,out var doc)||closing.Contains(document)) {MessageBox.Show("Open a writable manuscript and try again.",title);return;} if(doc.Maintenance!=null){MessageBox.Show("A document maintenance operation is already running.",title);return;} StartMaintenance(doc,new AdapterCommand{Kind="maintenance-markers",SessionId=doc.Session,Revision=doc.Revision}, result=>MessageBox.Show(result,title)); } catch(Exception ex)when(ex is COMException||ex is InvalidOperationException||ex is ArgumentException) {MessageBox.Show("Word could not start marker removal. Check that the document is open and writable.",title);} } private void StartMaintenance(LocalDocument doc,AdapterCommand command, Action localResult=null) { var kind=command.Kind.Substring("maintenance-".Length); bool legacy=localResult!=null; if(!DocumentMaintenancePolicy.IsAction(kind))throw new ArgumentException("Unknown maintenance operation."); if(kind!="inspect"&&Com(()=>doc.Document.ReadOnly))throw new InvalidOperationException("Document is read-only."); CancelExtraction(doc); doc.Maintenance=command;var started=Stopwatch.StartNew(); var stage=kind=="reset"?2:0;var index=kind=="reset"?0:-1;var count=0;var inspected=0;var removed=0;var found=0;int? expectedCount=null;var report=new System.Text.StringBuilder(); void Finish(string result) { if(!legacy){Reply(command,result);return;} if(doc.Maintenance==command)doc.Maintenance=null; if(legacy) { var summary=result.StartsWith("Complete:",StringComparison.Ordinal) ? found==0?"No legacy PlotDirector markers remain.":$"Found {found} legacy PlotDirector markers. Removed {removed}. Save this document to keep the cleanup." : $"{result}\r\nFound {found} markers so far. Removed {removed}."; localResult(summary); } } // Unwrapping a control can change Word's internal positions even with identical prose. // Read the range and saved state on either side of our own STA mutation, then // leave the usual revision check in place for edits between scheduler turns. void RemoveAnchor(Action remove) { if(legacy&&(DocumentEnd(doc.Document)!=doc.End|| (doc.WasSaved&&!Com(()=>doc.Document.Saved)))) throw new InvalidOperationException("Document changed before the marker removal."); remove(); removed++; if(!legacy)return; expectedCount=count-1; doc.End=DocumentEnd(doc.Document); if(Com(()=>doc.Document.Saved))Com(()=>{doc.Document.Saved=false;return true;}); doc.WasSaved=false; if(removed==1) { doc.Revision++; command.Revision=doc.Revision; doc.NeedsSnapshot=true; doc.WordCount=null; doc.ChapterTitle=""; doc.SceneTitle=""; RegisterState(doc); } } Action next=null; next=()=>{ if(doc.Maintenance!=command)return; if((!legacy&&started.Elapsed>TimeSpan.FromMinutes(2))||!documents.ContainsKey(doc.Document)||closing.Contains(doc.Document)||doc.Revision!=command.Revision){Finish("Stopped: document closed, saved or changed. Some markers may already be removed; inspect again.");return;} try{ if(!legacy&&++inspected>100000)throw new InvalidOperationException("Maintenance limit reached; inspect again."); if(stage==0){ Word.ContentControls controls=null;Word.ContentControl marker=null; try{controls=Com(()=>doc.Document.ContentControls);count=Com(()=>controls.Count);if(index<0)index=count; if(index>count||(legacy&&expectedCount.HasValue&&expectedCount.Value!=count))throw new InvalidOperationException("Marker collection changed; inspect again."); expectedCount=count; if(index==0){stage=1;index=-1;expectedCount=null;} else{marker=Com(()=>controls[index--]);var tag=Com(()=>marker.Tag);if(legacy?DocumentMaintenancePolicy.IsLegacyControl(tag):DocumentMaintenancePolicy.OwnsControl(tag)){found++;if(report.Length<3500)report.AppendLine("Control: "+tag);if(kind is "markers" or "clean"){RemoveAnchor(()=>{ var locked=legacy&&Com(()=>marker.LockContentControl); if(locked)Com(()=>{marker.LockContentControl=false;return true;}); try{Com(()=>{marker.Delete(false);return true;});} catch{if(locked)Com(()=>{marker.LockContentControl=true;return true;});throw;} });}}} }finally{Release(marker);Release(controls);} }else if(stage==1){ Word.Bookmarks bookmarks=null;Word.Bookmark marker=null;bool hidden=false;bool read=false; try{bookmarks=Com(()=>doc.Document.Bookmarks);hidden=Com(()=>bookmarks.ShowHidden);read=true;Com(()=>{bookmarks.ShowHidden=true;return true;});count=Com(()=>bookmarks.Count);if(index<0)index=count; if(index>count||(legacy&&expectedCount.HasValue&&expectedCount.Value!=count))throw new InvalidOperationException("Bookmarks changed; inspect again."); expectedCount=count; if(index==0){stage=legacy?3:2;index=0;} else{object key=index--;marker=Com(()=>bookmarks.get_Item(ref key));var name=Com(()=>marker.Name);if(legacy?DocumentMaintenancePolicy.IsLegacyBookmark(name):DocumentMaintenancePolicy.OwnsBookmark(name)){found++;if(report.Length<3500)report.AppendLine("Bookmark: "+name);if(kind is "markers" or "clean"){RemoveAnchor(()=>Com(()=>{marker.Delete();return true;}));}}} }finally{if(read)Com(()=>{bookmarks.ShowHidden=hidden;return true;});Release(marker);Release(bookmarks);} }else if(!legacy&&indexdoc.Document.CustomDocumentProperties);dynamic collection=properties;property=Com(()=>collection[name]);dynamic item=property;Com(()=>{item.Delete();return true;});}finally{Release(property);Release(properties);}}} }else{ if(kind is "reset" or "clean"){// The live session keeps its identity until close; a new open allocates an identity when metadata is absent. doc.IdentityPersisted=false;doc.BookId=null;doc.ProjectId=null;doc.AssociationSite="";link.Register(Descriptor(doc));} if(legacy&&removed>0)Com(()=>{doc.Document.Saved=false;return true;}); Finish("Complete: "+(kind=="inspect"?"PlotDirector identifiers (only owned metadata shown)":$"{removed} owned markers removed. Prose retained. Save Word normally if you wish to keep changes.")+"\r\n"+report);return; } if(!scheduler.Post("maintenance:"+doc.Session,next))Finish("Stopped: Word queue busy; inspect before retrying."); }catch(Exception e)when(e is COMException||e is InvalidOperationException||e is ArgumentException){Finish("Stopped: Word maintenance could not complete ("+e.GetType().Name+"). Some metadata may already be removed; inspect before retrying. No prose was deliberately edited.");} }; if(!scheduler.Post("maintenance:"+doc.Session,next))Finish("Stopped: Word queue busy."); } private void Reply(AdapterCommand command,string result){var doc=documents.Values.FirstOrDefault(d=>d.Session==command.SessionId);if(doc?.Maintenance==command)doc.Maintenance=null;link.TryPost(new Message{Kind="adapter-result",SessionId=command.SessionId,Revision=command.Revision,SnapshotId=command.Id,Action=command.Kind.StartsWith("chapter-",StringComparison.Ordinal)?command.Kind:"",OperationMessage=result});} private bool ScheduleSnapshot(LocalDocument doc,bool analyse=false,Guid? snapshot=null,bool paragraphs=false) { if (doc.Extraction != null || ConnectionState != "connected") return false; doc.Extraction = new Extraction { Snapshot = snapshot??Guid.NewGuid(), Revision=doc.Revision,Analyse=analyse,Limit=doc.End,ParagraphTracking=paragraphs }; 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) { 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,identityRange=null; Word.Paragraphs paragraphs=null;Word.Paragraph paragraph=null; try { string[] tags=Array.Empty(); 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); extraction.NativeParagraphId=""; if(extraction.ParagraphTracking){ identityRange=Com(()=>doc.Document.Range(extraction.Position,Math.Min(extraction.Position+1,extraction.ParagraphEnd))); try{var xml=Com(()=>identityRange.WordOpenXML);extraction.NativeParagraphId=PlotDirector.Companion.Protocol.Manuscript.WordParagraphIdentity.Read(xml);} catch(COMException){/* XML hints are optional; context reconciliation remains conservative. */} } } 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,NativeParagraphId=extraction.NativeParagraphId,MarkerTags=tags,CompletesParagraph=end>=extraction.ParagraphEnd}}; } finally { Release(identityRange);Release(textRange);Release(paragraphRange);Release(paragraph);Release(paragraphs);Release(point); } } private string[] ReadMarkers(Word.Range range) { var tags=new List();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) { CancelChapterRead(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 bool UnchangedBeforeSave(Word.Document document,LocalDocument state){try{return Com(()=>document.Saved)&&DocumentEnd(document)==state.End;}catch(COMException){return false;}catch(InvalidOperationException){return false;}} 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)){if(UnchangedBeforeSave(document,state))return;StopAi(state,"Save or close interrupted AI analysis. Successful results retained.");scheduler.Cancel("analyse:"+state.Session);CancelExtraction(state);state.NeedsSnapshot=true;state.Revision++;state.WordCount=null;state.ChapterTitle="";state.SceneTitle="";RegisterState(state);} } 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()); private void ProbeOpenDocuments(int index,int expectedCount,int generation,HashSet 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)ChangeActiveDocument(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-timer.Interval));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();RefreshChapterTimer();} 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)); if (active == doc) invalidateRibbon(); } 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(() => 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(() => 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(()=>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(()=>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 AdapterCommand Maintenance;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,ParagraphTracking;public string NativeParagraphId="";public Message Pending;} } }