WindowsMainLoop.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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 BlockingCollection<WindowsConsole.InputRecord> _resultQueue = new (new ConcurrentQueue<WindowsConsole.InputRecord> ());
  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. public AnsiEscapeSequenceRequests EscSeqRequests { get; } = new ();
  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. #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. if (_resultQueue.TryTake (out WindowsConsole.InputRecord dequeueResult))
  92. {
  93. ((WindowsDriver)_consoleDriver).ProcessInput (dequeueResult);
  94. }
  95. }
  96. #if HACK_CHECK_WINCHANGED
  97. if (_winChanged)
  98. {
  99. _winChanged = false;
  100. WinChanged?.Invoke (this, new SizeChangedEventArgs (_windowSize));
  101. }
  102. #endif
  103. }
  104. void IMainLoopDriver.TearDown ()
  105. {
  106. _inputHandlerTokenSource.Cancel ();
  107. _inputHandlerTokenSource.Dispose ();
  108. if (_winConsole is { })
  109. {
  110. var numOfEvents = _winConsole.GetNumberOfConsoleInputEvents ();
  111. if (numOfEvents > 0)
  112. {
  113. _winConsole.FlushConsoleInputBuffer ();
  114. //Debug.WriteLine ($"Flushed {numOfEvents} events.");
  115. }
  116. }
  117. _resultQueue.Dispose ();
  118. _eventReadyTokenSource.Cancel ();
  119. _eventReadyTokenSource.Dispose ();
  120. _eventReady.Dispose ();
  121. #if HACK_CHECK_WINCHANGED
  122. _winChange?.Dispose ();
  123. #endif
  124. _mainLoop = null;
  125. }
  126. internal bool _forceRead;
  127. private void WindowsInputHandler ()
  128. {
  129. while (_mainLoop is { })
  130. {
  131. try
  132. {
  133. if (_inputHandlerTokenSource.IsCancellationRequested)
  134. {
  135. return;
  136. }
  137. if (_resultQueue?.Count == 0 || _forceRead)
  138. {
  139. WindowsConsole.InputRecord? result = _winConsole!.DequeueInput ();
  140. if (result.HasValue)
  141. {
  142. _resultQueue!.Add (result.Value);
  143. }
  144. }
  145. if (!_inputHandlerTokenSource.IsCancellationRequested && _resultQueue?.Count > 0)
  146. {
  147. _eventReady.Set ();
  148. }
  149. }
  150. catch (OperationCanceledException)
  151. {
  152. return;
  153. }
  154. }
  155. }
  156. #if HACK_CHECK_WINCHANGED
  157. private readonly ManualResetEventSlim _winChange = new (false);
  158. private bool _winChanged;
  159. private Size _windowSize;
  160. private void CheckWinChange ()
  161. {
  162. while (_mainLoop is { })
  163. {
  164. _winChange.Wait ();
  165. _winChange.Reset ();
  166. // Check if the window size changed every half second.
  167. // We do this to minimize the weird tearing seen on Windows when resizing the console
  168. while (_mainLoop is { })
  169. {
  170. Task.Delay (500).Wait ();
  171. _windowSize = _winConsole.GetConsoleBufferWindow (out _);
  172. if (_windowSize != Size.Empty
  173. && (_windowSize.Width != _consoleDriver.Cols
  174. || _windowSize.Height != _consoleDriver.Rows))
  175. {
  176. break;
  177. }
  178. }
  179. _winChanged = true;
  180. _eventReady.Set ();
  181. }
  182. }
  183. #endif
  184. }