using System.Diagnostics; namespace PlotDirector.Companion.Client; // Pumped by a Windows Forms timer on Word's original UI thread. Actions never // execute on producers/Task.Run. Each action must itself bound its COM access. public sealed class WordAccessScheduler { private readonly Dictionary work = new(); private Queue order = new(); private readonly int ownerThread = Environment.CurrentManagedThreadId; private DateTime quietUntil; public const int Capacity = 64; public int Depth => work.Count; public long Superseded { get; private set; } public event Action? Measured; 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); } work[key] = action; 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 quietPeriod) { AssertOwner(); quietUntil = DateTime.UtcNow + quietPeriod; } public bool Pump() { AssertOwner(); if (DateTime.UtcNow < quietUntil || work.Count == 0) return false; var key = work.ContainsKey("selection") ? "selection" : order.Peek(); var action = work[key]; Cancel(key); var watch = Stopwatch.StartNew(); try { action(); } catch (Exception ex) { Failed?.Invoke(ex); } finally { Measured?.Invoke(key.Split(':')[0], watch.Elapsed.TotalMilliseconds); } return true; } }