Application.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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; }
  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. ConsoleDriver 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="ConsoleDriver"/>.
  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 (ConsoleDriver driver)
  45. {
  46. var sb = new StringBuilder ();
  47. Cell [,] contents = driver.Contents;
  48. for (var r = 0; r < driver.Rows; r++)
  49. {
  50. for (var c = 0; c < driver.Cols; c++)
  51. {
  52. Rune rune = contents [r, c].Rune;
  53. if (rune.DecodeSurrogatePair (out char [] sp))
  54. {
  55. sb.Append (sp);
  56. }
  57. else
  58. {
  59. sb.Append ((char)rune.Value);
  60. }
  61. if (rune.GetColumns () > 1)
  62. {
  63. c++;
  64. }
  65. // See Issue #2616
  66. //foreach (var combMark in contents [r, c].CombiningMarks) {
  67. // sb.Append ((char)combMark.Value);
  68. //}
  69. }
  70. sb.AppendLine ();
  71. }
  72. return sb.ToString ();
  73. }
  74. internal static List<CultureInfo> GetAvailableCulturesFromEmbeddedResources ()
  75. {
  76. ResourceManager rm = new (typeof (Strings));
  77. CultureInfo [] cultures = CultureInfo.GetCultures (CultureTypes.AllCultures);
  78. return cultures.Where (
  79. cultureInfo =>
  80. !cultureInfo.Equals (CultureInfo.InvariantCulture)
  81. && rm.GetResourceSet (cultureInfo, true, false) is { }
  82. )
  83. .ToList ();
  84. }
  85. internal static List<CultureInfo> GetSupportedCultures ()
  86. {
  87. CultureInfo [] cultures = CultureInfo.GetCultures (CultureTypes.AllCultures);
  88. // Get the assembly
  89. var assembly = Assembly.GetExecutingAssembly ();
  90. //Find the location of the assembly
  91. string assemblyLocation = AppDomain.CurrentDomain.BaseDirectory;
  92. // Find the resource file name of the assembly
  93. var resourceFilename = $"{assembly.GetName ().Name}.resources.dll";
  94. if (cultures.Length > 1 && Directory.Exists (Path.Combine (assemblyLocation, "pt-PT")))
  95. {
  96. // Return all culture for which satellite folder found with culture code.
  97. return cultures.Where (
  98. cultureInfo =>
  99. Directory.Exists (Path.Combine (assemblyLocation, cultureInfo.Name))
  100. && File.Exists (Path.Combine (assemblyLocation, cultureInfo.Name, resourceFilename))
  101. )
  102. .ToList ();
  103. }
  104. // It's called from a self-contained single-file and get available cultures from the embedded resources strings.
  105. return GetAvailableCulturesFromEmbeddedResources ();
  106. }
  107. // IMPORTANT: Ensure all property/fields are reset here. See Init_ResetState_Resets_Properties unit test.
  108. // Encapsulate all setting of initial state for Application; Having
  109. // this in a function like this ensures we don't make mistakes in
  110. // guaranteeing that the state of this singleton is deterministic when Init
  111. // starts running and after Shutdown returns.
  112. internal static void ResetState (bool ignoreDisposed = false)
  113. {
  114. // Shutdown is the bookend for Init. As such it needs to clean up all resources
  115. // Init created. Apps that do any threading will need to code defensively for this.
  116. // e.g. see Issue #537
  117. foreach (Toplevel? t in TopLevels)
  118. {
  119. t!.Running = false;
  120. }
  121. TopLevels.Clear ();
  122. Current = null;
  123. #if DEBUG_IDISPOSABLE
  124. // Don't dispose the Top. It's up to caller dispose it
  125. if (!ignoreDisposed && Top is { })
  126. {
  127. Debug.Assert (Top.WasDisposed);
  128. // If End wasn't called _cachedRunStateToplevel may be null
  129. if (_cachedRunStateToplevel is { })
  130. {
  131. Debug.Assert (_cachedRunStateToplevel.WasDisposed);
  132. Debug.Assert (_cachedRunStateToplevel == Top);
  133. }
  134. }
  135. #endif
  136. Top = null;
  137. _cachedRunStateToplevel = null;
  138. // MainLoop stuff
  139. MainLoop?.Dispose ();
  140. MainLoop = null;
  141. MainThreadId = -1;
  142. Iteration = null;
  143. EndAfterFirstIteration = false;
  144. // Driver stuff
  145. if (Driver is { })
  146. {
  147. Driver.SizeChanged -= Driver_SizeChanged;
  148. Driver.KeyDown -= Driver_KeyDown;
  149. Driver.KeyUp -= Driver_KeyUp;
  150. Driver.MouseEvent -= Driver_MouseEvent;
  151. Driver?.End ();
  152. Driver = null;
  153. }
  154. // Don't reset ForceDriver; it needs to be set before Init is called.
  155. //ForceDriver = string.Empty;
  156. //Force16Colors = false;
  157. _forceFakeConsole = false;
  158. // Run State stuff
  159. NotifyNewRunState = null;
  160. NotifyStopRunState = null;
  161. MouseGrabView = null;
  162. IsInitialized = false;
  163. // Mouse
  164. MouseEnteredView = null;
  165. WantContinuousButtonPressedView = null;
  166. MouseEvent = null;
  167. GrabbedMouse = null;
  168. UnGrabbingMouse = null;
  169. GrabbedMouse = null;
  170. UnGrabbedMouse = null;
  171. // Keyboard
  172. KeyDown = null;
  173. KeyUp = null;
  174. SizeChanging = null;
  175. Navigation = null;
  176. AddApplicationKeyBindings ();
  177. Colors.Reset ();
  178. // Reset synchronization context to allow the user to run async/await,
  179. // as the main loop has been ended, the synchronization context from
  180. // gui.cs does no longer process any callbacks. See #1084 for more details:
  181. // (https://github.com/gui-cs/Terminal.Gui/issues/1084).
  182. SynchronizationContext.SetSynchronizationContext (null);
  183. }
  184. // Only return true if the Current has changed.
  185. }