ApplicationMainLoop.cs 7.2 KB

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