ApplicationImpl.Lifecycle.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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 (IDriver? driver = null, 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. // Create a new lazy instance for potential future Init
  93. _lazyInstance = new (() => new ApplicationImpl ());
  94. }
  95. #if DEBUG
  96. /// <summary>
  97. /// DEBUG ONLY: Asserts that an event has no remaining subscribers.
  98. /// </summary>
  99. /// <param name="eventName">The name of the event for diagnostic purposes.</param>
  100. /// <param name="eventDelegate">The event delegate to check.</param>
  101. private static void AssertNoEventSubscribers (string eventName, Delegate? eventDelegate)
  102. {
  103. if (eventDelegate is null)
  104. {
  105. return;
  106. }
  107. Delegate [] subscribers = eventDelegate.GetInvocationList ();
  108. if (subscribers.Length > 0)
  109. {
  110. string subscriberInfo = string.Join (
  111. ", ",
  112. subscribers.Select (d => $"{d.Method.DeclaringType?.Name}.{d.Method.Name}"
  113. )
  114. );
  115. Debug.Fail (
  116. $"Application.{eventName} has {subscribers.Length} remaining subscriber(s) after Shutdown: {subscriberInfo}"
  117. );
  118. }
  119. }
  120. #endif
  121. /// <inheritdoc/>
  122. public void ResetState (bool ignoreDisposed = false)
  123. {
  124. // Shutdown is the bookend for Init. As such it needs to clean up all resources
  125. // Init created. Apps that do any threading will need to code defensively for this.
  126. // e.g. see Issue #537
  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. Popover?.Dispose ();
  140. Popover = null;
  141. // === 3. Clean up toplevels ===
  142. SessionStack.Clear ();
  143. #if DEBUG_IDISPOSABLE
  144. // Don't dispose the Current. It's up to caller dispose it
  145. if (View.EnableDebugIDisposableAsserts && !ignoreDisposed && Current is { })
  146. {
  147. Debug.Assert (Current.WasDisposed, $"Title = {Current.Title}, Id = {Current.Id}");
  148. // If End wasn't called _CachedSessionTokenToplevel may be null
  149. if (CachedSessionTokenToplevel is { })
  150. {
  151. Debug.Assert (CachedSessionTokenToplevel.WasDisposed);
  152. Debug.Assert (CachedSessionTokenToplevel == Current);
  153. }
  154. }
  155. #endif
  156. Current = null;
  157. CachedSessionTokenToplevel = null;
  158. // === 4. Clean up driver ===
  159. if (Driver is { })
  160. {
  161. UnsubscribeDriverEvents ();
  162. Driver?.End ();
  163. Driver = null;
  164. }
  165. // Reset screen
  166. ResetScreen ();
  167. _screen = null;
  168. // === 5. Clear run state ===
  169. Iteration = null;
  170. SessionBegun = null;
  171. SessionEnded = null;
  172. StopAfterFirstIteration = false;
  173. ClearScreenNextIteration = false;
  174. // === 6. Reset input systems ===
  175. // Mouse and Keyboard will be lazy-initialized on next access
  176. _mouse = null;
  177. _keyboard = null;
  178. Mouse.ResetState ();
  179. // === 7. Clear navigation and screen state ===
  180. ScreenChanged = null;
  181. //Navigation = null;
  182. // === 8. Reset initialization state ===
  183. Initialized = false;
  184. MainThreadId = null;
  185. // === 9. Clear graphics ===
  186. Sixel.Clear ();
  187. // === 10. Reset synchronization context ===
  188. // IMPORTANT: Always reset sync context, even if not initialized
  189. // This ensures cleanup works correctly even if Shutdown is called without Init
  190. // Reset synchronization context to allow the user to run async/await,
  191. // as the main loop has been ended, the synchronization context from
  192. // gui.cs does no longer process any callbacks. See #1084 for more details:
  193. // (https://github.com/gui-cs/Terminal.Gui/issues/1084).
  194. SynchronizationContext.SetSynchronizationContext (null);
  195. // Note: ForceDriver and Force16Colors are NOT reset;
  196. // they need to persist across Init/Shutdown cycles
  197. }
  198. /// <summary>
  199. /// Raises the <see cref="InitializedChanged"/> event.
  200. /// </summary>
  201. internal void RaiseInitializedChanged (object sender, EventArgs<bool> e) { InitializedChanged?.Invoke (sender, e); }
  202. }