2
0

ApplicationMainLoop.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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. // Check for any size changes; this will cause SizeChanged events
  119. SizeMonitor.Poll ();
  120. // Layout and draw any views that need it
  121. App?.LayoutAndDraw (forceRedraw: false);
  122. // Update the cursor
  123. SetCursor ();
  124. Stopwatch swCallbacks = Stopwatch.StartNew ();
  125. // Run any timeout callbacks that are due
  126. TimedEvents.RunTimers ();
  127. Logging.IterationInvokesAndTimeouts.Record (swCallbacks.Elapsed.Milliseconds);
  128. }
  129. private void SetCursor ()
  130. {
  131. View? mostFocused = App?.TopRunnableView?.MostFocused;
  132. if (mostFocused == null)
  133. {
  134. Output.SetCursorVisibility (CursorVisibility.Invisible);
  135. return;
  136. }
  137. Point? to = mostFocused.PositionCursor ();
  138. if (to.HasValue)
  139. {
  140. // Translate to screen coordinates
  141. Point screenPos = mostFocused.ViewportToScreen (to.Value);
  142. Output.SetCursorPosition (screenPos.X, screenPos.Y);
  143. Output.SetCursorVisibility (mostFocused.CursorVisibility);
  144. }
  145. else
  146. {
  147. Output.SetCursorVisibility (CursorVisibility.Invisible);
  148. }
  149. }
  150. /// <inheritdoc/>
  151. public void Dispose ()
  152. {
  153. // TODO release managed resources here
  154. }
  155. }