2
0

ApplicationV2.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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.Logger.LogInformation ($"Run '{view}'");
  137. ArgumentNullException.ThrowIfNull (view);
  138. if (!Application.Initialized)
  139. {
  140. throw new NotInitializedException (nameof (Run));
  141. }
  142. Application.Top = view;
  143. Application.Begin (view);
  144. // TODO : how to know when we are done?
  145. while (Application.TopLevels.TryPeek (out Toplevel? found) && found == view)
  146. {
  147. if (_coordinator is null)
  148. {
  149. throw new ($"{nameof (IMainLoopCoordinator)}inexplicably became null during Run");
  150. }
  151. _coordinator.RunIteration ();
  152. }
  153. }
  154. /// <inheritdoc/>
  155. public override void Shutdown ()
  156. {
  157. _coordinator?.Stop ();
  158. base.Shutdown ();
  159. Application.Driver = null;
  160. }
  161. /// <inheritdoc/>
  162. public override void RequestStop (Toplevel? top)
  163. {
  164. Logging.Logger.LogInformation ($"RequestStop '{top}'");
  165. top ??= Application.Top;
  166. if (top == null)
  167. {
  168. return;
  169. }
  170. var ev = new ToplevelClosingEventArgs (top);
  171. top.OnClosing (ev);
  172. if (ev.Cancel)
  173. {
  174. return;
  175. }
  176. top.Running = false;
  177. // TODO: This definition of stop seems sketchy
  178. Application.TopLevels.TryPop (out _);
  179. if (Application.TopLevels.Count > 0)
  180. {
  181. Application.Top = Application.TopLevels.Peek ();
  182. }
  183. else
  184. {
  185. Application.Top = null;
  186. }
  187. // Notify that it is closed
  188. top.OnClosed (top);
  189. }
  190. /// <inheritdoc/>
  191. public override void Invoke (Action action)
  192. {
  193. _timedEvents.AddIdle (
  194. () =>
  195. {
  196. action ();
  197. return false;
  198. }
  199. );
  200. }
  201. /// <inheritdoc/>
  202. public override void AddIdle (Func<bool> func) { _timedEvents.AddIdle (func); }
  203. /// <summary>
  204. /// Removes an idle function added by <see cref="AddIdle"/>
  205. /// </summary>
  206. /// <param name="fnTrue">Function to remove</param>
  207. /// <returns>True if it was found and removed</returns>
  208. public bool RemoveIdle (Func<bool> fnTrue) { return _timedEvents.RemoveIdle (fnTrue); }
  209. /// <inheritdoc/>
  210. public override object AddTimeout (TimeSpan time, Func<bool> callback) { return _timedEvents.AddTimeout (time, callback); }
  211. /// <inheritdoc/>
  212. public override bool RemoveTimeout (object token) { return _timedEvents.RemoveTimeout (token); }
  213. /// <inheritdoc />
  214. public override void LayoutAndDraw (bool forceDraw)
  215. {
  216. // No more ad-hoc drawing, you must wait for iteration to do it
  217. Application.Top?.SetNeedsDraw();
  218. Application.Top?.SetNeedsLayout ();
  219. }
  220. }