MainLoopCoordinator.cs 6.3 KB

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