ApplicationImpl.Lifecycle.cs 10 KB

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