Application.cs 8.2 KB

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