MainLoopCoordinator.cs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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. // ReSharper disable once UseConfigureAwaitFalse
  73. Task completedTask = await Task.WhenAny (waitForSemaphore, _inputTask);
  74. // Check if the task was the input task and if it has failed.
  75. if (completedTask == _inputTask)
  76. {
  77. if (_inputTask.IsFaulted)
  78. {
  79. throw _inputTask.Exception;
  80. }
  81. throw new ("Input loop exited during startup instead of entering read loop properly (i.e. and blocking)");
  82. }
  83. Logging.Logger.LogInformation ("Main Loop Coordinator booting complete");
  84. }
  85. private void RunInput ()
  86. {
  87. try
  88. {
  89. lock (_oLockInitialization)
  90. {
  91. // Instance must be constructed on the thread in which it is used.
  92. _input = _inputFactory.Invoke ();
  93. _input.Initialize (_inputBuffer);
  94. BuildFacadeIfPossible ();
  95. }
  96. try
  97. {
  98. _input.Run (_tokenSource.Token);
  99. }
  100. catch (OperationCanceledException)
  101. { }
  102. _input.Dispose ();
  103. }
  104. catch (Exception e)
  105. {
  106. Logging.Logger.LogCritical (e, "Input loop crashed");
  107. throw;
  108. }
  109. if (_stopCalled)
  110. {
  111. Logging.Logger.LogInformation ("Input loop exited cleanly");
  112. }
  113. else
  114. {
  115. Logging.Logger.LogCritical ("Input loop exited early (stop not called)");
  116. }
  117. }
  118. /// <inheritdoc/>
  119. public void RunIteration () { _loop.Iteration (); }
  120. private void BootMainLoop ()
  121. {
  122. lock (_oLockInitialization)
  123. {
  124. // Instance must be constructed on the thread in which it is used.
  125. _output = _outputFactory.Invoke ();
  126. _loop.Initialize (_timedEvents, _inputBuffer, _inputProcessor, _output);
  127. BuildFacadeIfPossible ();
  128. }
  129. }
  130. private void BuildFacadeIfPossible ()
  131. {
  132. if (_input != null && _output != null)
  133. {
  134. _facade = new (
  135. _inputProcessor,
  136. _loop.OutputBuffer,
  137. _output,
  138. _loop.AnsiRequestScheduler,
  139. _loop.WindowSizeMonitor);
  140. Application.Driver = _facade;
  141. _startupSemaphore.Release ();
  142. }
  143. }
  144. private bool _stopCalled;
  145. /// <inheritdoc/>
  146. public void Stop ()
  147. {
  148. // Ignore repeated calls to Stop - happens if user spams Application.Shutdown().
  149. if (_stopCalled)
  150. {
  151. return;
  152. }
  153. _stopCalled = true;
  154. _tokenSource.Cancel ();
  155. _output.Dispose ();
  156. // Wait for input infinite loop to exit
  157. _inputTask.Wait ();
  158. }
  159. }