2
0

ApplicationV2.cs 8.5 KB

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