ApplicationV2.cs 8.4 KB

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