54 lines
3.7 KiB
C#
54 lines
3.7 KiB
C#
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<string,Work> work=new();private Queue<string> order=new();
|
|
private readonly int ownerThread=Environment.CurrentManagedThreadId;
|
|
private readonly Func<double> now;
|
|
private double quietStart,quietUntil,quietCompleted,activeMs,actionStarted;private bool running;
|
|
public WordAccessScheduler():this(null){}
|
|
public WordAccessScheduler(Func<double>? 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));}}
|
|
public const int Capacity=64;public int Depth=>work.Count;public long Superseded{get;private set;}
|
|
public event Action<string,double>? Measured;public event Action<string,WordQueueWait>? Waited;public event Action<Exception>? 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<string>(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();if(running||now()<quietUntil||work.Count==0)return false;
|
|
var batch=now();var chapterBatch=false;
|
|
for(var steps=0;steps<16;steps++)
|
|
{
|
|
var key=work.ContainsKey("selection")?"selection":order.Peek();var chapter=key.StartsWith("chapter:",StringComparison.Ordinal);
|
|
if(steps>0&&!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()<quietUntil||work.Count==0||work.ContainsKey("selection"))break;
|
|
}
|
|
if(chapterBatch)Measured?.Invoke("chapter-batch",now()-batch);return true;
|
|
}
|
|
}
|