WindowsMainLoop.cs 6.1 KB

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