ApplicationMainLoop.cs 7.2 KB

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