ApplicationMainLoop.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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 ITimedEvents TimedEvents
  29. {
  30. get => _timedEvents ?? throw new NotInitializedException (nameof (TimedEvents));
  31. private set => _timedEvents = value;
  32. }
  33. // TODO: follow above pattern for others too
  34. /// <summary>
  35. /// The input events thread-safe collection. This is populated on separate
  36. /// thread by a <see cref="IInput{T}"/>. Is drained as part of each
  37. /// <see cref="Iteration"/> on the main loop thread.
  38. /// </summary>
  39. public ConcurrentQueue<TInputRecord> InputQueue
  40. {
  41. get => _inputQueue ?? throw new NotInitializedException (nameof (InputQueue));
  42. private set => _inputQueue = value;
  43. }
  44. /// <inheritdoc/>
  45. public IInputProcessor InputProcessor
  46. {
  47. get => _inputProcessor ?? throw new NotInitializedException (nameof (InputProcessor));
  48. private set => _inputProcessor = value;
  49. }
  50. /// <inheritdoc/>
  51. public IOutputBuffer OutputBuffer { get; } = new OutputBufferImpl ();
  52. /// <inheritdoc/>
  53. public IOutput Output
  54. {
  55. get => _output ?? throw new NotInitializedException (nameof (Output));
  56. private set => _output = value;
  57. }
  58. /// <inheritdoc/>
  59. public AnsiRequestScheduler AnsiRequestScheduler
  60. {
  61. get => _ansiRequestScheduler ?? throw new NotInitializedException (nameof (AnsiRequestScheduler));
  62. private set => _ansiRequestScheduler = value;
  63. }
  64. /// <inheritdoc/>
  65. public ISizeMonitor SizeMonitor
  66. {
  67. get => _sizeMonitor ?? throw new NotInitializedException (nameof (SizeMonitor));
  68. private set => _sizeMonitor = value;
  69. }
  70. /// <summary>
  71. /// Handles raising events and setting required draw status etc when <see cref="Application.Current"/> changes
  72. /// </summary>
  73. public IToplevelTransitionManager ToplevelTransitionManager = new ToplevelTransitionManager ();
  74. /// <summary>
  75. /// Initializes the class with the provided subcomponents
  76. /// </summary>
  77. /// <param name="timedEvents"></param>
  78. /// <param name="inputBuffer"></param>
  79. /// <param name="inputProcessor"></param>
  80. /// <param name="consoleOutput"></param>
  81. /// <param name="componentFactory"></param>
  82. public void Initialize (
  83. ITimedEvents timedEvents,
  84. ConcurrentQueue<TInputRecord> inputBuffer,
  85. IInputProcessor inputProcessor,
  86. IOutput consoleOutput,
  87. IComponentFactory<TInputRecord> componentFactory
  88. )
  89. {
  90. InputQueue = inputBuffer;
  91. Output = consoleOutput;
  92. InputProcessor = inputProcessor;
  93. TimedEvents = timedEvents;
  94. AnsiRequestScheduler = new (InputProcessor.GetParser ());
  95. OutputBuffer.SetSize (consoleOutput.GetSize ().Width, consoleOutput.GetSize ().Height);
  96. SizeMonitor = componentFactory.CreateSizeMonitor (Output, OutputBuffer);
  97. }
  98. /// <inheritdoc/>
  99. public void Iteration ()
  100. {
  101. Application.RaiseIteration ();
  102. DateTime dt = DateTime.Now;
  103. int timeAllowed = 1000 / Math.Max(1,(int)Application.MaximumIterationsPerSecond);
  104. IterationImpl ();
  105. TimeSpan took = DateTime.Now - dt;
  106. TimeSpan sleepFor = TimeSpan.FromMilliseconds (timeAllowed) - took;
  107. Logging.TotalIterationMetric.Record (took.Milliseconds);
  108. if (sleepFor.Milliseconds > 0)
  109. {
  110. Task.Delay (sleepFor).Wait ();
  111. }
  112. }
  113. internal void IterationImpl ()
  114. {
  115. // Pull any input events from the input queue and process them
  116. InputProcessor.ProcessQueue ();
  117. ToplevelTransitionManager.RaiseReadyEventIfNeeded ();
  118. ToplevelTransitionManager.HandleTopMaybeChanging ();
  119. if (Application.Current != null)
  120. {
  121. bool needsDrawOrLayout = AnySubViewsNeedDrawn (Application.Popover?.GetActivePopover () as View)
  122. || AnySubViewsNeedDrawn (Application.Current)
  123. || (Application.Mouse.MouseGrabView != null && AnySubViewsNeedDrawn (Application.Mouse.MouseGrabView));
  124. bool sizeChanged = SizeMonitor.Poll ();
  125. if (needsDrawOrLayout || sizeChanged)
  126. {
  127. Logging.Redraws.Add (1);
  128. Application.LayoutAndDraw (true);
  129. Output.Write (OutputBuffer);
  130. Output.SetCursorVisibility (CursorVisibility.Default);
  131. }
  132. SetCursor ();
  133. }
  134. var swCallbacks = Stopwatch.StartNew ();
  135. TimedEvents.RunTimers ();
  136. Logging.IterationInvokesAndTimeouts.Record (swCallbacks.Elapsed.Milliseconds);
  137. }
  138. private void SetCursor ()
  139. {
  140. View? mostFocused = Application.Current!.MostFocused;
  141. if (mostFocused == null)
  142. {
  143. return;
  144. }
  145. Point? to = mostFocused.PositionCursor ();
  146. if (to.HasValue)
  147. {
  148. // Translate to screen coordinates
  149. to = mostFocused.ViewportToScreen (to.Value);
  150. Output.SetCursorPosition (to.Value.X, to.Value.Y);
  151. Output.SetCursorVisibility (mostFocused.CursorVisibility);
  152. }
  153. else
  154. {
  155. Output.SetCursorVisibility (CursorVisibility.Invisible);
  156. }
  157. }
  158. private bool AnySubViewsNeedDrawn (View? v)
  159. {
  160. if (v is null)
  161. {
  162. return false;
  163. }
  164. if (v.NeedsDraw || v.NeedsLayout)
  165. {
  166. // Logging.Trace ($"{v.GetType ().Name} triggered redraw (NeedsDraw={v.NeedsDraw} NeedsLayout={v.NeedsLayout}) ");
  167. return true;
  168. }
  169. foreach (View subview in v.SubViews)
  170. {
  171. if (AnySubViewsNeedDrawn (subview))
  172. {
  173. return true;
  174. }
  175. }
  176. return false;
  177. }
  178. /// <inheritdoc/>
  179. public void Dispose ()
  180. {
  181. // TODO release managed resources here
  182. }
  183. }