ApplicationImpl.Lifecycle.cs 8.5 KB

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