MainLoopCoordinator.cs 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. #nullable disable
  2. using System.Collections.Concurrent;
  3. namespace Terminal.Gui.App;
  4. /// <summary>
  5. /// <para>
  6. /// Coordinates the creation and startup of the main UI loop and input thread.
  7. /// </para>
  8. /// <para>
  9. /// This class bootstraps the <see cref="ApplicationMainLoop{T}"/> that handles
  10. /// UI layout, drawing, and event processing while also managing a separate thread
  11. /// for reading console input asynchronously.
  12. /// </para>
  13. /// <para>This class is designed to be managed by <see cref="ApplicationImpl"/></para>
  14. /// </summary>
  15. /// <typeparam name="TInputRecord">Type of raw input events, e.g. <see cref="ConsoleKeyInfo"/> for .NET driver</typeparam>
  16. internal class MainLoopCoordinator<TInputRecord> : IMainLoopCoordinator where TInputRecord : struct
  17. {
  18. /// <summary>
  19. /// Creates a new coordinator that will manage the main UI loop and input thread.
  20. /// </summary>
  21. /// <param name="timedEvents">Handles scheduling and execution of user timeout callbacks</param>
  22. /// <param name="inputQueue">Thread-safe queue for buffering raw console input</param>
  23. /// <param name="loop">The main application loop instance</param>
  24. /// <param name="componentFactory">Factory for creating driver-specific components (input, output, etc.)</param>
  25. public MainLoopCoordinator (
  26. ITimedEvents timedEvents,
  27. ConcurrentQueue<TInputRecord> inputQueue,
  28. IApplicationMainLoop<TInputRecord> loop,
  29. IComponentFactory<TInputRecord> componentFactory
  30. )
  31. {
  32. _timedEvents = timedEvents;
  33. _inputQueue = inputQueue;
  34. _inputProcessor = componentFactory.CreateInputProcessor (_inputQueue);
  35. _loop = loop;
  36. _componentFactory = componentFactory;
  37. }
  38. private readonly IApplicationMainLoop<TInputRecord> _loop;
  39. private readonly IComponentFactory<TInputRecord> _componentFactory;
  40. private readonly CancellationTokenSource _runCancellationTokenSource = new ();
  41. private readonly ConcurrentQueue<TInputRecord> _inputQueue;
  42. private readonly IInputProcessor _inputProcessor;
  43. private readonly object _oLockInitialization = new ();
  44. private readonly ITimedEvents _timedEvents;
  45. private readonly SemaphoreSlim _startupSemaphore = new (0, 1);
  46. private IInput<TInputRecord> _input;
  47. private Task _inputTask;
  48. private IOutput _output;
  49. private DriverImpl _driver;
  50. private bool _stopCalled;
  51. /// <summary>
  52. /// Starts the input loop thread in separate task (returning immediately).
  53. /// </summary>
  54. public async Task StartInputTaskAsync ()
  55. {
  56. Logging.Trace ("Booting... ()");
  57. _inputTask = Task.Run (RunInput);
  58. // Main loop is now booted on same thread as rest of users application
  59. BootMainLoop ();
  60. // Wait asynchronously for the semaphore or task failure.
  61. Task waitForSemaphore = _startupSemaphore.WaitAsync ();
  62. // Wait for either the semaphore to be released or the input task to crash.
  63. // ReSharper disable once UseConfigureAwaitFalse
  64. Task completedTask = await Task.WhenAny (waitForSemaphore, _inputTask);
  65. // Check if the task was the input task and if it has failed.
  66. if (completedTask == _inputTask)
  67. {
  68. if (_inputTask.IsFaulted)
  69. {
  70. throw _inputTask.Exception;
  71. }
  72. Logging.Critical ("Input loop exited during startup instead of entering read loop properly (i.e. and blocking)");
  73. }
  74. Logging.Trace ("Booting complete");
  75. }
  76. /// <inheritdoc/>
  77. public void RunIteration ()
  78. {
  79. lock (_oLockInitialization)
  80. {
  81. _loop.Iteration ();
  82. }
  83. }
  84. /// <inheritdoc/>
  85. public void Stop ()
  86. {
  87. // Ignore repeated calls to Stop - happens if user spams Application.Shutdown().
  88. if (_stopCalled)
  89. {
  90. return;
  91. }
  92. _stopCalled = true;
  93. _runCancellationTokenSource.Cancel ();
  94. _output.Dispose ();
  95. // Wait for input infinite loop to exit
  96. _inputTask.Wait ();
  97. }
  98. private void BootMainLoop ()
  99. {
  100. //Logging.Trace ($"_inputProcessor: {_inputProcessor}, _output: {_output}, _componentFactory: {_componentFactory}");
  101. lock (_oLockInitialization)
  102. {
  103. // Instance must be constructed on the thread in which it is used.
  104. _output = _componentFactory.CreateOutput ();
  105. _loop.Initialize (_timedEvents, _inputQueue, _inputProcessor, _output, _componentFactory);
  106. BuildDriverIfPossible ();
  107. }
  108. }
  109. private void BuildDriverIfPossible ()
  110. {
  111. if (_input != null && _output != null)
  112. {
  113. _driver = new (
  114. _inputProcessor,
  115. _loop.OutputBuffer,
  116. _output,
  117. _loop.AnsiRequestScheduler,
  118. _loop.SizeMonitor);
  119. Application.Driver = _driver;
  120. _startupSemaphore.Release ();
  121. Logging.Trace ($"Driver: _input: {_input}, _output: {_output}");
  122. }
  123. }
  124. /// <summary>
  125. /// INTERNAL: Runs the IInput read loop on a new thread called the "Input Thread".
  126. /// </summary>
  127. private void RunInput ()
  128. {
  129. try
  130. {
  131. lock (_oLockInitialization)
  132. {
  133. // Instance must be constructed on the thread in which it is used.
  134. _input = _componentFactory.CreateInput ();
  135. _input.Initialize (_inputQueue);
  136. // Wire up InputImpl reference for ITestableInput support
  137. if (_inputProcessor is InputProcessorImpl<TInputRecord> impl)
  138. {
  139. impl.InputImpl = _input;
  140. }
  141. BuildDriverIfPossible ();
  142. }
  143. try
  144. {
  145. _input.Run (_runCancellationTokenSource.Token);
  146. }
  147. catch (OperationCanceledException)
  148. { }
  149. _input.Dispose ();
  150. }
  151. catch (Exception e)
  152. {
  153. Logging.Critical ($"Input loop crashed: {e}");
  154. throw;
  155. }
  156. if (_stopCalled)
  157. {
  158. Logging.Information ("Input loop exited cleanly");
  159. }
  160. else
  161. {
  162. Logging.Critical ("Input loop exited early (stop not called)");
  163. }
  164. }
  165. }