Application.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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. internal static List<CultureInfo> GetSupportedCultures ()
  90. {
  91. CultureInfo [] cultures = CultureInfo.GetCultures (CultureTypes.AllCultures);
  92. // Get the assembly
  93. var assembly = Assembly.GetExecutingAssembly ();
  94. //Find the location of the assembly
  95. string assemblyLocation = AppDomain.CurrentDomain.BaseDirectory;
  96. // Find the resource file name of the assembly
  97. var resourceFilename = $"{assembly.GetName ().Name}.resources.dll";
  98. if (cultures.Length > 1 && Directory.Exists (Path.Combine (assemblyLocation, "pt-PT")))
  99. {
  100. // Return all culture for which satellite folder found with culture code.
  101. return cultures.Where (
  102. cultureInfo =>
  103. Directory.Exists (Path.Combine (assemblyLocation, cultureInfo.Name))
  104. && File.Exists (Path.Combine (assemblyLocation, cultureInfo.Name, resourceFilename))
  105. )
  106. .ToList ();
  107. }
  108. // It's called from a self-contained single-file and get available cultures from the embedded resources strings.
  109. return GetAvailableCulturesFromEmbeddedResources ();
  110. }
  111. // IMPORTANT: Ensure all property/fields are reset here. See Init_ResetState_Resets_Properties unit test.
  112. // Encapsulate all setting of initial state for Application; Having
  113. // this in a function like this ensures we don't make mistakes in
  114. // guaranteeing that the state of this singleton is deterministic when Init
  115. // starts running and after Shutdown returns.
  116. internal static void ResetState (bool ignoreDisposed = false)
  117. {
  118. Application.Navigation = new ApplicationNavigation ();
  119. // Shutdown is the bookend for Init. As such it needs to clean up all resources
  120. // Init created. Apps that do any threading will need to code defensively for this.
  121. // e.g. see Issue #537
  122. foreach (Toplevel? t in TopLevels)
  123. {
  124. t!.Running = false;
  125. }
  126. TopLevels.Clear ();
  127. #if DEBUG_IDISPOSABLE
  128. // Don't dispose the Top. It's up to caller dispose it
  129. if (!ignoreDisposed && Top is { })
  130. {
  131. Debug.Assert (Top.WasDisposed);
  132. // If End wasn't called _cachedRunStateToplevel may be null
  133. if (_cachedRunStateToplevel is { })
  134. {
  135. Debug.Assert (_cachedRunStateToplevel.WasDisposed);
  136. Debug.Assert (_cachedRunStateToplevel == Top);
  137. }
  138. }
  139. #endif
  140. Top = null;
  141. _cachedRunStateToplevel = null;
  142. // MainLoop stuff
  143. MainLoop?.Dispose ();
  144. MainLoop = null;
  145. MainThreadId = -1;
  146. Iteration = null;
  147. EndAfterFirstIteration = false;
  148. // Driver stuff
  149. if (Driver is { })
  150. {
  151. UnsubscribeDriverEvents ();
  152. Driver?.End ();
  153. Driver = null;
  154. }
  155. _screen = null;
  156. // Don't reset ForceDriver; it needs to be set before Init is called.
  157. //ForceDriver = string.Empty;
  158. //Force16Colors = false;
  159. _forceFakeConsole = false;
  160. // Run State stuff
  161. NotifyNewRunState = null;
  162. NotifyStopRunState = null;
  163. MouseGrabView = null;
  164. Initialized = false;
  165. // Mouse
  166. _lastMousePosition = null;
  167. _cachedViewsUnderMouse.Clear ();
  168. WantContinuousButtonPressedView = null;
  169. MouseEvent = null;
  170. GrabbedMouse = null;
  171. UnGrabbingMouse = null;
  172. GrabbedMouse = null;
  173. UnGrabbedMouse = null;
  174. // Keyboard
  175. KeyDown = null;
  176. KeyUp = null;
  177. SizeChanging = null;
  178. Navigation = null;
  179. ClearScreenNextIteration = false;
  180. KeyBindings.Clear ();
  181. AddKeyBindings ();
  182. // Reset synchronization context to allow the user to run async/await,
  183. // as the main loop has been ended, the synchronization context from
  184. // gui.cs does no longer process any callbacks. See #1084 for more details:
  185. // (https://github.com/gui-cs/Terminal.Gui/issues/1084).
  186. SynchronizationContext.SetSynchronizationContext (null);
  187. }
  188. /// <summary>
  189. /// Adds specified idle handler function to main iteration processing. The handler function will be called
  190. /// once per iteration of the main loop after other events have been handled.
  191. /// </summary>
  192. public static void AddIdle (Func<bool> func) => ApplicationImpl.Instance.AddIdle (func);
  193. }