FakeMainLoop.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System;
  2. using System.Threading;
  3. namespace Terminal.Gui {
  4. /// <summary>
  5. /// Mainloop intended to be used with the .NET System.Console API, and can
  6. /// be used on Windows and Unix, it is cross platform but lacks things like
  7. /// file descriptor monitoring.
  8. /// </summary>
  9. /// <remarks>
  10. /// This implementation is used for FakeDriver.
  11. /// </remarks>
  12. public class FakeMainLoop : IMainLoopDriver {
  13. AutoResetEvent keyReady = new AutoResetEvent (false);
  14. AutoResetEvent waitForProbe = new AutoResetEvent (false);
  15. ConsoleKeyInfo? keyResult = null;
  16. MainLoop mainLoop;
  17. Func<ConsoleKeyInfo> consoleKeyReaderFn = null;
  18. /// <summary>
  19. /// Invoked when a Key is pressed.
  20. /// </summary>
  21. public Action<ConsoleKeyInfo> KeyPressed;
  22. /// <summary>
  23. /// Initializes the class.
  24. /// </summary>
  25. /// <remarks>
  26. /// Passing a consoleKeyReaderfn is provided to support unit test scenarios.
  27. /// </remarks>
  28. /// <param name="consoleKeyReaderFn">The method to be called to get a key from the console.</param>
  29. public FakeMainLoop (Func<ConsoleKeyInfo> consoleKeyReaderFn = null)
  30. {
  31. if (consoleKeyReaderFn == null) {
  32. throw new ArgumentNullException ("key reader function must be provided.");
  33. }
  34. this.consoleKeyReaderFn = consoleKeyReaderFn;
  35. }
  36. void WindowsKeyReader ()
  37. {
  38. while (true) {
  39. waitForProbe.WaitOne ();
  40. keyResult = consoleKeyReaderFn ();
  41. keyReady.Set ();
  42. }
  43. }
  44. void IMainLoopDriver.Setup (MainLoop mainLoop)
  45. {
  46. this.mainLoop = mainLoop;
  47. Thread readThread = new Thread (WindowsKeyReader);
  48. readThread.Start ();
  49. }
  50. void IMainLoopDriver.Wakeup ()
  51. {
  52. }
  53. bool IMainLoopDriver.EventsPending (bool wait)
  54. {
  55. long now = DateTime.UtcNow.Ticks;
  56. int waitTimeout;
  57. if (mainLoop.timeouts.Count > 0) {
  58. waitTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  59. if (waitTimeout < 0)
  60. return true;
  61. } else
  62. waitTimeout = -1;
  63. if (!wait)
  64. waitTimeout = 0;
  65. keyResult = null;
  66. waitForProbe.Set ();
  67. keyReady.WaitOne (waitTimeout);
  68. return keyResult.HasValue;
  69. }
  70. void IMainLoopDriver.MainIteration ()
  71. {
  72. if (keyResult.HasValue) {
  73. KeyPressed?.Invoke (keyResult.Value);
  74. keyResult = null;
  75. }
  76. }
  77. }
  78. }