WindowsMainLoop.cs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. #nullable enable
  2. using System.Collections.Concurrent;
  3. namespace Terminal.Gui;
  4. /// <summary>
  5. /// Mainloop intended to be used with the <see cref="WindowsDriver"/>, and can
  6. /// only be used on Windows.
  7. /// </summary>
  8. /// <remarks>
  9. /// This implementation is used for WindowsDriver.
  10. /// </remarks>
  11. internal class WindowsMainLoop : IMainLoopDriver
  12. {
  13. /// <summary>
  14. /// Invoked when the window is changed.
  15. /// </summary>
  16. public EventHandler<SizeChangedEventArgs>? WinChanged;
  17. private readonly IConsoleDriver _consoleDriver;
  18. private readonly ManualResetEventSlim _eventReady = new (false);
  19. // The records that we keep fetching
  20. private readonly ConcurrentQueue<WindowsConsole.InputRecord> _resultQueue = new ();
  21. private readonly ManualResetEventSlim _waitForProbe = new (false);
  22. private readonly WindowsConsole? _winConsole;
  23. private CancellationTokenSource _eventReadyTokenSource = new ();
  24. private readonly CancellationTokenSource _inputHandlerTokenSource = new ();
  25. private MainLoop? _mainLoop;
  26. public WindowsMainLoop (IConsoleDriver consoleDriver)
  27. {
  28. _consoleDriver = consoleDriver ?? throw new ArgumentNullException (nameof (consoleDriver));
  29. if (!ConsoleDriver.RunningUnitTests)
  30. {
  31. _winConsole = ((WindowsDriver)consoleDriver).WinConsole;
  32. _winConsole!._mainLoop = this;
  33. }
  34. }
  35. void IMainLoopDriver.Setup (MainLoop mainLoop)
  36. {
  37. _mainLoop = mainLoop;
  38. if (ConsoleDriver.RunningUnitTests)
  39. {
  40. return;
  41. }
  42. Task.Run (WindowsInputHandler, _inputHandlerTokenSource.Token);
  43. #if HACK_CHECK_WINCHANGED
  44. Task.Run (CheckWinChange);
  45. #endif
  46. }
  47. void IMainLoopDriver.Wakeup () { _eventReady.Set (); }
  48. bool IMainLoopDriver.EventsPending ()
  49. {
  50. if (ConsoleDriver.RunningUnitTests)
  51. {
  52. return true;
  53. }
  54. _waitForProbe.Set ();
  55. #if HACK_CHECK_WINCHANGED
  56. _winChange.Set ();
  57. #endif
  58. if (_resultQueue.Count > 0 || _mainLoop!.CheckTimersAndIdleHandlers (out int waitTimeout))
  59. {
  60. return true;
  61. }
  62. try
  63. {
  64. if (!_eventReadyTokenSource.IsCancellationRequested)
  65. {
  66. // Note: ManualResetEventSlim.Wait will wait indefinitely if the timeout is -1. The timeout is -1 when there
  67. // are no timers, but there IS an idle handler waiting.
  68. _eventReady.Wait (waitTimeout, _eventReadyTokenSource.Token);
  69. }
  70. }
  71. catch (OperationCanceledException)
  72. {
  73. return true;
  74. }
  75. finally
  76. {
  77. if (!_eventReadyTokenSource.IsCancellationRequested)
  78. {
  79. _eventReady.Reset ();
  80. }
  81. }
  82. if (!_eventReadyTokenSource.IsCancellationRequested)
  83. {
  84. #if HACK_CHECK_WINCHANGED
  85. return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _) || _winChanged;
  86. #else
  87. return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _);
  88. #endif
  89. }
  90. _eventReadyTokenSource.Dispose ();
  91. _eventReadyTokenSource = new CancellationTokenSource ();
  92. // If cancellation was requested then always return true
  93. return true;
  94. }
  95. void IMainLoopDriver.Iteration ()
  96. {
  97. while (!ConsoleDriver.RunningUnitTests && _resultQueue.TryDequeue (out WindowsConsole.InputRecord inputRecords))
  98. {
  99. ((WindowsDriver)_consoleDriver).ProcessInput (inputRecords);
  100. }
  101. #if HACK_CHECK_WINCHANGED
  102. if (_winChanged)
  103. {
  104. _winChanged = false;
  105. WinChanged?.Invoke (this, new SizeChangedEventArgs (_windowSize));
  106. }
  107. #endif
  108. }
  109. void IMainLoopDriver.TearDown ()
  110. {
  111. _inputHandlerTokenSource.Cancel ();
  112. _inputHandlerTokenSource.Dispose ();
  113. if (_winConsole is { })
  114. {
  115. var numOfEvents = _winConsole.GetNumberOfConsoleInputEvents ();
  116. if (numOfEvents > 0)
  117. {
  118. _winConsole.FlushConsoleInputBuffer ();
  119. //Debug.WriteLine ($"Flushed {numOfEvents} events.");
  120. }
  121. }
  122. _waitForProbe.Dispose ();
  123. _resultQueue.Clear ();
  124. _eventReadyTokenSource.Cancel ();
  125. _eventReadyTokenSource.Dispose ();
  126. _eventReady.Dispose ();
  127. #if HACK_CHECK_WINCHANGED
  128. _winChange?.Dispose ();
  129. #endif
  130. _mainLoop = null;
  131. }
  132. private void WindowsInputHandler ()
  133. {
  134. while (_mainLoop is { })
  135. {
  136. try
  137. {
  138. if (_inputHandlerTokenSource.IsCancellationRequested)
  139. {
  140. try
  141. {
  142. _waitForProbe.Wait (_inputHandlerTokenSource.Token);
  143. }
  144. catch (Exception ex)
  145. {
  146. if (ex is OperationCanceledException or ObjectDisposedException)
  147. {
  148. return;
  149. }
  150. throw;
  151. }
  152. _waitForProbe.Reset ();
  153. }
  154. ProcessInputQueue ();
  155. }
  156. catch (OperationCanceledException)
  157. {
  158. return;
  159. }
  160. }
  161. }
  162. private void ProcessInputQueue ()
  163. {
  164. if (_resultQueue?.Count == 0)
  165. {
  166. WindowsConsole.InputRecord? result = _winConsole!.DequeueInput ();
  167. if (result.HasValue)
  168. {
  169. _resultQueue!.Enqueue (result.Value);
  170. _eventReady.Set ();
  171. }
  172. }
  173. }
  174. #if HACK_CHECK_WINCHANGED
  175. private readonly ManualResetEventSlim _winChange = new (false);
  176. private bool _winChanged;
  177. private Size _windowSize;
  178. private void CheckWinChange ()
  179. {
  180. while (_mainLoop is { })
  181. {
  182. _winChange.Wait ();
  183. _winChange.Reset ();
  184. // Check if the window size changed every half second.
  185. // We do this to minimize the weird tearing seen on Windows when resizing the console
  186. while (_mainLoop is { })
  187. {
  188. Task.Delay (500).Wait ();
  189. _windowSize = _winConsole.GetConsoleBufferWindow (out _);
  190. if (_windowSize != Size.Empty
  191. && (_windowSize.Width != _consoleDriver.Cols
  192. || _windowSize.Height != _consoleDriver.Rows))
  193. {
  194. break;
  195. }
  196. }
  197. _winChanged = true;
  198. _eventReady.Set ();
  199. }
  200. }
  201. #endif
  202. }