Application.cs 8.9 KB

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