ApplicationMainLoop.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. using System.Collections.Concurrent;
  2. using System.Diagnostics;
  3. namespace Terminal.Gui.App;
  4. /// <summary>
  5. /// The main application loop that runs Terminal.Gui's UI rendering and event processing.
  6. /// </summary>
  7. /// <remarks>
  8. /// This class coordinates the Terminal.Gui application lifecycle by:
  9. /// <list type="bullet">
  10. /// <item>Processing buffered input events and translating them to UI events</item>
  11. /// <item>Executing user timeout callbacks at scheduled intervals</item>
  12. /// <item>Detecting which views need redrawing or layout updates</item>
  13. /// <item>Rendering UI changes to the console output buffer</item>
  14. /// <item>Managing cursor position and visibility</item>
  15. /// <item>Throttling iterations to respect <see cref="Application.MaximumIterationsPerSecond"/></item>
  16. /// </list>
  17. /// </remarks>
  18. /// <typeparam name="TInputRecord">Type of raw input events, e.g. <see cref="ConsoleKeyInfo"/> for .NET driver</typeparam>
  19. public class ApplicationMainLoop<TInputRecord> : IApplicationMainLoop<TInputRecord> where TInputRecord : struct
  20. {
  21. private ITimedEvents? _timedEvents;
  22. private ConcurrentQueue<TInputRecord>? _inputQueue;
  23. private IInputProcessor? _inputProcessor;
  24. private IOutput? _output;
  25. private AnsiRequestScheduler? _ansiRequestScheduler;
  26. private ISizeMonitor? _sizeMonitor;
  27. /// <inheritdoc/>
  28. public IApplication? App { get; private set; }
  29. /// <inheritdoc/>
  30. public ITimedEvents TimedEvents
  31. {
  32. get => _timedEvents ?? throw new NotInitializedException (nameof (TimedEvents));
  33. private set => _timedEvents = value;
  34. }
  35. // TODO: follow above pattern for others too
  36. /// <summary>
  37. /// The input events thread-safe collection. This is populated on separate
  38. /// thread by a <see cref="IInput{T}"/>. Is drained as part of each
  39. /// <see cref="Iteration"/> on the main loop thread.
  40. /// </summary>
  41. public ConcurrentQueue<TInputRecord> InputQueue
  42. {
  43. get => _inputQueue ?? throw new NotInitializedException (nameof (InputQueue));
  44. private set => _inputQueue = value;
  45. }
  46. /// <inheritdoc/>
  47. public IInputProcessor InputProcessor
  48. {
  49. get => _inputProcessor ?? throw new NotInitializedException (nameof (InputProcessor));
  50. private set => _inputProcessor = value;
  51. }
  52. /// <inheritdoc/>
  53. public IOutputBuffer OutputBuffer { get; } = new OutputBufferImpl ();
  54. /// <inheritdoc/>
  55. public IOutput Output
  56. {
  57. get => _output ?? throw new NotInitializedException (nameof (Output));
  58. private set => _output = value;
  59. }
  60. /// <inheritdoc/>
  61. public AnsiRequestScheduler AnsiRequestScheduler
  62. {
  63. get => _ansiRequestScheduler ?? throw new NotInitializedException (nameof (AnsiRequestScheduler));
  64. private set => _ansiRequestScheduler = value;
  65. }
  66. /// <inheritdoc/>
  67. public ISizeMonitor SizeMonitor
  68. {
  69. get => _sizeMonitor ?? throw new NotInitializedException (nameof (SizeMonitor));
  70. private set => _sizeMonitor = value;
  71. }
  72. /// <summary>
  73. /// Handles raising events and setting required draw status etc when <see cref="IApplication.Current"/> changes
  74. /// </summary>
  75. public IToplevelTransitionManager ToplevelTransitionManager = new ToplevelTransitionManager ();
  76. /// <summary>
  77. /// Initializes the class with the provided subcomponents
  78. /// </summary>
  79. /// <param name="timedEvents"></param>
  80. /// <param name="inputBuffer"></param>
  81. /// <param name="inputProcessor"></param>
  82. /// <param name="consoleOutput"></param>
  83. /// <param name="componentFactory"></param>
  84. /// <param name="app"></param>
  85. public void Initialize (
  86. ITimedEvents timedEvents,
  87. ConcurrentQueue<TInputRecord> inputBuffer,
  88. IInputProcessor inputProcessor,
  89. IOutput consoleOutput,
  90. IComponentFactory<TInputRecord> componentFactory,
  91. IApplication? app
  92. )
  93. {
  94. App = app;
  95. InputQueue = inputBuffer;
  96. Output = consoleOutput;
  97. InputProcessor = inputProcessor;
  98. TimedEvents = timedEvents;
  99. AnsiRequestScheduler = new (InputProcessor.GetParser ());
  100. OutputBuffer.SetSize (consoleOutput.GetSize ().Width, consoleOutput.GetSize ().Height);
  101. SizeMonitor = componentFactory.CreateSizeMonitor (Output, OutputBuffer);
  102. }
  103. /// <inheritdoc/>
  104. public void Iteration ()
  105. {
  106. App?.RaiseIteration ();
  107. DateTime dt = DateTime.Now;
  108. int timeAllowed = 1000 / Math.Max (1, (int)Application.MaximumIterationsPerSecond);
  109. IterationImpl ();
  110. TimeSpan took = DateTime.Now - dt;
  111. TimeSpan sleepFor = TimeSpan.FromMilliseconds (timeAllowed) - took;
  112. Logging.TotalIterationMetric.Record (took.Milliseconds);
  113. if (sleepFor.Milliseconds > 0)
  114. {
  115. Task.Delay (sleepFor).Wait ();
  116. }
  117. }
  118. internal void IterationImpl ()
  119. {
  120. // Pull any input events from the input queue and process them
  121. InputProcessor.ProcessQueue ();
  122. ToplevelTransitionManager.RaiseReadyEventIfNeeded (App);
  123. ToplevelTransitionManager.HandleTopMaybeChanging (App);
  124. if (App?.Current != null)
  125. {
  126. bool needsDrawOrLayout = AnySubViewsNeedDrawn (App?.Popover?.GetActivePopover () as View)
  127. || AnySubViewsNeedDrawn (App?.Current)
  128. || (App?.Mouse.MouseGrabView != null && AnySubViewsNeedDrawn (App?.Mouse.MouseGrabView));
  129. bool sizeChanged = SizeMonitor.Poll ();
  130. if (needsDrawOrLayout || sizeChanged)
  131. {
  132. Logging.Redraws.Add (1);
  133. App?.LayoutAndDraw (true);
  134. Output.Write (OutputBuffer);
  135. Output.SetCursorVisibility (CursorVisibility.Default);
  136. }
  137. SetCursor ();
  138. }
  139. var swCallbacks = Stopwatch.StartNew ();
  140. TimedEvents.RunTimers ();
  141. Logging.IterationInvokesAndTimeouts.Record (swCallbacks.Elapsed.Milliseconds);
  142. }
  143. private void SetCursor ()
  144. {
  145. View? mostFocused = App?.Current!.MostFocused;
  146. if (mostFocused == null)
  147. {
  148. return;
  149. }
  150. Point? to = mostFocused.PositionCursor ();
  151. if (to.HasValue)
  152. {
  153. // Translate to screen coordinates
  154. to = mostFocused.ViewportToScreen (to.Value);
  155. Output.SetCursorPosition (to.Value.X, to.Value.Y);
  156. Output.SetCursorVisibility (mostFocused.CursorVisibility);
  157. }
  158. else
  159. {
  160. Output.SetCursorVisibility (CursorVisibility.Invisible);
  161. }
  162. }
  163. private bool AnySubViewsNeedDrawn (View? v)
  164. {
  165. if (v is null)
  166. {
  167. return false;
  168. }
  169. if (v.NeedsDraw || v.NeedsLayout)
  170. {
  171. // Logging.Trace ($"{v.GetType ().Name} triggered redraw (NeedsDraw={v.NeedsDraw} NeedsLayout={v.NeedsLayout}) ");
  172. return true;
  173. }
  174. foreach (View subview in v.SubViews)
  175. {
  176. if (AnySubViewsNeedDrawn (subview))
  177. {
  178. return true;
  179. }
  180. }
  181. return false;
  182. }
  183. /// <inheritdoc/>
  184. public void Dispose ()
  185. {
  186. // TODO release managed resources here
  187. }
  188. }