ApplicationV2.cs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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. bool definetlyUnix = (driverName?.Contains ("unix") ?? false) || _componentFactory is IComponentFactory<char>;
  68. if (definetlyWin)
  69. {
  70. _coordinator = CreateSubcomponents (() => new WindowsComponentFactory ());
  71. }
  72. else if (definetlyNet)
  73. {
  74. _coordinator = CreateSubcomponents (() => new NetComponentFactory ());
  75. }
  76. else if (definetlyUnix)
  77. {
  78. _coordinator = CreateSubcomponents (() => new UnixComponentFactory ());
  79. }
  80. else if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows)
  81. {
  82. _coordinator = CreateSubcomponents (() => new WindowsComponentFactory ());
  83. }
  84. else
  85. {
  86. _coordinator = CreateSubcomponents (() => new UnixComponentFactory ());
  87. }
  88. _coordinator.StartAsync ().Wait ();
  89. if (Application.Driver == null)
  90. {
  91. throw new ("Application.Driver was null even after booting MainLoopCoordinator");
  92. }
  93. }
  94. private IMainLoopCoordinator CreateSubcomponents<T> (Func<IComponentFactory<T>> fallbackFactory)
  95. {
  96. ConcurrentQueue<T> inputBuffer = new ();
  97. MainLoop<T> loop = new ();
  98. IComponentFactory<T> cf;
  99. if (_componentFactory is IComponentFactory<T> typedFactory)
  100. {
  101. cf = typedFactory;
  102. }
  103. else
  104. {
  105. cf = fallbackFactory ();
  106. }
  107. return new MainLoopCoordinator<T> (_timedEvents, inputBuffer, loop, cf);
  108. }
  109. /// <inheritdoc/>
  110. [RequiresUnreferencedCode ("AOT")]
  111. [RequiresDynamicCode ("AOT")]
  112. public override T Run<T> (Func<Exception, bool>? errorHandler = null, IConsoleDriver? driver = null)
  113. {
  114. var top = new T ();
  115. Run (top, errorHandler);
  116. return top;
  117. }
  118. /// <inheritdoc/>
  119. public override void Run (Toplevel view, Func<Exception, bool>? errorHandler = null)
  120. {
  121. Logging.Information ($"Run '{view}'");
  122. ArgumentNullException.ThrowIfNull (view);
  123. if (!Application.Initialized)
  124. {
  125. throw new NotInitializedException (nameof (Run));
  126. }
  127. if (Application.Driver == null)
  128. {
  129. // See Run_T_Init_Driver_Cleared_with_TestTopLevel_Throws
  130. throw new InvalidOperationException ("Driver was inexplicably null when trying to Run view");
  131. }
  132. Application.Top = view;
  133. RunState rs = Application.Begin (view);
  134. Application.Top.Running = true;
  135. // QUESTION: how to know when we are done? - ANSWER: Running == false
  136. while (Application.TopLevels.TryPeek (out Toplevel? found) && found == view && view.Running)
  137. {
  138. if (_coordinator is null)
  139. {
  140. throw new ($"{nameof (IMainLoopCoordinator)}inexplicably became null during Run");
  141. }
  142. _coordinator.RunIteration ();
  143. }
  144. Logging.Information ($"Run - Calling End");
  145. Application.End (rs);
  146. }
  147. /// <inheritdoc/>
  148. public override void Shutdown ()
  149. {
  150. _coordinator?.Stop ();
  151. base.Shutdown ();
  152. Application.Driver = null;
  153. }
  154. /// <inheritdoc/>
  155. public override void RequestStop (Toplevel? top)
  156. {
  157. Logging.Logger.LogInformation ($"RequestStop '{(top is {} ? top : "null")}'");
  158. top ??= Application.Top;
  159. if (top == null)
  160. {
  161. return;
  162. }
  163. var ev = new ToplevelClosingEventArgs (top);
  164. top.OnClosing (ev);
  165. if (ev.Cancel)
  166. {
  167. return;
  168. }
  169. // All RequestStop does is set the Running property to false - In the next iteration
  170. // this will be detected
  171. top.Running = false;
  172. }
  173. /// <inheritdoc/>
  174. public override void Invoke (Action action)
  175. {
  176. // If we are already on the main UI thread
  177. if (Application.MainThreadId == Thread.CurrentThread.ManagedThreadId)
  178. {
  179. action ();
  180. return;
  181. }
  182. _timedEvents.Add (TimeSpan.Zero,
  183. () =>
  184. {
  185. action ();
  186. return false;
  187. }
  188. );
  189. }
  190. /// <inheritdoc/>
  191. public override object AddTimeout (TimeSpan time, Func<bool> callback) { return _timedEvents.Add (time, callback); }
  192. /// <inheritdoc/>
  193. public override bool RemoveTimeout (object token) { return _timedEvents.Remove (token); }
  194. /// <inheritdoc />
  195. public override void LayoutAndDraw (bool forceDraw)
  196. {
  197. // No more ad-hoc drawing, you must wait for iteration to do it
  198. Application.Top?.SetNeedsDraw();
  199. Application.Top?.SetNeedsLayout ();
  200. }
  201. }