ApplicationV2.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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. SynchronizationContext.SetSynchronizationContext (new MainLoopSyncContext ());
  67. Application.MainThreadId = Thread.CurrentThread.ManagedThreadId;
  68. }
  69. private void CreateDriver (string? driverName)
  70. {
  71. PlatformID p = Environment.OSVersion.Platform;
  72. bool definetlyWin = driverName?.Contains ("win") ?? false;
  73. bool definetlyNet = driverName?.Contains ("net") ?? false;
  74. if (definetlyWin)
  75. {
  76. _coordinator = CreateWindowsSubcomponents ();
  77. }
  78. else if (definetlyNet)
  79. {
  80. _coordinator = CreateNetSubcomponents ();
  81. }
  82. else if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows)
  83. {
  84. _coordinator = CreateWindowsSubcomponents ();
  85. }
  86. else
  87. {
  88. _coordinator = CreateNetSubcomponents ();
  89. }
  90. _coordinator.StartAsync ().Wait ();
  91. if (Application.Driver == null)
  92. {
  93. throw new ("Application.Driver was null even after booting MainLoopCoordinator");
  94. }
  95. }
  96. private IMainLoopCoordinator CreateWindowsSubcomponents ()
  97. {
  98. ConcurrentQueue<WindowsConsole.InputRecord> inputBuffer = new ();
  99. MainLoop<WindowsConsole.InputRecord> loop = new ();
  100. return new MainLoopCoordinator<WindowsConsole.InputRecord> (
  101. _timedEvents,
  102. _winInputFactory,
  103. inputBuffer,
  104. new WindowsInputProcessor (inputBuffer),
  105. _winOutputFactory,
  106. loop);
  107. }
  108. private IMainLoopCoordinator CreateNetSubcomponents ()
  109. {
  110. ConcurrentQueue<ConsoleKeyInfo> inputBuffer = new ();
  111. MainLoop<ConsoleKeyInfo> loop = new ();
  112. return new MainLoopCoordinator<ConsoleKeyInfo> (
  113. _timedEvents,
  114. _netInputFactory,
  115. inputBuffer,
  116. new NetInputProcessor (inputBuffer),
  117. _netOutputFactory,
  118. loop);
  119. }
  120. /// <inheritdoc/>
  121. [RequiresUnreferencedCode ("AOT")]
  122. [RequiresDynamicCode ("AOT")]
  123. public override T Run<T> (Func<Exception, bool>? errorHandler = null, IConsoleDriver? driver = null)
  124. {
  125. var top = new T ();
  126. Run (top, errorHandler);
  127. return top;
  128. }
  129. /// <inheritdoc/>
  130. public override void Run (Toplevel view, Func<Exception, bool>? errorHandler = null)
  131. {
  132. Logging.Logger.LogInformation ($"Run '{view}'");
  133. ArgumentNullException.ThrowIfNull (view);
  134. if (!Application.Initialized)
  135. {
  136. throw new NotInitializedException (nameof (Run));
  137. }
  138. Application.Top = view;
  139. Application.Begin (view);
  140. // TODO : how to know when we are done?
  141. while (Application.TopLevels.TryPeek (out Toplevel? found) && found == view)
  142. {
  143. if (_coordinator is null)
  144. {
  145. throw new ($"{nameof (IMainLoopCoordinator)}inexplicably became null during Run");
  146. }
  147. _coordinator.RunIteration ();
  148. }
  149. }
  150. /// <inheritdoc/>
  151. public override void Shutdown ()
  152. {
  153. _coordinator?.Stop ();
  154. base.Shutdown ();
  155. Application.Driver = null;
  156. }
  157. /// <inheritdoc/>
  158. public override void RequestStop (Toplevel? top)
  159. {
  160. Logging.Logger.LogInformation ($"RequestStop '{top}'");
  161. // TODO: This definition of stop seems sketchy
  162. Application.TopLevels.TryPop (out _);
  163. if (Application.TopLevels.Count > 0)
  164. {
  165. Application.Top = Application.TopLevels.Peek ();
  166. }
  167. else
  168. {
  169. Application.Top = null;
  170. }
  171. }
  172. /// <inheritdoc/>
  173. public override void Invoke (Action action)
  174. {
  175. _timedEvents.AddIdle (
  176. () =>
  177. {
  178. action ();
  179. return false;
  180. }
  181. );
  182. }
  183. /// <inheritdoc/>
  184. public override void AddIdle (Func<bool> func) { _timedEvents.AddIdle (func); }
  185. /// <summary>
  186. /// Removes an idle function added by <see cref="AddIdle"/>
  187. /// </summary>
  188. /// <param name="fnTrue">Function to remove</param>
  189. /// <returns>True if it was found and removed</returns>
  190. public bool RemoveIdle (Func<bool> fnTrue) { return _timedEvents.RemoveIdle (fnTrue); }
  191. /// <inheritdoc/>
  192. public override object AddTimeout (TimeSpan time, Func<bool> callback) { return _timedEvents.AddTimeout (time, callback); }
  193. /// <inheritdoc/>
  194. public override bool RemoveTimeout (object token) { return _timedEvents.RemoveTimeout (token); }
  195. /// <inheritdoc />
  196. public override void LayoutAndDraw (bool forceDraw)
  197. {
  198. // No more ad-hoc drawing, you must wait for iteration to do it
  199. Application.Top?.SetNeedsDraw();
  200. Application.Top?.SetNeedsLayout ();
  201. }
  202. }