WindowsMainLoop.cs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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 (OperationCanceledException)
  139. {
  140. return;
  141. }
  142. ((IMainLoopDriver)this)._waitForInput.Reset ();
  143. }
  144. ProcessInputQueue ();
  145. }
  146. catch (OperationCanceledException)
  147. {
  148. return;
  149. }
  150. }
  151. }
  152. private void ProcessInputQueue ()
  153. {
  154. if (_resultQueue?.Count == 0 || _forceRead)
  155. {
  156. WindowsConsole.InputRecord? result = _winConsole!.DequeueInput ();
  157. if (result.HasValue)
  158. {
  159. _resultQueue!.Enqueue (result.Value);
  160. _eventReady.Set ();
  161. }
  162. }
  163. }
  164. #if HACK_CHECK_WINCHANGED
  165. private readonly ManualResetEventSlim _winChange = new (false);
  166. private bool _winChanged;
  167. private Size _windowSize;
  168. private void CheckWinChange ()
  169. {
  170. while (_mainLoop is { })
  171. {
  172. _winChange.Wait ();
  173. _winChange.Reset ();
  174. // Check if the window size changed every half second.
  175. // We do this to minimize the weird tearing seen on Windows when resizing the console
  176. while (_mainLoop is { })
  177. {
  178. Task.Delay (500).Wait ();
  179. _windowSize = _winConsole.GetConsoleBufferWindow (out _);
  180. if (_windowSize != Size.Empty
  181. && (_windowSize.Width != _consoleDriver.Cols
  182. || _windowSize.Height != _consoleDriver.Rows))
  183. {
  184. break;
  185. }
  186. }
  187. _winChanged = true;
  188. _eventReady.Set ();
  189. }
  190. }
  191. #endif
  192. }