WindowsMainLoop.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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!.TimedEvents.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.TimedEvents.CheckTimersAndIdleHandlers (out _) || _winChanged;
  86. #else
  87. return _resultQueue.Count > 0 || _mainLoop.TimedEvents.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. foreach (var i in ((WindowsDriver)_consoleDriver).ShouldReleaseParserHeldKeys ())
  98. {
  99. ((WindowsDriver)_consoleDriver).ProcessInputAfterParsing (i);
  100. }
  101. while (!ConsoleDriver.RunningUnitTests && _resultQueue.TryDequeue (out WindowsConsole.InputRecord inputRecords))
  102. {
  103. ((WindowsDriver)_consoleDriver).ProcessInput (inputRecords);
  104. }
  105. #if HACK_CHECK_WINCHANGED
  106. if (_winChanged)
  107. {
  108. _winChanged = false;
  109. WinChanged?.Invoke (this, new SizeChangedEventArgs (_windowSize));
  110. }
  111. #endif
  112. }
  113. void IMainLoopDriver.TearDown ()
  114. {
  115. _inputHandlerTokenSource.Cancel ();
  116. _inputHandlerTokenSource.Dispose ();
  117. if (_winConsole is { })
  118. {
  119. var numOfEvents = _winConsole.GetNumberOfConsoleInputEvents ();
  120. if (numOfEvents > 0)
  121. {
  122. _winConsole.FlushConsoleInputBuffer ();
  123. //Debug.WriteLine ($"Flushed {numOfEvents} events.");
  124. }
  125. }
  126. _waitForProbe.Dispose ();
  127. _resultQueue.Clear ();
  128. _eventReadyTokenSource.Cancel ();
  129. _eventReadyTokenSource.Dispose ();
  130. _eventReady.Dispose ();
  131. #if HACK_CHECK_WINCHANGED
  132. _winChange?.Dispose ();
  133. #endif
  134. _mainLoop = null;
  135. }
  136. private void WindowsInputHandler ()
  137. {
  138. while (_mainLoop is { })
  139. {
  140. try
  141. {
  142. if (_inputHandlerTokenSource.IsCancellationRequested)
  143. {
  144. try
  145. {
  146. _waitForProbe.Wait (_inputHandlerTokenSource.Token);
  147. }
  148. catch (Exception ex)
  149. {
  150. if (ex is OperationCanceledException or ObjectDisposedException)
  151. {
  152. return;
  153. }
  154. throw;
  155. }
  156. _waitForProbe.Reset ();
  157. }
  158. ProcessInputQueue ();
  159. }
  160. catch (OperationCanceledException)
  161. {
  162. return;
  163. }
  164. }
  165. }
  166. private void ProcessInputQueue ()
  167. {
  168. if (_resultQueue?.Count == 0)
  169. {
  170. WindowsConsole.InputRecord? result = _winConsole!.DequeueInput ();
  171. if (result.HasValue)
  172. {
  173. _resultQueue!.Enqueue (result.Value);
  174. _eventReady.Set ();
  175. }
  176. }
  177. }
  178. #if HACK_CHECK_WINCHANGED
  179. private readonly ManualResetEventSlim _winChange = new (false);
  180. private bool _winChanged;
  181. private Size _windowSize;
  182. private void CheckWinChange ()
  183. {
  184. while (_mainLoop is { })
  185. {
  186. _winChange.Wait ();
  187. _winChange.Reset ();
  188. // Check if the window size changed every half second.
  189. // We do this to minimize the weird tearing seen on Windows when resizing the console
  190. while (_mainLoop is { })
  191. {
  192. Task.Delay (500).Wait ();
  193. _windowSize = _winConsole.GetConsoleBufferWindow (out _);
  194. if (_windowSize != Size.Empty
  195. && (_windowSize.Width != _consoleDriver.Cols
  196. || _windowSize.Height != _consoleDriver.Rows))
  197. {
  198. break;
  199. }
  200. }
  201. _winChanged = true;
  202. _eventReady.Set ();
  203. }
  204. }
  205. #endif
  206. }