WindowsMainLoop.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. internal 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 (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. public AnsiEscapeSequenceRequests EscSeqRequests { get; } = new ();
  36. void IMainLoopDriver.Setup (MainLoop mainLoop)
  37. {
  38. _mainLoop = mainLoop;
  39. if (ConsoleDriver.RunningUnitTests)
  40. {
  41. return;
  42. }
  43. Task.Run (WindowsInputHandler, _inputHandlerTokenSource.Token);
  44. #if HACK_CHECK_WINCHANGED
  45. Task.Run (CheckWinChange);
  46. #endif
  47. }
  48. void IMainLoopDriver.Wakeup () { _eventReady.Set (); }
  49. bool IMainLoopDriver.EventsPending ()
  50. {
  51. _waitForProbe.Set ();
  52. #if HACK_CHECK_WINCHANGED
  53. _winChange.Set ();
  54. #endif
  55. if (_mainLoop!.CheckTimersAndIdleHandlers (out int waitTimeout))
  56. {
  57. return true;
  58. }
  59. try
  60. {
  61. if (!_eventReadyTokenSource.IsCancellationRequested)
  62. {
  63. // Note: ManualResetEventSlim.Wait will wait indefinitely if the timeout is -1. The timeout is -1 when there
  64. // are no timers, but there IS an idle handler waiting.
  65. _eventReady.Wait (waitTimeout, _eventReadyTokenSource.Token);
  66. }
  67. }
  68. catch (OperationCanceledException)
  69. {
  70. return true;
  71. }
  72. finally
  73. {
  74. _eventReady.Reset ();
  75. }
  76. if (!_eventReadyTokenSource.IsCancellationRequested)
  77. {
  78. #if HACK_CHECK_WINCHANGED
  79. return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _) || _winChanged;
  80. #else
  81. return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _);
  82. #endif
  83. }
  84. _eventReadyTokenSource.Dispose ();
  85. _eventReadyTokenSource = new CancellationTokenSource ();
  86. return true;
  87. }
  88. void IMainLoopDriver.Iteration ()
  89. {
  90. while (_resultQueue.Count > 0)
  91. {
  92. if (_resultQueue.TryDequeue (out WindowsConsole.InputRecord []? inputRecords))
  93. {
  94. if (inputRecords is { Length: > 0 })
  95. {
  96. ((WindowsDriver)_consoleDriver).ProcessInput (inputRecords [0]);
  97. }
  98. }
  99. }
  100. #if HACK_CHECK_WINCHANGED
  101. if (_winChanged)
  102. {
  103. _winChanged = false;
  104. WinChanged?.Invoke (this, new SizeChangedEventArgs (_windowSize));
  105. }
  106. #endif
  107. }
  108. void IMainLoopDriver.TearDown ()
  109. {
  110. _inputHandlerTokenSource.Cancel ();
  111. _inputHandlerTokenSource.Dispose ();
  112. if (_winConsole is { })
  113. {
  114. var numOfEvents = _winConsole.GetNumberOfConsoleInputEvents ();
  115. if (numOfEvents > 0)
  116. {
  117. _winConsole.FlushConsoleInputBuffer ();
  118. //Debug.WriteLine ($"Flushed {numOfEvents} events.");
  119. }
  120. }
  121. _waitForProbe.Dispose ();
  122. _resultQueue.Clear ();
  123. _eventReadyTokenSource.Cancel ();
  124. _eventReadyTokenSource.Dispose ();
  125. _eventReady.Dispose ();
  126. #if HACK_CHECK_WINCHANGED
  127. _winChange?.Dispose ();
  128. #endif
  129. _mainLoop = null;
  130. }
  131. internal bool _forceRead;
  132. private void WindowsInputHandler ()
  133. {
  134. while (_mainLoop is { })
  135. {
  136. try
  137. {
  138. if (!_inputHandlerTokenSource.IsCancellationRequested && !_forceRead)
  139. {
  140. _waitForProbe.Wait (_inputHandlerTokenSource.Token);
  141. }
  142. }
  143. catch (OperationCanceledException)
  144. {
  145. // Wakes the _waitForProbe if it's waiting
  146. _waitForProbe.Set ();
  147. return;
  148. }
  149. finally
  150. {
  151. // If IsCancellationRequested is true the code after
  152. // the `finally` block will not be executed.
  153. if (!_inputHandlerTokenSource.IsCancellationRequested)
  154. {
  155. _waitForProbe.Reset ();
  156. }
  157. }
  158. if (_resultQueue?.Count == 0 || _forceRead)
  159. {
  160. while (!_inputHandlerTokenSource.IsCancellationRequested)
  161. {
  162. WindowsConsole.InputRecord [] inpRec = _winConsole.ReadConsoleInput ();
  163. if (inpRec is { })
  164. {
  165. _resultQueue!.Enqueue (inpRec);
  166. break;
  167. }
  168. if (!_forceRead)
  169. {
  170. try
  171. {
  172. Task.Delay (100, _inputHandlerTokenSource.Token).Wait (_inputHandlerTokenSource.Token);
  173. }
  174. catch (OperationCanceledException)
  175. { }
  176. }
  177. }
  178. }
  179. _eventReady.Set ();
  180. }
  181. }
  182. #if HACK_CHECK_WINCHANGED
  183. private readonly ManualResetEventSlim _winChange = new (false);
  184. private bool _winChanged;
  185. private Size _windowSize;
  186. private void CheckWinChange ()
  187. {
  188. while (_mainLoop is { })
  189. {
  190. _winChange.Wait ();
  191. _winChange.Reset ();
  192. // Check if the window size changed every half second.
  193. // We do this to minimize the weird tearing seen on Windows when resizing the console
  194. while (_mainLoop is { })
  195. {
  196. Task.Delay (500).Wait ();
  197. _windowSize = _winConsole.GetConsoleBufferWindow (out _);
  198. if (_windowSize != Size.Empty
  199. && (_windowSize.Width != _consoleDriver.Cols
  200. || _windowSize.Height != _consoleDriver.Rows))
  201. {
  202. break;
  203. }
  204. }
  205. _winChanged = true;
  206. _eventReady.Set ();
  207. }
  208. }
  209. #endif
  210. }