Application.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. #nullable enable
  2. // We use global using directives to simplify the code and avoid repetitive namespace declarations.
  3. // Put them here so they are available throughout the application.
  4. // Do not put them in AssemblyInfo.cs as it will break GitVersion's /updateassemblyinfo
  5. global using Attribute = Terminal.Gui.Drawing.Attribute;
  6. global using Color = Terminal.Gui.Drawing.Color;
  7. global using CM = Terminal.Gui.Configuration.ConfigurationManager;
  8. global using Terminal.Gui.App;
  9. global using Terminal.Gui.Drivers;
  10. global using Terminal.Gui.Input;
  11. global using Terminal.Gui.Configuration;
  12. global using Terminal.Gui.ViewBase;
  13. global using Terminal.Gui.Views;
  14. global using Terminal.Gui.Drawing;
  15. global using Terminal.Gui.Text;
  16. global using Terminal.Gui.Resources;
  17. global using Terminal.Gui.FileServices;
  18. using System.Diagnostics;
  19. using System.Globalization;
  20. using System.Reflection;
  21. using System.Resources;
  22. namespace Terminal.Gui.App;
  23. /// <summary>A static, singleton class representing the application. This class is the entry point for the application.</summary>
  24. /// <example>
  25. /// <code>
  26. /// Application.Init();
  27. /// var win = new Window()
  28. /// {
  29. /// Title = $"Example App ({Application.QuitKey} to quit)"
  30. /// };
  31. /// Application.Run(win);
  32. /// win.Dispose();
  33. /// Application.Shutdown();
  34. /// </code>
  35. /// </example>
  36. /// <remarks></remarks>
  37. public static partial class Application
  38. {
  39. /// <summary>Gets all cultures supported by the application without the invariant language.</summary>
  40. public static List<CultureInfo>? SupportedCultures { get; private set; } = GetSupportedCultures ();
  41. /// <summary>
  42. /// <para>
  43. /// Handles recurring events. These are invoked on the main UI thread - allowing for
  44. /// safe updates to <see cref="View"/> instances.
  45. /// </para>
  46. /// </summary>
  47. public static ITimedEvents? TimedEvents => ApplicationImpl.Instance?.TimedEvents;
  48. /// <summary>
  49. /// Gets a string representation of the Application as rendered by <see cref="Driver"/>.
  50. /// </summary>
  51. /// <returns>A string representation of the Application </returns>
  52. public new static string ToString ()
  53. {
  54. IConsoleDriver? driver = Driver;
  55. if (driver is null)
  56. {
  57. return string.Empty;
  58. }
  59. return ToString (driver);
  60. }
  61. /// <summary>
  62. /// Gets a string representation of the Application rendered by the provided <see cref="IConsoleDriver"/>.
  63. /// </summary>
  64. /// <param name="driver">The driver to use to render the contents.</param>
  65. /// <returns>A string representation of the Application </returns>
  66. public static string ToString (IConsoleDriver? driver)
  67. {
  68. if (driver is null)
  69. {
  70. return string.Empty;
  71. }
  72. var sb = new StringBuilder ();
  73. Cell [,] contents = driver?.Contents!;
  74. for (var r = 0; r < driver!.Rows; r++)
  75. {
  76. for (var c = 0; c < driver.Cols; c++)
  77. {
  78. Rune rune = contents [r, c].Rune;
  79. if (rune.DecodeSurrogatePair (out char []? sp))
  80. {
  81. sb.Append (sp);
  82. }
  83. else
  84. {
  85. sb.Append ((char)rune.Value);
  86. }
  87. if (rune.GetColumns () > 1)
  88. {
  89. c++;
  90. }
  91. // See Issue #2616
  92. //foreach (var combMark in contents [r, c].CombiningMarks) {
  93. // sb.Append ((char)combMark.Value);
  94. //}
  95. }
  96. sb.AppendLine ();
  97. }
  98. return sb.ToString ();
  99. }
  100. internal static List<CultureInfo> GetAvailableCulturesFromEmbeddedResources ()
  101. {
  102. ResourceManager rm = new (typeof (Strings));
  103. CultureInfo [] cultures = CultureInfo.GetCultures (CultureTypes.AllCultures);
  104. return cultures.Where (
  105. cultureInfo =>
  106. !cultureInfo.Equals (CultureInfo.InvariantCulture)
  107. && rm.GetResourceSet (cultureInfo, true, false) is { }
  108. )
  109. .ToList ();
  110. }
  111. // BUGBUG: This does not return en-US even though it's supported by default
  112. internal static List<CultureInfo> GetSupportedCultures ()
  113. {
  114. CultureInfo [] cultures = CultureInfo.GetCultures (CultureTypes.AllCultures);
  115. // Get the assembly
  116. var assembly = Assembly.GetExecutingAssembly ();
  117. //Find the location of the assembly
  118. string assemblyLocation = AppDomain.CurrentDomain.BaseDirectory;
  119. // Find the resource file name of the assembly
  120. var resourceFilename = $"{assembly.GetName ().Name}.resources.dll";
  121. if (cultures.Length > 1 && Directory.Exists (Path.Combine (assemblyLocation, "pt-PT")))
  122. {
  123. // Return all culture for which satellite folder found with culture code.
  124. return cultures.Where (
  125. cultureInfo =>
  126. Directory.Exists (Path.Combine (assemblyLocation, cultureInfo.Name))
  127. && File.Exists (Path.Combine (assemblyLocation, cultureInfo.Name, resourceFilename))
  128. )
  129. .ToList ();
  130. }
  131. // It's called from a self-contained single-file and get available cultures from the embedded resources strings.
  132. return GetAvailableCulturesFromEmbeddedResources ();
  133. }
  134. // IMPORTANT: Ensure all property/fields are reset here. See Init_ResetState_Resets_Properties unit test.
  135. // Encapsulate all setting of initial state for Application; Having
  136. // this in a function like this ensures we don't make mistakes in
  137. // guaranteeing that the state of this singleton is deterministic when Init
  138. // starts running and after Shutdown returns.
  139. internal static void ResetState (bool ignoreDisposed = false)
  140. {
  141. Navigation = new ();
  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. foreach (Toplevel? t in TopLevels)
  146. {
  147. t!.Running = false;
  148. }
  149. if (Popover?.GetActivePopover () is View popover)
  150. {
  151. // This forcefully closes the popover; invoking Command.Quit would be more graceful
  152. // but since this is shutdown, doing this is ok.
  153. popover.Visible = false;
  154. }
  155. Popover?.Dispose ();
  156. Popover = null;
  157. TopLevels.Clear ();
  158. #if DEBUG_IDISPOSABLE
  159. // Don't dispose the Top. It's up to caller dispose it
  160. if (View.EnableDebugIDisposableAsserts && !ignoreDisposed && Top is { })
  161. {
  162. Debug.Assert (Top.WasDisposed, $"Title = {Top.Title}, Id = {Top.Id}");
  163. // If End wasn't called _cachedRunStateToplevel may be null
  164. if (_cachedRunStateToplevel is { })
  165. {
  166. Debug.Assert (_cachedRunStateToplevel.WasDisposed);
  167. Debug.Assert (_cachedRunStateToplevel == Top);
  168. }
  169. }
  170. #endif
  171. Top = null;
  172. _cachedRunStateToplevel = null;
  173. // MainLoop stuff
  174. MainLoop?.Dispose ();
  175. MainLoop = null;
  176. MainThreadId = -1;
  177. Iteration = null;
  178. EndAfterFirstIteration = false;
  179. ClearScreenNextIteration = false;
  180. // Driver stuff
  181. if (Driver is { })
  182. {
  183. UnsubscribeDriverEvents ();
  184. Driver?.End ();
  185. Driver = null;
  186. }
  187. _screen = null;
  188. // Don't reset ForceDriver; it needs to be set before Init is called.
  189. //ForceDriver = string.Empty;
  190. //Force16Colors = false;
  191. _forceFakeConsole = false;
  192. // Run State stuff
  193. NotifyNewRunState = null;
  194. NotifyStopRunState = null;
  195. MouseGrabHandler = new MouseGrabHandler ();
  196. Initialized = false;
  197. // Mouse
  198. // Do not clear _lastMousePosition; Popover's require it to stay set with
  199. // last mouse pos.
  200. //_lastMousePosition = null;
  201. CachedViewsUnderMouse.Clear ();
  202. MouseEvent = null;
  203. // Keyboard
  204. KeyDown = null;
  205. KeyUp = null;
  206. SizeChanging = null;
  207. Navigation = null;
  208. KeyBindings.Clear ();
  209. AddKeyBindings ();
  210. // Reset synchronization context to allow the user to run async/await,
  211. // as the main loop has been ended, the synchronization context from
  212. // gui.cs does no longer process any callbacks. See #1084 for more details:
  213. // (https://github.com/gui-cs/Terminal.Gui/issues/1084).
  214. SynchronizationContext.SetSynchronizationContext (null);
  215. }
  216. }