WindowsMainLoop.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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 ConsoleDriver _consoleDriver;
  18. private readonly ManualResetEventSlim _eventReady = new (false);
  19. // The records that we keep fetching
  20. private readonly ConcurrentQueue<WindowsConsole.InputRecord> _resultQueue = new ();
  21. ManualResetEventSlim IMainLoopDriver._waitForInput { get; set; } = 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 (ConsoleDriver 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. ((IMainLoopDriver)this)._waitForInput.Set ();
  51. #if HACK_CHECK_WINCHANGED
  52. _winChange.Set ();
  53. #endif
  54. if (_resultQueue.Count > 0 || _mainLoop!.CheckTimersAndIdleHandlers (out int waitTimeout))
  55. {
  56. return true;
  57. }
  58. try
  59. {
  60. if (!_eventReadyTokenSource.IsCancellationRequested)
  61. {
  62. // Note: ManualResetEventSlim.Wait will wait indefinitely if the timeout is -1. The timeout is -1 when there
  63. // are no timers, but there IS an idle handler waiting.
  64. _eventReady.Wait (waitTimeout, _eventReadyTokenSource.Token);
  65. }
  66. }
  67. catch (OperationCanceledException)
  68. {
  69. return true;
  70. }
  71. finally
  72. {
  73. _eventReady.Reset ();
  74. }
  75. if (!_eventReadyTokenSource.IsCancellationRequested)
  76. {
  77. #if HACK_CHECK_WINCHANGED
  78. return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _) || _winChanged;
  79. #else
  80. return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _);
  81. #endif
  82. }
  83. _eventReadyTokenSource.Dispose ();
  84. _eventReadyTokenSource = new CancellationTokenSource ();
  85. // If cancellation was requested then always return true
  86. return true;
  87. }
  88. void IMainLoopDriver.Iteration ()
  89. {
  90. while (_resultQueue.TryDequeue (out WindowsConsole.InputRecord inputRecords))
  91. {
  92. ((WindowsDriver)_consoleDriver).ProcessInput (inputRecords);
  93. }
  94. #if HACK_CHECK_WINCHANGED
  95. if (_winChanged)
  96. {
  97. _winChanged = false;
  98. WinChanged?.Invoke (this, new SizeChangedEventArgs (_windowSize));
  99. }
  100. #endif
  101. }
  102. void IMainLoopDriver.TearDown ()
  103. {
  104. _inputHandlerTokenSource.Cancel ();
  105. _inputHandlerTokenSource.Dispose ();
  106. if (_winConsole is { })
  107. {
  108. var numOfEvents = _winConsole.GetNumberOfConsoleInputEvents ();
  109. if (numOfEvents > 0)
  110. {
  111. _winConsole.FlushConsoleInputBuffer ();
  112. //Debug.WriteLine ($"Flushed {numOfEvents} events.");
  113. }
  114. }
  115. ((IMainLoopDriver)this)._waitForInput?.Dispose ();
  116. _resultQueue.Clear ();
  117. _eventReadyTokenSource.Cancel ();
  118. _eventReadyTokenSource.Dispose ();
  119. _eventReady.Dispose ();
  120. #if HACK_CHECK_WINCHANGED
  121. _winChange?.Dispose ();
  122. #endif
  123. _mainLoop = null;
  124. }
  125. public bool _forceRead { get; set; }
  126. private void WindowsInputHandler ()
  127. {
  128. while (_mainLoop is { })
  129. {
  130. try
  131. {
  132. if (_inputHandlerTokenSource.IsCancellationRequested && !_forceRead)
  133. {
  134. try
  135. {
  136. ((IMainLoopDriver)this)._waitForInput.Wait (_inputHandlerTokenSource.Token);
  137. }
  138. catch (Exception ex)
  139. {
  140. if (ex is OperationCanceledException or ObjectDisposedException)
  141. {
  142. return;
  143. }
  144. throw;
  145. }
  146. ((IMainLoopDriver)this)._waitForInput.Reset ();
  147. }
  148. ProcessInputQueue ();
  149. }
  150. catch (OperationCanceledException)
  151. {
  152. return;
  153. }
  154. }
  155. }
  156. private void ProcessInputQueue ()
  157. {
  158. if (_resultQueue?.Count == 0 || _forceRead)
  159. {
  160. WindowsConsole.InputRecord? result = _winConsole!.DequeueInput ();
  161. if (result.HasValue)
  162. {
  163. _resultQueue!.Enqueue (result.Value);
  164. _eventReady.Set ();
  165. }
  166. }
  167. }
  168. #if HACK_CHECK_WINCHANGED
  169. private readonly ManualResetEventSlim _winChange = new (false);
  170. private bool _winChanged;
  171. private Size _windowSize;
  172. private void CheckWinChange ()
  173. {
  174. while (_mainLoop is { })
  175. {
  176. _winChange.Wait ();
  177. _winChange.Reset ();
  178. // Check if the window size changed every half second.
  179. // We do this to minimize the weird tearing seen on Windows when resizing the console
  180. while (_mainLoop is { })
  181. {
  182. Task.Delay (500).Wait ();
  183. _windowSize = _winConsole.GetConsoleBufferWindow (out _);
  184. if (_windowSize != Size.Empty
  185. && (_windowSize.Width != _consoleDriver.Cols
  186. || _windowSize.Height != _consoleDriver.Rows))
  187. {
  188. break;
  189. }
  190. }
  191. _winChanged = true;
  192. _eventReady.Set ();
  193. }
  194. }
  195. #endif
  196. }