ApplicationImpl.Lifecycle.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. #nullable enable
  2. using System.Diagnostics;
  3. using System.Diagnostics.CodeAnalysis;
  4. namespace Terminal.Gui.App;
  5. public partial class ApplicationImpl
  6. {
  7. /// <inheritdoc/>
  8. public bool Initialized { get; set; }
  9. /// <inheritdoc/>
  10. public event EventHandler<EventArgs<bool>>? InitializedChanged;
  11. /// <inheritdoc/>
  12. [RequiresUnreferencedCode ("AOT")]
  13. [RequiresDynamicCode ("AOT")]
  14. public void Init (IDriver? driver = null, string? driverName = null)
  15. {
  16. if (Initialized)
  17. {
  18. Logging.Error ("Init called multiple times without shutdown, aborting.");
  19. throw new InvalidOperationException ("Init called multiple times without Shutdown");
  20. }
  21. if (!string.IsNullOrWhiteSpace (driverName))
  22. {
  23. _driverName = driverName;
  24. }
  25. if (string.IsNullOrWhiteSpace (_driverName))
  26. {
  27. _driverName = ForceDriver;
  28. }
  29. Debug.Assert (Navigation is null);
  30. Navigation = new ();
  31. Debug.Assert (Popover is null);
  32. Popover = new ();
  33. // Preserve existing keyboard settings if they exist
  34. bool hasExistingKeyboard = _keyboard is { };
  35. Key existingQuitKey = _keyboard?.QuitKey ?? Key.Esc;
  36. Key existingArrangeKey = _keyboard?.ArrangeKey ?? Key.F5.WithCtrl;
  37. Key existingNextTabKey = _keyboard?.NextTabKey ?? Key.Tab;
  38. Key existingPrevTabKey = _keyboard?.PrevTabKey ?? Key.Tab.WithShift;
  39. Key existingNextTabGroupKey = _keyboard?.NextTabGroupKey ?? Key.F6;
  40. Key existingPrevTabGroupKey = _keyboard?.PrevTabGroupKey ?? Key.F6.WithShift;
  41. // Reset keyboard to ensure fresh state with default bindings
  42. _keyboard = new KeyboardImpl { Application = this };
  43. // Restore previously set keys if they existed and were different from defaults
  44. if (hasExistingKeyboard)
  45. {
  46. _keyboard.QuitKey = existingQuitKey;
  47. _keyboard.ArrangeKey = existingArrangeKey;
  48. _keyboard.NextTabKey = existingNextTabKey;
  49. _keyboard.PrevTabKey = existingPrevTabKey;
  50. _keyboard.NextTabGroupKey = existingNextTabGroupKey;
  51. _keyboard.PrevTabGroupKey = existingPrevTabGroupKey;
  52. }
  53. CreateDriver (driverName ?? _driverName);
  54. Screen = Driver!.Screen;
  55. Initialized = true;
  56. RaiseInitializedChanged (this, new (true));
  57. SubscribeDriverEvents ();
  58. SynchronizationContext.SetSynchronizationContext (new ());
  59. MainThreadId = Thread.CurrentThread.ManagedThreadId;
  60. }
  61. /// <summary>Shutdown an application initialized with <see cref="Init"/>.</summary>
  62. public void Shutdown ()
  63. {
  64. // Stop the coordinator if running
  65. Coordinator?.Stop ();
  66. // Capture state before cleanup
  67. bool wasInitialized = Initialized;
  68. #if DEBUG
  69. // Check that all Application events have no remaining subscribers BEFORE clearing them
  70. // Only check if we were actually initialized
  71. if (wasInitialized)
  72. {
  73. AssertNoEventSubscribers (nameof (Iteration), Iteration);
  74. AssertNoEventSubscribers (nameof (SessionBegun), SessionBegun);
  75. AssertNoEventSubscribers (nameof (SessionEnded), SessionEnded);
  76. AssertNoEventSubscribers (nameof (ScreenChanged), ScreenChanged);
  77. //AssertNoEventSubscribers (nameof (InitializedChanged), InitializedChanged);
  78. }
  79. #endif
  80. // Clean up all application state (including sync context)
  81. // ResetState handles the case where Initialized is false
  82. ResetState ();
  83. // Configuration manager diagnostics
  84. ConfigurationManager.PrintJsonErrors ();
  85. // Raise the initialized changed event to notify shutdown
  86. if (wasInitialized)
  87. {
  88. bool init = Initialized; // Will be false after ResetState
  89. RaiseInitializedChanged (this, new (in init));
  90. }
  91. // Clear the event to prevent memory leaks
  92. InitializedChanged = null;
  93. // Create a new lazy instance for potential future Init
  94. _lazyInstance = new (() => new ApplicationImpl ());
  95. }
  96. #if DEBUG
  97. /// <summary>
  98. /// DEBUG ONLY: Asserts that an event has no remaining subscribers.
  99. /// </summary>
  100. /// <param name="eventName">The name of the event for diagnostic purposes.</param>
  101. /// <param name="eventDelegate">The event delegate to check.</param>
  102. private static void AssertNoEventSubscribers (string eventName, Delegate? eventDelegate)
  103. {
  104. if (eventDelegate is null)
  105. {
  106. return;
  107. }
  108. Delegate [] subscribers = eventDelegate.GetInvocationList ();
  109. if (subscribers.Length > 0)
  110. {
  111. string subscriberInfo = string.Join (
  112. ", ",
  113. subscribers.Select (d => $"{d.Method.DeclaringType?.Name}.{d.Method.Name}"
  114. )
  115. );
  116. Debug.Fail (
  117. $"Application.{eventName} has {subscribers.Length} remaining subscriber(s) after Shutdown: {subscriberInfo}"
  118. );
  119. }
  120. }
  121. #endif
  122. /// <inheritdoc/>
  123. public void ResetState (bool ignoreDisposed = false)
  124. {
  125. // Shutdown is the bookend for Init. As such it needs to clean up all resources
  126. // Init created. Apps that do any threading will need to code defensively for this.
  127. // e.g. see Issue #537
  128. // === 1. Stop all running toplevels ===
  129. foreach (Toplevel? t in TopLevels)
  130. {
  131. t!.Running = false;
  132. }
  133. // === 2. Close and dispose popover ===
  134. if (Popover?.GetActivePopover () is View popover)
  135. {
  136. // This forcefully closes the popover; invoking Command.Quit would be more graceful
  137. // but since this is shutdown, doing this is ok.
  138. popover.Visible = false;
  139. }
  140. Popover?.Dispose ();
  141. Popover = null;
  142. // === 3. Clean up toplevels ===
  143. TopLevels.Clear ();
  144. #if DEBUG_IDISPOSABLE
  145. // Don't dispose the Top. It's up to caller dispose it
  146. if (View.EnableDebugIDisposableAsserts && !ignoreDisposed && Top is { })
  147. {
  148. Debug.Assert (Top.WasDisposed, $"Title = {Top.Title}, Id = {Top.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 == Top);
  154. }
  155. }
  156. #endif
  157. Top = 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. }