ApplicationImpl.Lifecycle.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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);
  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. private bool _isResetingState;
  120. /// <inheritdoc/>
  121. public void ResetState (bool ignoreDisposed = false)
  122. {
  123. _isResetingState = true;
  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. // === 0. Stop all timers ===
  128. TimedEvents?.StopAll ();
  129. // === 1. Stop all running toplevels ===
  130. foreach (Toplevel? t in SessionStack)
  131. {
  132. t!.Running = false;
  133. }
  134. // === 2. Close and dispose popover ===
  135. if (Popover?.GetActivePopover () is View popover)
  136. {
  137. // This forcefully closes the popover; invoking Command.Quit would be more graceful
  138. // but since this is shutdown, doing this is ok.
  139. popover.Visible = false;
  140. }
  141. // Any popovers added to Popover have their lifetime controlled by Popover
  142. Popover?.Dispose ();
  143. Popover = null;
  144. // === 3. Clean up toplevels ===
  145. SessionStack.Clear ();
  146. #if DEBUG_IDISPOSABLE
  147. // Don't dispose the Current. It's up to caller dispose it
  148. if (View.EnableDebugIDisposableAsserts && !ignoreDisposed && Current is { })
  149. {
  150. Debug.Assert (Current.WasDisposed, $"Title = {Current.Title}, Id = {Current.Id}");
  151. // If End wasn't called _CachedSessionTokenToplevel may be null
  152. if (CachedSessionTokenToplevel is { })
  153. {
  154. Debug.Assert (CachedSessionTokenToplevel.WasDisposed);
  155. Debug.Assert (CachedSessionTokenToplevel == Current);
  156. }
  157. }
  158. #endif
  159. Current = null;
  160. CachedSessionTokenToplevel = null;
  161. // === 4. Clean up driver ===
  162. if (Driver is { })
  163. {
  164. UnsubscribeDriverEvents ();
  165. Driver?.End ();
  166. Driver = null;
  167. }
  168. // Reset screen
  169. ResetScreen ();
  170. _screen = null;
  171. // === 5. Clear run state ===
  172. Iteration = null;
  173. SessionBegun = null;
  174. SessionEnded = null;
  175. StopAfterFirstIteration = false;
  176. ClearScreenNextIteration = false;
  177. // === 6. Reset input systems ===
  178. // Mouse and Keyboard will be lazy-initialized on next access
  179. _mouse = null;
  180. _keyboard = null;
  181. Mouse.ResetState ();
  182. // === 7. Clear navigation and screen state ===
  183. ScreenChanged = null;
  184. //Navigation = null;
  185. // === 8. Reset initialization state ===
  186. Initialized = false;
  187. MainThreadId = null;
  188. // === 9. Clear graphics ===
  189. Sixel.Clear ();
  190. // === 10. Reset ForceDriver ===
  191. // Note: ForceDriver and Force16Colors are reset
  192. // If they need to persist across Init/Shutdown cycles
  193. // then the user of the library should manage that state
  194. Force16Colors = false;
  195. ForceDriver = string.Empty;
  196. // === 11. Reset synchronization context ===
  197. // IMPORTANT: Always reset sync context, even if not initialized
  198. // This ensures cleanup works correctly even if Shutdown is called without Init
  199. // Reset synchronization context to allow the user to run async/await,
  200. // as the main loop has been ended, the synchronization context from
  201. // gui.cs does no longer process any callbacks. See #1084 for more details:
  202. // (https://github.com/gui-cs/Terminal.Gui/issues/1084).
  203. SynchronizationContext.SetSynchronizationContext (null);
  204. _isResetingState = false;
  205. }
  206. /// <summary>
  207. /// Raises the <see cref="InitializedChanged"/> event.
  208. /// </summary>
  209. internal void RaiseInitializedChanged (object sender, EventArgs<bool> e) { InitializedChanged?.Invoke (sender, e); }
  210. }