ApplicationImpl.Lifecycle.cs 9.7 KB

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