ApplicationImpl.Lifecycle.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. using System.Diagnostics;
  2. using System.Diagnostics.CodeAnalysis;
  3. namespace Terminal.Gui.App;
  4. public partial class ApplicationImpl
  5. {
  6. /// <inheritdoc/>
  7. public bool Initialized { get; set; }
  8. /// <inheritdoc/>
  9. public event EventHandler<EventArgs<bool>>? InitializedChanged;
  10. /// <inheritdoc/>
  11. [RequiresUnreferencedCode ("AOT")]
  12. [RequiresDynamicCode ("AOT")]
  13. public IApplication Init (string? driverName = null)
  14. {
  15. if (Initialized)
  16. {
  17. Logging.Error ("Init called multiple times without shutdown, aborting.");
  18. throw new InvalidOperationException ("Init called multiple times without Shutdown");
  19. }
  20. // Check the fence: ensure we're not mixing application models
  21. // If this is a legacy static instance and instance-based model was used, throw
  22. if (this == _instance && _modelUsage == ApplicationModelUsage.InstanceBased)
  23. {
  24. throw new InvalidOperationException (
  25. "Cannot use legacy static Application model (Application.Init/ApplicationImpl.Instance) after using modern instance-based model (Application.Create). " +
  26. "Use only one model per process.");
  27. }
  28. // If this is an instance-based instance and legacy static model was used, throw
  29. if (this != _instance && _modelUsage == ApplicationModelUsage.LegacyStatic)
  30. {
  31. throw new InvalidOperationException (
  32. "Cannot use modern instance-based model (Application.Create) after using legacy static Application model (Application.Init/ApplicationImpl.Instance). " +
  33. "Use only one model per process.");
  34. }
  35. if (!string.IsNullOrWhiteSpace (driverName))
  36. {
  37. _driverName = driverName;
  38. }
  39. if (string.IsNullOrWhiteSpace (_driverName))
  40. {
  41. _driverName = ForceDriver;
  42. }
  43. // Debug.Assert (Navigation is null);
  44. // Navigation = new ();
  45. //Debug.Assert (Popover is null);
  46. //Popover = new ();
  47. // Preserve existing keyboard settings if they exist
  48. bool hasExistingKeyboard = _keyboard is { };
  49. Key existingQuitKey = _keyboard?.QuitKey ?? Key.Esc;
  50. Key existingArrangeKey = _keyboard?.ArrangeKey ?? Key.F5.WithCtrl;
  51. Key existingNextTabKey = _keyboard?.NextTabKey ?? Key.Tab;
  52. Key existingPrevTabKey = _keyboard?.PrevTabKey ?? Key.Tab.WithShift;
  53. Key existingNextTabGroupKey = _keyboard?.NextTabGroupKey ?? Key.F6;
  54. Key existingPrevTabGroupKey = _keyboard?.PrevTabGroupKey ?? Key.F6.WithShift;
  55. // Reset keyboard to ensure fresh state with default bindings
  56. _keyboard = new KeyboardImpl { App = this };
  57. // Restore previously set keys if they existed and were different from defaults
  58. if (hasExistingKeyboard)
  59. {
  60. _keyboard.QuitKey = existingQuitKey;
  61. _keyboard.ArrangeKey = existingArrangeKey;
  62. _keyboard.NextTabKey = existingNextTabKey;
  63. _keyboard.PrevTabKey = existingPrevTabKey;
  64. _keyboard.NextTabGroupKey = existingNextTabGroupKey;
  65. _keyboard.PrevTabGroupKey = existingPrevTabGroupKey;
  66. }
  67. CreateDriver (_driverName);
  68. Screen = Driver!.Screen;
  69. Initialized = true;
  70. RaiseInitializedChanged (this, new (true));
  71. SubscribeDriverEvents ();
  72. SynchronizationContext.SetSynchronizationContext (new ());
  73. MainThreadId = Thread.CurrentThread.ManagedThreadId;
  74. return this;
  75. }
  76. /// <summary>Shutdown an application initialized with <see cref="Init"/>.</summary>
  77. public object? Shutdown ()
  78. {
  79. // Extract result from framework-owned runnable before disposal
  80. object? result = null;
  81. IRunnable? runnableToDispose = FrameworkOwnedRunnable;
  82. if (runnableToDispose is { })
  83. {
  84. // Extract the result using reflection to get the Result property value
  85. var resultProperty = runnableToDispose.GetType().GetProperty("Result");
  86. result = resultProperty?.GetValue(runnableToDispose);
  87. }
  88. // Stop the coordinator if running
  89. Coordinator?.Stop ();
  90. // Capture state before cleanup
  91. bool wasInitialized = Initialized;
  92. #if DEBUG
  93. // Check that all Application events have no remaining subscribers BEFORE clearing them
  94. // Only check if we were actually initialized
  95. if (wasInitialized)
  96. {
  97. AssertNoEventSubscribers (nameof (Iteration), Iteration);
  98. AssertNoEventSubscribers (nameof (SessionBegun), SessionBegun);
  99. AssertNoEventSubscribers (nameof (SessionEnded), SessionEnded);
  100. AssertNoEventSubscribers (nameof (ScreenChanged), ScreenChanged);
  101. //AssertNoEventSubscribers (nameof (InitializedChanged), InitializedChanged);
  102. }
  103. #endif
  104. // Dispose the framework-owned runnable if it exists
  105. if (runnableToDispose is { })
  106. {
  107. if (runnableToDispose is IDisposable disposable)
  108. {
  109. disposable.Dispose();
  110. }
  111. FrameworkOwnedRunnable = null;
  112. }
  113. // Clean up all application state (including sync context)
  114. // ResetState handles the case where Initialized is false
  115. ResetState ();
  116. // Configuration manager diagnostics
  117. ConfigurationManager.PrintJsonErrors ();
  118. // Raise the initialized changed event to notify shutdown
  119. if (wasInitialized)
  120. {
  121. bool init = Initialized; // Will be false after ResetState
  122. RaiseInitializedChanged (this, new (in init));
  123. }
  124. // Clear the event to prevent memory leaks
  125. InitializedChanged = null;
  126. return result;
  127. }
  128. #if DEBUG
  129. /// <summary>
  130. /// DEBUG ONLY: Asserts that an event has no remaining subscribers.
  131. /// </summary>
  132. /// <param name="eventName">The name of the event for diagnostic purposes.</param>
  133. /// <param name="eventDelegate">The event delegate to check.</param>
  134. private static void AssertNoEventSubscribers (string eventName, Delegate? eventDelegate)
  135. {
  136. if (eventDelegate is null)
  137. {
  138. return;
  139. }
  140. Delegate [] subscribers = eventDelegate.GetInvocationList ();
  141. if (subscribers.Length > 0)
  142. {
  143. string subscriberInfo = string.Join (
  144. ", ",
  145. subscribers.Select (d => $"{d.Method.DeclaringType?.Name}.{d.Method.Name}"
  146. )
  147. );
  148. Debug.Fail (
  149. $"Application.{eventName} has {subscribers.Length} remaining subscriber(s) after Shutdown: {subscriberInfo}"
  150. );
  151. }
  152. }
  153. #endif
  154. /// <inheritdoc/>
  155. public void ResetState (bool ignoreDisposed = false)
  156. {
  157. // Shutdown is the bookend for Init. As such it needs to clean up all resources
  158. // Init created. Apps that do any threading will need to code defensively for this.
  159. // e.g. see Issue #537
  160. // === 0. Stop all timers ===
  161. TimedEvents?.StopAll ();
  162. // === 1. Stop all running toplevels ===
  163. foreach (Toplevel t in SessionStack)
  164. {
  165. t.Running = false;
  166. }
  167. // === 2. Close and dispose popover ===
  168. if (Popover?.GetActivePopover () is View popover)
  169. {
  170. // This forcefully closes the popover; invoking Command.Quit would be more graceful
  171. // but since this is shutdown, doing this is ok.
  172. popover.Visible = false;
  173. }
  174. // Any popovers added to Popover have their lifetime controlled by Popover
  175. Popover?.Dispose ();
  176. Popover = null;
  177. // === 3. Clean up toplevels ===
  178. SessionStack.Clear ();
  179. RunnableSessionStack?.Clear ();
  180. #if DEBUG_IDISPOSABLE
  181. // Don't dispose the TopRunnable. It's up to caller dispose it
  182. if (View.EnableDebugIDisposableAsserts && !ignoreDisposed && TopRunnable is { })
  183. {
  184. Debug.Assert (TopRunnable.WasDisposed, $"Title = {TopRunnable.Title}, Id = {TopRunnable.Id}");
  185. // If End wasn't called _CachedSessionTokenToplevel may be null
  186. if (CachedSessionTokenToplevel is { })
  187. {
  188. Debug.Assert (CachedSessionTokenToplevel.WasDisposed);
  189. Debug.Assert (CachedSessionTokenToplevel == TopRunnable);
  190. }
  191. }
  192. #endif
  193. TopRunnable = null;
  194. CachedSessionTokenToplevel = null;
  195. // === 4. Clean up driver ===
  196. if (Driver is { })
  197. {
  198. UnsubscribeDriverEvents ();
  199. Driver?.End ();
  200. Driver = null;
  201. }
  202. // Reset screen
  203. ResetScreen ();
  204. _screen = null;
  205. // === 5. Clear run state ===
  206. Iteration = null;
  207. SessionBegun = null;
  208. SessionEnded = null;
  209. StopAfterFirstIteration = false;
  210. ClearScreenNextIteration = false;
  211. // === 6. Reset input systems ===
  212. // Mouse and Keyboard will be lazy-initialized on next access
  213. _mouse = null;
  214. _keyboard = null;
  215. Mouse.ResetState ();
  216. // === 7. Clear navigation and screen state ===
  217. ScreenChanged = null;
  218. //Navigation = null;
  219. // === 8. Reset initialization state ===
  220. Initialized = false;
  221. MainThreadId = null;
  222. // === 9. Clear graphics ===
  223. Sixel.Clear ();
  224. // === 10. Reset ForceDriver ===
  225. // Note: ForceDriver and Force16Colors are reset
  226. // If they need to persist across Init/Shutdown cycles
  227. // then the user of the library should manage that state
  228. Force16Colors = false;
  229. ForceDriver = string.Empty;
  230. // === 11. Reset synchronization context ===
  231. // IMPORTANT: Always reset sync context, even if not initialized
  232. // This ensures cleanup works correctly even if Shutdown is called without Init
  233. // Reset synchronization context to allow the user to run async/await,
  234. // as the main loop has been ended, the synchronization context from
  235. // gui.cs does no longer process any callbacks. See #1084 for more details:
  236. // (https://github.com/gui-cs/Terminal.Gui/issues/1084).
  237. SynchronizationContext.SetSynchronizationContext (null);
  238. }
  239. /// <summary>
  240. /// Raises the <see cref="InitializedChanged"/> event.
  241. /// </summary>
  242. internal void RaiseInitializedChanged (object sender, EventArgs<bool> e) { InitializedChanged?.Invoke (sender, e); }
  243. }