ApplicationV2.cs 8.5 KB

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