ApplicationV2.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. #nullable enable
  2. using System.Collections.Concurrent;
  3. using System.Diagnostics.CodeAnalysis;
  4. using Microsoft.Extensions.Logging;
  5. namespace Terminal.Gui;
  6. /// <summary>
  7. /// Implementation of <see cref="IApplication"/> that boots the new 'v2'
  8. /// main loop architecture.
  9. /// </summary>
  10. public class ApplicationV2 : ApplicationImpl
  11. {
  12. private readonly Func<INetInput> _netInputFactory;
  13. private readonly Func<IConsoleOutput> _netOutputFactory;
  14. private readonly Func<IWindowsInput> _winInputFactory;
  15. private readonly Func<IConsoleOutput> _winOutputFactory;
  16. private IMainLoopCoordinator? _coordinator;
  17. private string? _driverName;
  18. private readonly ITimedEvents _timedEvents = new TimedEvents ();
  19. /// <summary>
  20. /// Creates anew instance of the Application backend. The provided
  21. /// factory methods will be used on Init calls to get things booted.
  22. /// </summary>
  23. public ApplicationV2 () : this (
  24. () => new NetInput (),
  25. () => new NetOutput (),
  26. () => new WindowsInput (),
  27. () => new WindowsOutput ()
  28. )
  29. { }
  30. internal ApplicationV2 (
  31. Func<INetInput> netInputFactory,
  32. Func<IConsoleOutput> netOutputFactory,
  33. Func<IWindowsInput> winInputFactory,
  34. Func<IConsoleOutput> winOutputFactory
  35. )
  36. {
  37. _netInputFactory = netInputFactory;
  38. _netOutputFactory = netOutputFactory;
  39. _winInputFactory = winInputFactory;
  40. _winOutputFactory = winOutputFactory;
  41. IsLegacy = false;
  42. }
  43. /// <inheritdoc/>
  44. [RequiresUnreferencedCode ("AOT")]
  45. [RequiresDynamicCode ("AOT")]
  46. public override void Init (IConsoleDriver? driver = null, string? driverName = null)
  47. {
  48. if (Application.Initialized)
  49. {
  50. Logging.Logger.LogError ("Init called multiple times without shutdown, ignoring.");
  51. return;
  52. }
  53. if (!string.IsNullOrWhiteSpace (driverName))
  54. {
  55. _driverName = driverName;
  56. }
  57. Application.Navigation = new ();
  58. Application.AddKeyBindings ();
  59. // This is consistent with Application.ForceDriver which magnetically picks up driverName
  60. // making it use custom driver in future shutdown/init calls where no driver is specified
  61. CreateDriver (driverName ?? _driverName);
  62. Application.InitializeConfigurationManagement ();
  63. Application.Initialized = true;
  64. Application.OnInitializedChanged (this, new (true));
  65. Application.SubscribeDriverEvents ();
  66. }
  67. private void CreateDriver (string? driverName)
  68. {
  69. PlatformID p = Environment.OSVersion.Platform;
  70. bool definetlyWin = driverName?.Contains ("win") ?? false;
  71. bool definetlyNet = driverName?.Contains ("net") ?? false;
  72. if (definetlyWin)
  73. {
  74. _coordinator = CreateWindowsSubcomponents ();
  75. }
  76. else if (definetlyNet)
  77. {
  78. _coordinator = CreateNetSubcomponents ();
  79. }
  80. else if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows)
  81. {
  82. _coordinator = CreateWindowsSubcomponents ();
  83. }
  84. else
  85. {
  86. _coordinator = CreateNetSubcomponents ();
  87. }
  88. _coordinator.StartAsync ().Wait ();
  89. if (Application.Driver == null)
  90. {
  91. throw new ("Application.Driver was null even after booting MainLoopCoordinator");
  92. }
  93. }
  94. private IMainLoopCoordinator CreateWindowsSubcomponents ()
  95. {
  96. ConcurrentQueue<WindowsConsole.InputRecord> inputBuffer = new ();
  97. MainLoop<WindowsConsole.InputRecord> loop = new ();
  98. return new MainLoopCoordinator<WindowsConsole.InputRecord> (
  99. _timedEvents,
  100. _winInputFactory,
  101. inputBuffer,
  102. new WindowsInputProcessor (inputBuffer),
  103. _winOutputFactory,
  104. loop);
  105. }
  106. private IMainLoopCoordinator CreateNetSubcomponents ()
  107. {
  108. ConcurrentQueue<ConsoleKeyInfo> inputBuffer = new ();
  109. MainLoop<ConsoleKeyInfo> loop = new ();
  110. return new MainLoopCoordinator<ConsoleKeyInfo> (
  111. _timedEvents,
  112. _netInputFactory,
  113. inputBuffer,
  114. new NetInputProcessor (inputBuffer),
  115. _netOutputFactory,
  116. loop);
  117. }
  118. /// <inheritdoc/>
  119. [RequiresUnreferencedCode ("AOT")]
  120. [RequiresDynamicCode ("AOT")]
  121. public override T Run<T> (Func<Exception, bool>? errorHandler = null, IConsoleDriver? driver = null)
  122. {
  123. var top = new T ();
  124. Run (top, errorHandler);
  125. return top;
  126. }
  127. /// <inheritdoc/>
  128. public override void Run (Toplevel view, Func<Exception, bool>? errorHandler = null)
  129. {
  130. Logging.Logger.LogInformation ($"Run '{view}'");
  131. ArgumentNullException.ThrowIfNull (view);
  132. if (!Application.Initialized)
  133. {
  134. throw new NotInitializedException (nameof (Run));
  135. }
  136. Application.Top = view;
  137. Application.Begin (view);
  138. // TODO : how to know when we are done?
  139. while (Application.TopLevels.TryPeek (out Toplevel? found) && found == view)
  140. {
  141. if (_coordinator is null)
  142. {
  143. throw new ($"{nameof (IMainLoopCoordinator)}inexplicably became null during Run");
  144. }
  145. _coordinator.RunIteration ();
  146. }
  147. }
  148. /// <inheritdoc/>
  149. public override void Shutdown ()
  150. {
  151. _coordinator?.Stop ();
  152. base.Shutdown ();
  153. Application.Driver = null;
  154. }
  155. /// <inheritdoc/>
  156. public override void RequestStop (Toplevel? top)
  157. {
  158. Logging.Logger.LogInformation ($"RequestStop '{top}'");
  159. // TODO: This definition of stop seems sketchy
  160. Application.TopLevels.TryPop (out _);
  161. if (Application.TopLevels.Count > 0)
  162. {
  163. Application.Top = Application.TopLevels.Peek ();
  164. }
  165. else
  166. {
  167. Application.Top = null;
  168. }
  169. }
  170. /// <inheritdoc/>
  171. public override void Invoke (Action action)
  172. {
  173. _timedEvents.AddIdle (
  174. () =>
  175. {
  176. action ();
  177. return false;
  178. }
  179. );
  180. }
  181. /// <inheritdoc/>
  182. public override void AddIdle (Func<bool> func) { _timedEvents.AddIdle (func); }
  183. /// <summary>
  184. /// Removes an idle function added by <see cref="AddIdle"/>
  185. /// </summary>
  186. /// <param name="fnTrue">Function to remove</param>
  187. /// <returns>True if it was found and removed</returns>
  188. public bool RemoveIdle (Func<bool> fnTrue) { return _timedEvents.RemoveIdle (fnTrue); }
  189. /// <inheritdoc/>
  190. public override object AddTimeout (TimeSpan time, Func<bool> callback) { return _timedEvents.AddTimeout (time, callback); }
  191. /// <inheritdoc/>
  192. public override bool RemoveTimeout (object token) { return _timedEvents.RemoveTimeout (token); }
  193. /// <inheritdoc />
  194. public override void LayoutAndDraw (bool forceDraw)
  195. {
  196. // No more ad-hoc drawing, you must wait for iteration to do it
  197. Application.Top?.SetNeedsDraw();
  198. Application.Top?.SetNeedsLayout ();
  199. }
  200. }