using System.Diagnostics; namespace PlotDirector.Companion.Client; public sealed class WordQueueWait { public double TotalMs{get;set;}public double AuthorQuietMs{get;set;}public double OtherWorkMs{get;set;}public double TimerHostIdleMs{get;set;} } // Pumped only on Word's original UI thread. The optional monotonic clock supports // deterministic scheduling tests; actions still bound their own COM access. public sealed class WordAccessScheduler { private sealed class Work(Action action,double queued,double active,double quiet) {public Action Action=action;public double Queued=queued,Active=active,Quiet=quiet;} private readonly Dictionary work=new();private Queue order=new(); private readonly int ownerThread=Environment.CurrentManagedThreadId; private readonly Func now; private double quietStart,quietUntil,quietCompleted,activeMs,actionStarted;private bool running; public WordAccessScheduler():this(null){} public WordAccessScheduler(Func? milliseconds){now=milliseconds??(()=>Stopwatch.GetTimestamp()*1000d/Stopwatch.Frequency);} private double QuietAt(double time)=>quietCompleted+Math.Max(0,Math.Min(time,quietUntil)-quietStart); private double ActiveAt(double time)=>activeMs+(running?time-actionStarted:0); public bool HasRunnableChapterWork{get{AssertOwner();return now()>=quietUntil&&work.Keys.Any(k=>k.StartsWith("chapter:",StringComparison.Ordinal));}} private double? lastWake; public string HeadDescription { get { AssertOwner(); var time=now(); var key=work.ContainsKey("selection")?"selection":order.Count>0?order.Peek():null; var head=key==null?"empty":$"{key.Split(':')[0]}, age {Math.Max(0,time-work[key].Queued):F0} ms"; return head+(lastWake.HasValue?$"; last scheduler wake {Math.Max(0,time-lastWake.Value):F0} ms ago":"; scheduler has not woken"); } } public const int Capacity=64;public int Depth=>work.Count;public long Superseded{get;private set;} public event Action? Measured;public event Action? Waited;public event Action? Failed; private void AssertOwner(){if(Environment.CurrentManagedThreadId!=ownerThread)throw new InvalidOperationException("Word work must stay on its owning UI thread.");} public bool Post(string key,Action action) { AssertOwner();if(work.ContainsKey(key))Superseded++;else{if(work.Count>=Capacity)return false;order.Enqueue(key);} var time=now();work[key]=new(action,time,ActiveAt(time),QuietAt(time));return true; } public void Cancel(string key){AssertOwner();work.Remove(key);order=new Queue(order.Where(k=>k!=key));} public void Clear(){AssertOwner();work.Clear();order.Clear();} public void PrioritizeAuthor(TimeSpan period){AssertOwner();var time=now();quietCompleted=QuietAt(time);quietStart=time;quietUntil=time+period.TotalMilliseconds;} public bool Pump() { AssertOwner();lastWake=now();if(running||lastWake.Value0&&!chapter)break;if(chapter)chapterBatch=true; var item=work[key];Cancel(key);var time=now();var delay=Math.Max(0,time-item.Queued); var quiet=Math.Min(delay,Math.Max(0,QuietAt(time)-item.Quiet)); var other=Math.Min(delay-quiet,Math.Max(0,ActiveAt(time)-item.Active)); Waited?.Invoke(key,new(){TotalMs=delay,AuthorQuietMs=quiet,OtherWorkMs=other,TimerHostIdleMs=Math.Max(0,delay-quiet-other)}); actionStarted=now();running=true; try{item.Action();}catch(Exception ex){Failed?.Invoke(ex);} finally{var duration=now()-actionStarted;activeMs+=duration;running=false;Measured?.Invoke(key.Split(':')[0],duration);} if(!chapter||now()-batch>=15||now()