2
0

ApplicationMainLoop.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. #nullable enable
  2. using Terminal.Gui.Drivers;
  3. using System.Collections.Concurrent;
  4. using System.Diagnostics;
  5. namespace Terminal.Gui.App;
  6. /// <summary>
  7. /// The main application loop that runs Terminal.Gui's UI rendering and event processing.
  8. /// </summary>
  9. /// <remarks>
  10. /// This class coordinates the Terminal.Gui application lifecycle by:
  11. /// <list type="bullet">
  12. /// <item>Processing buffered input events and translating them to UI events</item>
  13. /// <item>Executing user timeout callbacks at scheduled intervals</item>
  14. /// <item>Detecting which views need redrawing or layout updates</item>
  15. /// <item>Rendering UI changes to the console output buffer</item>
  16. /// <item>Managing cursor position and visibility</item>
  17. /// <item>Throttling iterations to respect <see cref="Application.MaximumIterationsPerSecond"/></item>
  18. /// </list>
  19. /// </remarks>
  20. /// <typeparam name="T">Type of raw input events, e.g. <see cref="ConsoleKeyInfo"/> for .NET driver</typeparam>
  21. public class ApplicationMainLoop<T> : IApplicationMainLoop<T>
  22. {
  23. private ITimedEvents? _timedEvents;
  24. private ConcurrentQueue<T>? _inputBuffer;
  25. private IInputProcessor? _inputProcessor;
  26. private IConsoleOutput? _out;
  27. private AnsiRequestScheduler? _ansiRequestScheduler;
  28. private IConsoleSizeMonitor? _consoleSizeMonitor;
  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="IConsoleInput{T}"/>. Is drained as part of each
  39. /// <see cref="Iteration"/>
  40. /// </summary>
  41. public ConcurrentQueue<T> InputBuffer
  42. {
  43. get => _inputBuffer ?? throw new NotInitializedException (nameof (InputBuffer));
  44. private set => _inputBuffer = 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 OutputBuffer ();
  54. /// <inheritdoc/>
  55. public IConsoleOutput Out
  56. {
  57. get => _out ?? throw new NotInitializedException (nameof (Out));
  58. private set => _out = 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 IConsoleSizeMonitor ConsoleSizeMonitor
  68. {
  69. get => _consoleSizeMonitor ?? throw new NotInitializedException (nameof (ConsoleSizeMonitor));
  70. private set => _consoleSizeMonitor = value;
  71. }
  72. /// <summary>
  73. /// Handles raising events and setting required draw status etc when <see cref="Application.Top"/> changes
  74. /// </summary>
  75. public IToplevelTransitionManager ToplevelTransitionManager = new ToplevelTransitionManager ();
  76. /// <summary>
  77. /// Determines how to get the current system type, adjust
  78. /// in unit tests to simulate specific timings.
  79. /// </summary>
  80. public Func<DateTime> Now { get; set; } = () => DateTime.Now;
  81. /// <summary>
  82. /// Initializes the class with the provided subcomponents
  83. /// </summary>
  84. /// <param name="timedEvents"></param>
  85. /// <param name="inputBuffer"></param>
  86. /// <param name="inputProcessor"></param>
  87. /// <param name="consoleOutput"></param>
  88. /// <param name="componentFactory"></param>
  89. public void Initialize (
  90. ITimedEvents timedEvents,
  91. ConcurrentQueue<T> inputBuffer,
  92. IInputProcessor inputProcessor,
  93. IConsoleOutput consoleOutput,
  94. IComponentFactory<T> componentFactory
  95. )
  96. {
  97. InputBuffer = inputBuffer;
  98. Out = consoleOutput;
  99. InputProcessor = inputProcessor;
  100. TimedEvents = timedEvents;
  101. AnsiRequestScheduler = new (InputProcessor.GetParser ());
  102. ConsoleSizeMonitor = componentFactory.CreateConsoleSizeMonitor (Out, OutputBuffer);
  103. }
  104. /// <inheritdoc/>
  105. public void Iteration ()
  106. {
  107. Application.RaiseIteration ();
  108. DateTime dt = Now ();
  109. int timeAllowed = 1000 / Math.Max(1,(int)Application.MaximumIterationsPerSecond);
  110. IterationImpl ();
  111. TimeSpan took = Now () - dt;
  112. TimeSpan sleepFor = TimeSpan.FromMilliseconds (timeAllowed) - took;
  113. Logging.TotalIterationMetric.Record (took.Milliseconds);
  114. if (sleepFor.Milliseconds > 0)
  115. {
  116. Task.Delay (sleepFor).Wait ();
  117. }
  118. }
  119. internal void IterationImpl ()
  120. {
  121. InputProcessor.ProcessQueue ();
  122. ToplevelTransitionManager.RaiseReadyEventIfNeeded ();
  123. ToplevelTransitionManager.HandleTopMaybeChanging ();
  124. if (Application.Top != null)
  125. {
  126. bool needsDrawOrLayout = AnySubViewsNeedDrawn (Application.Popover?.GetActivePopover () as View)
  127. || AnySubViewsNeedDrawn (Application.Top)
  128. || (Application.Mouse.MouseGrabView != null && AnySubViewsNeedDrawn (Application.Mouse.MouseGrabView));
  129. bool sizeChanged = ConsoleSizeMonitor.Poll ();
  130. if (needsDrawOrLayout || sizeChanged)
  131. {
  132. Logging.Redraws.Add (1);
  133. Application.LayoutAndDraw (true);
  134. Out.Write (OutputBuffer);
  135. Out.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 = Application.Top!.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. Out.SetCursorPosition (to.Value.X, to.Value.Y);
  156. Out.SetCursorVisibility (mostFocused.CursorVisibility);
  157. }
  158. else
  159. {
  160. Out.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. }