ApplicationV2.cs 8.2 KB

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