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