WindowsMainLoop.cs 7.0 KB

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