Application.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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. /// Maximum number of iterations of the main loop (and hence draws)
  50. /// to allow to occur per second. Defaults to <see cref="DefaultMaximumIterationsPerSecond"/>> which is a 40ms sleep
  51. /// after iteration (factoring in how long iteration took to run).
  52. /// <remarks>Note that not every iteration draws (see <see cref="View.NeedsDraw"/>).
  53. /// Only affects v2 drivers.</remarks>
  54. /// </summary>
  55. public static ushort MaximumIterationsPerSecond = DefaultMaximumIterationsPerSecond;
  56. /// <summary>
  57. /// Default value for <see cref="MaximumIterationsPerSecond"/>
  58. /// </summary>
  59. public const ushort DefaultMaximumIterationsPerSecond = 25;
  60. /// <summary>
  61. /// Gets a string representation of the Application as rendered by <see cref="Driver"/>.
  62. /// </summary>
  63. /// <returns>A string representation of the Application </returns>
  64. public new static string ToString ()
  65. {
  66. IConsoleDriver? driver = Driver;
  67. if (driver is null)
  68. {
  69. return string.Empty;
  70. }
  71. return ToString (driver);
  72. }
  73. /// <summary>
  74. /// Gets a string representation of the Application rendered by the provided <see cref="IConsoleDriver"/>.
  75. /// </summary>
  76. /// <param name="driver">The driver to use to render the contents.</param>
  77. /// <returns>A string representation of the Application </returns>
  78. public static string ToString (IConsoleDriver? driver)
  79. {
  80. if (driver is null)
  81. {
  82. return string.Empty;
  83. }
  84. var sb = new StringBuilder ();
  85. Cell [,] contents = driver?.Contents!;
  86. for (var r = 0; r < driver!.Rows; r++)
  87. {
  88. for (var c = 0; c < driver.Cols; c++)
  89. {
  90. Rune rune = contents [r, c].Rune;
  91. if (rune.DecodeSurrogatePair (out char []? sp))
  92. {
  93. sb.Append (sp);
  94. }
  95. else
  96. {
  97. sb.Append ((char)rune.Value);
  98. }
  99. if (rune.GetColumns () > 1)
  100. {
  101. c++;
  102. }
  103. // See Issue #2616
  104. //foreach (var combMark in contents [r, c].CombiningMarks) {
  105. // sb.Append ((char)combMark.Value);
  106. //}
  107. }
  108. sb.AppendLine ();
  109. }
  110. return sb.ToString ();
  111. }
  112. internal static List<CultureInfo> GetAvailableCulturesFromEmbeddedResources ()
  113. {
  114. ResourceManager rm = new (typeof (Strings));
  115. CultureInfo [] cultures = CultureInfo.GetCultures (CultureTypes.AllCultures);
  116. return cultures.Where (
  117. cultureInfo =>
  118. !cultureInfo.Equals (CultureInfo.InvariantCulture)
  119. && rm.GetResourceSet (cultureInfo, true, false) is { }
  120. )
  121. .ToList ();
  122. }
  123. // BUGBUG: This does not return en-US even though it's supported by default
  124. internal static List<CultureInfo> GetSupportedCultures ()
  125. {
  126. CultureInfo [] cultures = CultureInfo.GetCultures (CultureTypes.AllCultures);
  127. // Get the assembly
  128. var assembly = Assembly.GetExecutingAssembly ();
  129. //Find the location of the assembly
  130. string assemblyLocation = AppDomain.CurrentDomain.BaseDirectory;
  131. // Find the resource file name of the assembly
  132. var resourceFilename = $"{assembly.GetName ().Name}.resources.dll";
  133. if (cultures.Length > 1 && Directory.Exists (Path.Combine (assemblyLocation, "pt-PT")))
  134. {
  135. // Return all culture for which satellite folder found with culture code.
  136. return cultures.Where (
  137. cultureInfo =>
  138. Directory.Exists (Path.Combine (assemblyLocation, cultureInfo.Name))
  139. && File.Exists (Path.Combine (assemblyLocation, cultureInfo.Name, resourceFilename))
  140. )
  141. .ToList ();
  142. }
  143. // It's called from a self-contained single-file and get available cultures from the embedded resources strings.
  144. return GetAvailableCulturesFromEmbeddedResources ();
  145. }
  146. // IMPORTANT: Ensure all property/fields are reset here. See Init_ResetState_Resets_Properties unit test.
  147. // Encapsulate all setting of initial state for Application; Having
  148. // this in a function like this ensures we don't make mistakes in
  149. // guaranteeing that the state of this singleton is deterministic when Init
  150. // starts running and after Shutdown returns.
  151. internal static void ResetState (bool ignoreDisposed = false)
  152. {
  153. // Shutdown is the bookend for Init. As such it needs to clean up all resources
  154. // Init created. Apps that do any threading will need to code defensively for this.
  155. // e.g. see Issue #537
  156. foreach (Toplevel? t in TopLevels)
  157. {
  158. t!.Running = false;
  159. }
  160. if (Popover?.GetActivePopover () is View popover)
  161. {
  162. // This forcefully closes the popover; invoking Command.Quit would be more graceful
  163. // but since this is shutdown, doing this is ok.
  164. popover.Visible = false;
  165. }
  166. Popover?.Dispose ();
  167. Popover = null;
  168. TopLevels.Clear ();
  169. #if DEBUG_IDISPOSABLE
  170. // Don't dispose the Top. It's up to caller dispose it
  171. if (View.EnableDebugIDisposableAsserts && !ignoreDisposed && Top is { })
  172. {
  173. Debug.Assert (Top.WasDisposed, $"Title = {Top.Title}, Id = {Top.Id}");
  174. // If End wasn't called _cachedRunStateToplevel may be null
  175. if (CachedRunStateToplevel is { })
  176. {
  177. Debug.Assert (CachedRunStateToplevel.WasDisposed);
  178. Debug.Assert (CachedRunStateToplevel == Top);
  179. }
  180. }
  181. #endif
  182. Top = null;
  183. CachedRunStateToplevel = null;
  184. MainThreadId = -1;
  185. Iteration = null;
  186. EndAfterFirstIteration = false;
  187. ClearScreenNextIteration = false;
  188. // Driver stuff
  189. if (Driver is { })
  190. {
  191. UnsubscribeDriverEvents ();
  192. Driver?.End ();
  193. Driver = null;
  194. }
  195. // Reset Screen to null so it will be recalculated on next access
  196. // Note: ApplicationImpl.Shutdown() also calls ResetScreen() before calling this method
  197. // to avoid potential circular reference issues. Calling it twice is harmless.
  198. if (ApplicationImpl.Instance is ApplicationImpl impl)
  199. {
  200. impl.ResetScreen ();
  201. }
  202. // Don't reset ForceDriver; it needs to be set before Init is called.
  203. //ForceDriver = string.Empty;
  204. //Force16Colors = false;
  205. _forceFakeConsole = false;
  206. // Run State stuff
  207. NotifyNewRunState = null;
  208. NotifyStopRunState = null;
  209. // Mouse and Keyboard will be lazy-initialized in ApplicationImpl on next access
  210. Initialized = false;
  211. // Mouse
  212. // Do not clear _lastMousePosition; Popovers require it to stay set with
  213. // last mouse pos.
  214. //_lastMousePosition = null;
  215. CachedViewsUnderMouse.Clear ();
  216. ResetMouseState ();
  217. // Keyboard events and bindings are now managed by the Keyboard instance
  218. ScreenChanged = null;
  219. Navigation = null;
  220. // Reset synchronization context to allow the user to run async/await,
  221. // as the main loop has been ended, the synchronization context from
  222. // gui.cs does no longer process any callbacks. See #1084 for more details:
  223. // (https://github.com/gui-cs/Terminal.Gui/issues/1084).
  224. SynchronizationContext.SetSynchronizationContext (null);
  225. }
  226. }