MainLoop.cs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. #nullable enable
  2. using System.Collections.Concurrent;
  3. using System.Diagnostics;
  4. namespace Terminal.Gui;
  5. /// <inheritdoc/>
  6. public class MainLoop<T> : IMainLoop<T>
  7. {
  8. private ITimedEvents? _timedEvents;
  9. private ConcurrentQueue<T>? _inputBuffer;
  10. private IInputProcessor? _inputProcessor;
  11. private IConsoleOutput? _out;
  12. private AnsiRequestScheduler? _ansiRequestScheduler;
  13. private IWindowSizeMonitor? _windowSizeMonitor;
  14. /// <inheritdoc/>
  15. public ITimedEvents TimedEvents
  16. {
  17. get => _timedEvents ?? throw new NotInitializedException (nameof (TimedEvents));
  18. private set => _timedEvents = value;
  19. }
  20. // TODO: follow above pattern for others too
  21. /// <summary>
  22. /// The input events thread-safe collection. This is populated on separate
  23. /// thread by a <see cref="IConsoleInput{T}"/>. Is drained as part of each
  24. /// <see cref="Iteration"/>
  25. /// </summary>
  26. public ConcurrentQueue<T> InputBuffer
  27. {
  28. get => _inputBuffer ?? throw new NotInitializedException (nameof (InputBuffer));
  29. private set => _inputBuffer = value;
  30. }
  31. /// <inheritdoc/>
  32. public IInputProcessor InputProcessor
  33. {
  34. get => _inputProcessor ?? throw new NotInitializedException (nameof (InputProcessor));
  35. private set => _inputProcessor = value;
  36. }
  37. /// <inheritdoc/>
  38. public IOutputBuffer OutputBuffer { get; } = new OutputBuffer ();
  39. /// <inheritdoc/>
  40. public IConsoleOutput Out
  41. {
  42. get => _out ?? throw new NotInitializedException (nameof (Out));
  43. private set => _out = value;
  44. }
  45. /// <inheritdoc/>
  46. public AnsiRequestScheduler AnsiRequestScheduler
  47. {
  48. get => _ansiRequestScheduler ?? throw new NotInitializedException (nameof (AnsiRequestScheduler));
  49. private set => _ansiRequestScheduler = value;
  50. }
  51. /// <inheritdoc/>
  52. public IWindowSizeMonitor WindowSizeMonitor
  53. {
  54. get => _windowSizeMonitor ?? throw new NotInitializedException (nameof (WindowSizeMonitor));
  55. private set => _windowSizeMonitor = value;
  56. }
  57. /// <summary>
  58. /// Handles raising events and setting required draw status etc when <see cref="Application.Top"/> changes
  59. /// </summary>
  60. public IToplevelTransitionManager ToplevelTransitionManager = new ToplevelTransitionManager ();
  61. /// <summary>
  62. /// Determines how to get the current system type, adjust
  63. /// in unit tests to simulate specific timings.
  64. /// </summary>
  65. public Func<DateTime> Now { get; set; } = () => DateTime.Now;
  66. /// <summary>
  67. /// Initializes the class with the provided subcomponents
  68. /// </summary>
  69. /// <param name="timedEvents"></param>
  70. /// <param name="inputBuffer"></param>
  71. /// <param name="inputProcessor"></param>
  72. /// <param name="consoleOutput"></param>
  73. public void Initialize (ITimedEvents timedEvents, ConcurrentQueue<T> inputBuffer, IInputProcessor inputProcessor, IConsoleOutput consoleOutput)
  74. {
  75. InputBuffer = inputBuffer;
  76. Out = consoleOutput;
  77. InputProcessor = inputProcessor;
  78. TimedEvents = timedEvents;
  79. AnsiRequestScheduler = new (InputProcessor.GetParser ());
  80. WindowSizeMonitor = new WindowSizeMonitor (Out, OutputBuffer);
  81. }
  82. /// <inheritdoc/>
  83. public void Iteration ()
  84. {
  85. DateTime dt = Now ();
  86. IterationImpl ();
  87. TimeSpan took = Now () - dt;
  88. TimeSpan sleepFor = TimeSpan.FromMilliseconds (50) - took;
  89. Logging.TotalIterationMetric.Record (took.Milliseconds);
  90. if (sleepFor.Milliseconds > 0)
  91. {
  92. Task.Delay (sleepFor).Wait ();
  93. }
  94. }
  95. internal void IterationImpl ()
  96. {
  97. InputProcessor.ProcessQueue ();
  98. ToplevelTransitionManager.RaiseReadyEventIfNeeded ();
  99. ToplevelTransitionManager.HandleTopMaybeChanging ();
  100. if (Application.Top != null)
  101. {
  102. bool needsDrawOrLayout = AnySubviewsNeedDrawn (Application.Top);
  103. bool sizeChanged = WindowSizeMonitor.Poll ();
  104. if (needsDrawOrLayout || sizeChanged)
  105. {
  106. Logging.Redraws.Add (1);
  107. // TODO: Test only
  108. Application.LayoutAndDraw (true);
  109. Out.Write (OutputBuffer);
  110. Out.SetCursorVisibility (CursorVisibility.Default);
  111. }
  112. SetCursor ();
  113. }
  114. var swCallbacks = Stopwatch.StartNew ();
  115. TimedEvents.LockAndRunTimers ();
  116. TimedEvents.LockAndRunIdles ();
  117. Logging.IterationInvokesAndTimeouts.Record (swCallbacks.Elapsed.Milliseconds);
  118. }
  119. private void SetCursor ()
  120. {
  121. View? mostFocused = Application.Top.MostFocused;
  122. if (mostFocused == null)
  123. {
  124. return;
  125. }
  126. Point? to = mostFocused.PositionCursor ();
  127. if (to.HasValue)
  128. {
  129. // Translate to screen coordinates
  130. to = mostFocused.ViewportToScreen (to.Value);
  131. Out.SetCursorPosition (to.Value.X, to.Value.Y);
  132. Out.SetCursorVisibility (mostFocused.CursorVisibility);
  133. }
  134. else
  135. {
  136. Out.SetCursorVisibility (CursorVisibility.Invisible);
  137. }
  138. }
  139. private bool AnySubviewsNeedDrawn (View v)
  140. {
  141. if (v.NeedsDraw || v.NeedsLayout)
  142. {
  143. Logging.Trace ($"{v.GetType ().Name} triggered redraw (NeedsDraw={v.NeedsDraw} NeedsLayout={v.NeedsLayout}) ");
  144. return true;
  145. }
  146. foreach (View subview in v.Subviews)
  147. {
  148. if (AnySubviewsNeedDrawn (subview))
  149. {
  150. return true;
  151. }
  152. }
  153. return false;
  154. }
  155. /// <inheritdoc/>
  156. public void Dispose ()
  157. {
  158. // TODO release managed resources here
  159. }
  160. }