2
0

ApplicationMainLoop.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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. /// Initializes the class with the provided subcomponents
  74. /// </summary>
  75. /// <param name="timedEvents"></param>
  76. /// <param name="inputBuffer"></param>
  77. /// <param name="inputProcessor"></param>
  78. /// <param name="consoleOutput"></param>
  79. /// <param name="componentFactory"></param>
  80. /// <param name="app"></param>
  81. public void Initialize (
  82. ITimedEvents timedEvents,
  83. ConcurrentQueue<TInputRecord> inputBuffer,
  84. IInputProcessor inputProcessor,
  85. IOutput consoleOutput,
  86. IComponentFactory<TInputRecord> componentFactory,
  87. IApplication? app
  88. )
  89. {
  90. App = app;
  91. InputQueue = inputBuffer;
  92. Output = consoleOutput;
  93. InputProcessor = inputProcessor;
  94. TimedEvents = timedEvents;
  95. AnsiRequestScheduler = new (InputProcessor.GetParser ());
  96. OutputBuffer.SetSize (consoleOutput.GetSize ().Width, consoleOutput.GetSize ().Height);
  97. SizeMonitor = componentFactory.CreateSizeMonitor (Output, OutputBuffer);
  98. }
  99. /// <inheritdoc/>
  100. public void Iteration ()
  101. {
  102. App?.RaiseIteration ();
  103. DateTime dt = DateTime.Now;
  104. int timeAllowed = 1000 / Math.Max (1, (int)Application.MaximumIterationsPerSecond);
  105. IterationImpl ();
  106. TimeSpan took = DateTime.Now - dt;
  107. TimeSpan sleepFor = TimeSpan.FromMilliseconds (timeAllowed) - took;
  108. Logging.TotalIterationMetric.Record (took.Milliseconds);
  109. if (sleepFor.Milliseconds > 0)
  110. {
  111. Task.Delay (sleepFor).Wait ();
  112. }
  113. }
  114. internal void IterationImpl ()
  115. {
  116. // Pull any input events from the input queue and process them
  117. InputProcessor.ProcessQueue ();
  118. if (App?.TopRunnableView != null)
  119. {
  120. bool needsDrawOrLayout = AnySubViewsNeedDrawn (App?.Popover?.GetActivePopover () as View)
  121. || AnySubViewsNeedDrawn (App?.TopRunnableView)
  122. || (App?.Mouse.MouseGrabView != null && AnySubViewsNeedDrawn (App?.Mouse.MouseGrabView));
  123. bool sizeChanged = SizeMonitor.Poll ();
  124. if (needsDrawOrLayout || sizeChanged)
  125. {
  126. Logging.Redraws.Add (1);
  127. App?.LayoutAndDraw (true);
  128. Output.Write (OutputBuffer);
  129. Output.SetCursorVisibility (CursorVisibility.Default);
  130. }
  131. SetCursor ();
  132. }
  133. var swCallbacks = Stopwatch.StartNew ();
  134. TimedEvents.RunTimers ();
  135. Logging.IterationInvokesAndTimeouts.Record (swCallbacks.Elapsed.Milliseconds);
  136. }
  137. private void SetCursor ()
  138. {
  139. View? mostFocused = App?.TopRunnableView!.MostFocused;
  140. if (mostFocused == null)
  141. {
  142. return;
  143. }
  144. Point? to = mostFocused.PositionCursor ();
  145. if (to.HasValue)
  146. {
  147. // Translate to screen coordinates
  148. to = mostFocused.ViewportToScreen (to.Value);
  149. Output.SetCursorPosition (to.Value.X, to.Value.Y);
  150. Output.SetCursorVisibility (mostFocused.CursorVisibility);
  151. }
  152. else
  153. {
  154. Output.SetCursorVisibility (CursorVisibility.Invisible);
  155. }
  156. }
  157. private bool AnySubViewsNeedDrawn (View? v)
  158. {
  159. if (v is null)
  160. {
  161. return false;
  162. }
  163. if (v.NeedsDraw || v.NeedsLayout)
  164. {
  165. // Logging.Trace ($"{v.GetType ().Name} triggered redraw (NeedsDraw={v.NeedsDraw} NeedsLayout={v.NeedsLayout}) ");
  166. return true;
  167. }
  168. foreach (View subview in v.SubViews)
  169. {
  170. if (AnySubViewsNeedDrawn (subview))
  171. {
  172. return true;
  173. }
  174. }
  175. return false;
  176. }
  177. /// <inheritdoc/>
  178. public void Dispose ()
  179. {
  180. // TODO release managed resources here
  181. }
  182. }