SmoothAcceleratingTimeout.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. namespace Terminal.Gui.App;
  2. /// <summary>
  3. /// Timeout which accelerates slowly at first then fast up to a maximum speed.
  4. /// Use <see cref="AdvanceStage"/> to increment the stage of the timer (e.g. in
  5. /// your timer callback code).
  6. /// </summary>
  7. public class SmoothAcceleratingTimeout : Timeout
  8. {
  9. /// <summary>
  10. /// Creates a new instance of the smooth acceleration timeout.
  11. /// </summary>
  12. /// <param name="initialDelay">Delay before first tick, the longest it will ever take</param>
  13. /// <param name="minDelay">The fastest the timer can get no matter how long it runs</param>
  14. /// <param name="decayFactor">Controls how fast the timer accelerates</param>
  15. /// <param name="callback">Method to call when timer ticks</param>
  16. public SmoothAcceleratingTimeout (TimeSpan initialDelay, TimeSpan minDelay, double decayFactor, Func<bool> callback)
  17. {
  18. _initialDelay = initialDelay;
  19. _minDelay = minDelay;
  20. _decayFactor = decayFactor;
  21. Callback = callback;
  22. }
  23. private readonly TimeSpan _initialDelay;
  24. private readonly TimeSpan _minDelay;
  25. private readonly double _decayFactor;
  26. private int _stage;
  27. /// <summary>
  28. /// Advances the timer stage, this should be called from your timer callback or whenever
  29. /// you want to advance the speed.
  30. /// </summary>
  31. public void AdvanceStage () { _stage++; }
  32. /// <summary>
  33. /// Resets the timer to original speed.
  34. /// </summary>
  35. public void Reset () { _stage = 0; }
  36. /// <inheritdoc/>
  37. public override TimeSpan Span
  38. {
  39. get
  40. {
  41. double initialMs = _initialDelay.TotalMilliseconds;
  42. double minMs = _minDelay.TotalMilliseconds;
  43. double delayMs = minMs + (initialMs - minMs) * Math.Pow (_decayFactor, _stage);
  44. return TimeSpan.FromMilliseconds (delayMs);
  45. }
  46. }
  47. }