ApplicationImpl.Run.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. using System.Diagnostics;
  2. using System.Diagnostics.CodeAnalysis;
  3. namespace Terminal.Gui.App;
  4. public partial class ApplicationImpl
  5. {
  6. /// <summary>
  7. /// INTERNAL: Gets or sets the managed thread ID of the application's main UI thread, which is set during
  8. /// <see cref="Init"/> and used to determine if code is executing on the main thread.
  9. /// </summary>
  10. /// <value>
  11. /// The managed thread ID of the main UI thread, or <see langword="null"/> if the application is not initialized.
  12. /// </value>
  13. internal int? MainThreadId { get; set; }
  14. #region Begin->Run->Stop->End
  15. /// <inheritdoc/>
  16. public event EventHandler<SessionTokenEventArgs>? SessionBegun;
  17. /// <inheritdoc/>
  18. public event EventHandler<ToplevelEventArgs>? SessionEnded;
  19. /// <inheritdoc/>
  20. public SessionToken Begin (Toplevel toplevel)
  21. {
  22. ArgumentNullException.ThrowIfNull (toplevel);
  23. // Ensure the mouse is ungrabbed.
  24. if (Mouse.MouseGrabView is { })
  25. {
  26. Mouse.UngrabMouse ();
  27. }
  28. var rs = new SessionToken (toplevel);
  29. #if DEBUG_IDISPOSABLE
  30. if (View.EnableDebugIDisposableAsserts && Current is { } && toplevel != Current && !SessionStack.Contains (Current))
  31. {
  32. // This assertion confirm if the Current was already disposed
  33. Debug.Assert (Current.WasDisposed);
  34. Debug.Assert (Current == CachedSessionTokenToplevel);
  35. }
  36. #endif
  37. lock (SessionStack)
  38. {
  39. if (Current is { } && toplevel != Current && !SessionStack.Contains (Current))
  40. {
  41. // If Current was already disposed and isn't on the Toplevels Stack,
  42. // clean it up here if is the same as _CachedSessionTokenToplevel
  43. if (Current == CachedSessionTokenToplevel)
  44. {
  45. Current = null;
  46. }
  47. else
  48. {
  49. // Probably this will never hit
  50. throw new ObjectDisposedException (Current.GetType ().FullName);
  51. }
  52. }
  53. // BUGBUG: We should not depend on `Id` internally.
  54. // BUGBUG: It is super unclear what this code does anyway.
  55. if (string.IsNullOrEmpty (toplevel.Id))
  56. {
  57. var count = 1;
  58. var id = (SessionStack.Count + count).ToString ();
  59. while (SessionStack.Count > 0 && SessionStack.FirstOrDefault (x => x.Id == id) is { })
  60. {
  61. count++;
  62. id = (SessionStack.Count + count).ToString ();
  63. }
  64. toplevel.Id = (SessionStack.Count + count).ToString ();
  65. SessionStack.Push (toplevel);
  66. }
  67. else
  68. {
  69. Toplevel? dup = SessionStack.FirstOrDefault (x => x.Id == toplevel.Id);
  70. if (dup is null)
  71. {
  72. SessionStack.Push (toplevel);
  73. }
  74. }
  75. }
  76. if (Current is null)
  77. {
  78. Current = toplevel;
  79. }
  80. if ((Current?.Modal == false && toplevel.Modal)
  81. || (Current?.Modal == false && !toplevel.Modal)
  82. || (Current?.Modal == true && toplevel.Modal))
  83. {
  84. if (toplevel.Visible)
  85. {
  86. if (Current is { HasFocus: true })
  87. {
  88. Current.HasFocus = false;
  89. }
  90. // Force leave events for any entered views in the old Current
  91. if (Mouse.GetLastMousePosition () is { })
  92. {
  93. Mouse.RaiseMouseEnterLeaveEvents (Mouse.GetLastMousePosition ()!.Value, new ());
  94. }
  95. Current?.OnDeactivate (toplevel);
  96. Toplevel previousTop = Current!;
  97. Current = toplevel;
  98. Current.OnActivate (previousTop);
  99. }
  100. }
  101. // View implements ISupportInitializeNotification which is derived from ISupportInitialize
  102. if (!toplevel.IsInitialized)
  103. {
  104. toplevel.BeginInit ();
  105. toplevel.EndInit (); // Calls Layout
  106. }
  107. // Try to set initial focus to any TabStop
  108. if (!toplevel.HasFocus)
  109. {
  110. toplevel.SetFocus ();
  111. }
  112. toplevel.OnLoaded ();
  113. Instance.LayoutAndDraw (true);
  114. if (PositionCursor ())
  115. {
  116. Driver?.UpdateCursor ();
  117. }
  118. SessionBegun?.Invoke (this, new (rs));
  119. return rs;
  120. }
  121. /// <inheritdoc/>
  122. public bool StopAfterFirstIteration { get; set; }
  123. /// <inheritdoc/>
  124. public event EventHandler<IterationEventArgs>? Iteration;
  125. /// <inheritdoc/>
  126. [RequiresUnreferencedCode ("AOT")]
  127. [RequiresDynamicCode ("AOT")]
  128. public Toplevel Run (Func<Exception, bool>? errorHandler = null, string? driver = null) { return Run<Toplevel> (errorHandler, driver); }
  129. /// <inheritdoc/>
  130. [RequiresUnreferencedCode ("AOT")]
  131. [RequiresDynamicCode ("AOT")]
  132. public TView Run<TView> (Func<Exception, bool>? errorHandler = null, string? driver = null)
  133. where TView : Toplevel, new ()
  134. {
  135. if (!Initialized)
  136. {
  137. // Init() has NOT been called. Auto-initialize as per interface contract.
  138. Init (null, driver);
  139. }
  140. TView top = new ();
  141. Run (top, errorHandler);
  142. return top;
  143. }
  144. /// <inheritdoc/>
  145. public void Run (Toplevel view, Func<Exception, bool>? errorHandler = null)
  146. {
  147. Logging.Information ($"Run '{view}'");
  148. ArgumentNullException.ThrowIfNull (view);
  149. if (!Initialized)
  150. {
  151. throw new NotInitializedException (nameof (Run));
  152. }
  153. if (Driver == null)
  154. {
  155. throw new InvalidOperationException ("Driver was inexplicably null when trying to Run view");
  156. }
  157. Current = view;
  158. SessionToken rs = Application.Begin (view);
  159. Current.Running = true;
  160. var firstIteration = true;
  161. while (SessionStack.TryPeek (out Toplevel? found) && found == view && view.Running)
  162. {
  163. if (Coordinator is null)
  164. {
  165. throw new ($"{nameof (IMainLoopCoordinator)} inexplicably became null during Run");
  166. }
  167. Coordinator.RunIteration ();
  168. if (StopAfterFirstIteration && firstIteration)
  169. {
  170. Logging.Information ("Run - Stopping after first iteration as requested");
  171. view.RequestStop ();
  172. }
  173. firstIteration = false;
  174. }
  175. Logging.Information ("Run - Calling End");
  176. Application.End (rs);
  177. }
  178. /// <inheritdoc/>
  179. public void End (SessionToken sessionToken)
  180. {
  181. ArgumentNullException.ThrowIfNull (sessionToken);
  182. if (Popover?.GetActivePopover () as View is { Visible: true } visiblePopover)
  183. {
  184. ApplicationPopover.HideWithQuitCommand (visiblePopover);
  185. }
  186. sessionToken.Toplevel.OnUnloaded ();
  187. // End the Session
  188. // First, take it off the Toplevel Stack
  189. if (SessionStack.TryPop (out Toplevel? topOfStack))
  190. {
  191. if (topOfStack != sessionToken.Toplevel)
  192. {
  193. // If the top of the stack is not the SessionToken.Toplevel then
  194. // this call to End is not balanced with the call to Begin that started the Session
  195. throw new ArgumentException ("End must be balanced with calls to Begin");
  196. }
  197. }
  198. // Notify that it is closing
  199. sessionToken.Toplevel?.OnClosed (sessionToken.Toplevel);
  200. if (SessionStack.TryPeek (out Toplevel? newTop))
  201. {
  202. Current = newTop;
  203. Current?.SetNeedsDraw ();
  204. }
  205. if (sessionToken.Toplevel is { HasFocus: true })
  206. {
  207. sessionToken.Toplevel.HasFocus = false;
  208. }
  209. if (Current is { HasFocus: false })
  210. {
  211. Current.SetFocus ();
  212. }
  213. CachedSessionTokenToplevel = sessionToken.Toplevel;
  214. sessionToken.Toplevel = null;
  215. sessionToken.Dispose ();
  216. // BUGBUG: Why layout and draw here? This causes the screen to be cleared!
  217. //LayoutAndDraw (true);
  218. SessionEnded?.Invoke (this, new (CachedSessionTokenToplevel));
  219. }
  220. /// <inheritdoc/>
  221. public void RequestStop () { RequestStop (null); }
  222. /// <inheritdoc/>
  223. public void RequestStop (Toplevel? top)
  224. {
  225. Logging.Trace ($"Current: '{(top is { } ? top : "null")}'");
  226. top ??= Current;
  227. if (top == null)
  228. {
  229. return;
  230. }
  231. ToplevelClosingEventArgs ev = new (top);
  232. top.OnClosing (ev);
  233. if (ev.Cancel)
  234. {
  235. return;
  236. }
  237. top.Running = false;
  238. }
  239. /// <inheritdoc/>
  240. public void RaiseIteration () { Iteration?.Invoke (null, new ()); }
  241. #endregion Begin->Run->Stop->End
  242. #region Timeouts and Invoke
  243. private readonly ITimedEvents _timedEvents = new TimedEvents ();
  244. /// <inheritdoc/>
  245. public ITimedEvents? TimedEvents => _timedEvents;
  246. /// <inheritdoc/>
  247. public object AddTimeout (TimeSpan time, Func<bool> callback) { return _timedEvents.Add (time, callback); }
  248. /// <inheritdoc/>
  249. public bool RemoveTimeout (object token) { return _timedEvents.Remove (token); }
  250. /// <inheritdoc/>
  251. public void Invoke (Action action)
  252. {
  253. // If we are already on the main UI thread
  254. if (Current is { Running: true } && MainThreadId == Thread.CurrentThread.ManagedThreadId)
  255. {
  256. action ();
  257. return;
  258. }
  259. _timedEvents.Add (
  260. TimeSpan.Zero,
  261. () =>
  262. {
  263. action ();
  264. return false;
  265. }
  266. );
  267. }
  268. #endregion Timeouts and Invoke
  269. }