MainLoopCoordinator.cs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. using System.Collections.Concurrent;
  2. using Microsoft.Extensions.Logging;
  3. namespace Terminal.Gui;
  4. /// <summary>
  5. /// <para>
  6. /// Handles creating the input loop thread and bootstrapping the
  7. /// <see cref="MainLoop{T}"/> that handles layout/drawing/events etc.
  8. /// </para>
  9. /// <para>This class is designed to be managed by <see cref="ApplicationV2"/></para>
  10. /// </summary>
  11. /// <typeparam name="T"></typeparam>
  12. internal class MainLoopCoordinator<T> : IMainLoopCoordinator
  13. {
  14. private readonly Func<IConsoleInput<T>> _inputFactory;
  15. private readonly ConcurrentQueue<T> _inputBuffer;
  16. private readonly IInputProcessor _inputProcessor;
  17. private readonly IMainLoop<T> _loop;
  18. private readonly CancellationTokenSource _tokenSource = new ();
  19. private readonly Func<IConsoleOutput> _outputFactory;
  20. private IConsoleInput<T> _input;
  21. private IConsoleOutput _output;
  22. private readonly object _oLockInitialization = new ();
  23. private ConsoleDriverFacade<T> _facade;
  24. private Task _inputTask;
  25. private readonly ITimedEvents _timedEvents;
  26. private readonly SemaphoreSlim _startupSemaphore = new (0, 1);
  27. /// <summary>
  28. /// Creates a new coordinator
  29. /// </summary>
  30. /// <param name="timedEvents"></param>
  31. /// <param name="inputFactory">
  32. /// Function to create a new input. This must call <see langword="new"/>
  33. /// explicitly and cannot return an existing instance. This requirement arises because Windows
  34. /// console screen buffer APIs are thread-specific for certain operations.
  35. /// </param>
  36. /// <param name="inputBuffer"></param>
  37. /// <param name="inputProcessor"></param>
  38. /// <param name="outputFactory">
  39. /// Function to create a new output. This must call <see langword="new"/>
  40. /// explicitly and cannot return an existing instance. This requirement arises because Windows
  41. /// console screen buffer APIs are thread-specific for certain operations.
  42. /// </param>
  43. /// <param name="loop"></param>
  44. public MainLoopCoordinator (
  45. ITimedEvents timedEvents,
  46. Func<IConsoleInput<T>> inputFactory,
  47. ConcurrentQueue<T> inputBuffer,
  48. IInputProcessor inputProcessor,
  49. Func<IConsoleOutput> outputFactory,
  50. IMainLoop<T> loop
  51. )
  52. {
  53. _timedEvents = timedEvents;
  54. _inputFactory = inputFactory;
  55. _inputBuffer = inputBuffer;
  56. _inputProcessor = inputProcessor;
  57. _outputFactory = outputFactory;
  58. _loop = loop;
  59. }
  60. /// <summary>
  61. /// Starts the input loop thread in separate task (returning immediately).
  62. /// </summary>
  63. public async Task StartAsync ()
  64. {
  65. Logging.Logger.LogInformation ("Main Loop Coordinator booting...");
  66. _inputTask = Task.Run (RunInput);
  67. // Main loop is now booted on same thread as rest of users application
  68. BootMainLoop ();
  69. // Wait asynchronously for the semaphore or task failure.
  70. Task waitForSemaphore = _startupSemaphore.WaitAsync ();
  71. // Wait for either the semaphore to be released or the input task to crash.
  72. Task completedTask = await Task.WhenAny (waitForSemaphore, _inputTask).ConfigureAwait (false);
  73. // Check if the task was the input task and if it has failed.
  74. if (completedTask == _inputTask)
  75. {
  76. if (_inputTask.IsFaulted)
  77. {
  78. throw _inputTask.Exception;
  79. }
  80. throw new ("Input loop exited during startup instead of entering read loop properly (i.e. and blocking)");
  81. }
  82. Logging.Logger.LogInformation ("Main Loop Coordinator booting complete");
  83. }
  84. private void RunInput ()
  85. {
  86. try
  87. {
  88. lock (_oLockInitialization)
  89. {
  90. // Instance must be constructed on the thread in which it is used.
  91. _input = _inputFactory.Invoke ();
  92. _input.Initialize (_inputBuffer);
  93. BuildFacadeIfPossible ();
  94. }
  95. try
  96. {
  97. _input.Run (_tokenSource.Token);
  98. }
  99. catch (OperationCanceledException)
  100. { }
  101. _input.Dispose ();
  102. }
  103. catch (Exception e)
  104. {
  105. Logging.Logger.LogCritical (e, "Input loop crashed");
  106. throw;
  107. }
  108. if (_stopCalled)
  109. {
  110. Logging.Logger.LogInformation ("Input loop exited cleanly");
  111. }
  112. else
  113. {
  114. Logging.Logger.LogCritical ("Input loop exited early (stop not called)");
  115. }
  116. }
  117. /// <inheritdoc/>
  118. public void RunIteration () { _loop.Iteration (); }
  119. private void BootMainLoop ()
  120. {
  121. lock (_oLockInitialization)
  122. {
  123. // Instance must be constructed on the thread in which it is used.
  124. _output = _outputFactory.Invoke ();
  125. _loop.Initialize (_timedEvents, _inputBuffer, _inputProcessor, _output);
  126. BuildFacadeIfPossible ();
  127. }
  128. }
  129. private void BuildFacadeIfPossible ()
  130. {
  131. if (_input != null && _output != null)
  132. {
  133. _facade = new (
  134. _inputProcessor,
  135. _loop.OutputBuffer,
  136. _output,
  137. _loop.AnsiRequestScheduler,
  138. _loop.WindowSizeMonitor);
  139. Application.Driver = _facade;
  140. _startupSemaphore.Release ();
  141. }
  142. }
  143. private bool _stopCalled;
  144. /// <inheritdoc/>
  145. public void Stop ()
  146. {
  147. // Ignore repeated calls to Stop - happens if user spams Application.Shutdown().
  148. if (_stopCalled)
  149. {
  150. return;
  151. }
  152. _stopCalled = true;
  153. _tokenSource.Cancel ();
  154. _output.Dispose ();
  155. // Wait for input infinite loop to exit
  156. _inputTask.Wait ();
  157. }
  158. }